Implement clippy suggestions

This commit is contained in:
Henry Schimke
2023-01-04 14:48:16 -06:00
parent c65eadf102
commit 48287631dd
196 changed files with 2465 additions and 2574 deletions

View File

@@ -44,12 +44,10 @@ fn loadImage(fileName: &str) -> DynamicImage {
file.exists(),
"Please download and install test images, and run from the 'core' directory"
);
DynamicImage::from(
image::io::Reader::open(file)
.expect("image should load")
.decode()
.expect("decode"),
)
image::io::Reader::open(file)
.expect("image should load")
.decode()
.expect("decode")
}
// In case the golden images are not monochromatic, convert the RGB values to greyscale.
@@ -58,8 +56,8 @@ fn createMatrixFromImage(image: DynamicImage) -> BitMatrix {
let height = image.height() as usize;
// let pixels = vec![0u32; width * height]; //new int[width * height];
// image.getRGB(0, 0, width, height, pixels, 0, width);
let img_src = DynamicImage::from(image).into_rgb8(); //image.as_rgb8().unwrap().as_bytes();
// let pixels = img_src.as_bytes();
let img_src = image.into_rgb8(); //image.as_rgb8().unwrap().as_bytes();
// let pixels = img_src.as_bytes();
let mut matrix = BitMatrix::new(width as u32, height as u32).expect("create new bitmatrix");
for y in 0..height as u32 {
@@ -70,11 +68,11 @@ fn createMatrixFromImage(image: DynamicImage) -> BitMatrix {
let [red, green, blue] = img_src.get_pixel(x, y).0;
let luminance = (306 * red as u32 + 601 * green as u32 + 117 * blue as u32) >> 10;
if luminance <= 0x7F {
matrix.set(x as u32, y as u32);
matrix.set(x, y);
}
}
}
return matrix;
matrix
}
#[test]

View File

@@ -43,7 +43,7 @@ fn checkVersion(version: Result<&Version, Exceptions>, number: u32, dimension: u
assert_eq!(number, version.getVersionNumber());
// assertNotNull(version.getAlignmentPatternCenters());
if number > 1 {
assert!(version.getAlignmentPatternCenters().len() > 0);
assert!(!version.getAlignmentPatternCenters().is_empty());
}
assert_eq!(dimension, version.getDimensionForVersion());
let _tmp = version.getECBlocksForLevel(ErrorCorrectionLevel::H);

View File

@@ -36,10 +36,10 @@ impl BitMatrixParser {
pub fn new(bit_matrix: BitMatrix) -> Result<Self, Exceptions> {
let dimension = bit_matrix.getHeight();
if dimension < 21 || (dimension & 0x03) != 1 {
Err(Exceptions::FormatException(format!(
Err(Exceptions::FormatException(Some(format!(
"{} < 21 || ({} % 0x03) != 1",
dimension, dimension
)))
))))
} else {
Ok(Self {
bitMatrix: bit_matrix,
@@ -59,7 +59,7 @@ impl BitMatrixParser {
*/
pub fn readFormatInformation(&mut self) -> Result<&FormatInformation, Exceptions> {
if self.parsedFormatInfo.is_some() {
return Ok(&self.parsedFormatInfo.as_ref().unwrap());
return Ok(self.parsedFormatInfo.as_ref().unwrap());
}
// Read top-left format info bits
@@ -96,7 +96,7 @@ impl BitMatrixParser {
if let Some(pfi) = &self.parsedFormatInfo {
return Ok(pfi);
}
Err(Exceptions::FormatException("".to_owned()))
Err(Exceptions::FormatException(None))
}
/**
@@ -108,7 +108,7 @@ impl BitMatrixParser {
*/
pub fn readVersion(&mut self) -> Result<VersionRef, Exceptions> {
if let Some(pv) = self.parsedVersion {
return Ok(&pv);
return Ok(pv);
}
let dimension = self.bitMatrix.getHeight();
@@ -152,7 +152,7 @@ impl BitMatrixParser {
return Ok(theParsedVersion);
}
}
Err(Exceptions::FormatException("".to_owned()))
Err(Exceptions::FormatException(None))
}
fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 {
@@ -236,7 +236,7 @@ impl BitMatrixParser {
}
if resultOffset != version.getTotalCodewords() as usize {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
Ok(result)
}
@@ -250,7 +250,7 @@ impl BitMatrixParser {
let dimension = self.bitMatrix.getHeight();
dataMask.unmaskBitMatrix(&mut self.bitMatrix, dimension);
} else {
return; // We have no format information, and have no data mask
// We have no format information, and have no data mask
}
// if self.parsedFormatInfo.is_none() {
// return; // We have no format information, and have no data mask

View File

@@ -55,7 +55,7 @@ impl DataBlock {
ecLevel: ErrorCorrectionLevel,
) -> Result<Vec<Self>, Exceptions> {
if rawCodewords.len() as u32 != version.getTotalCodewords() {
return Err(Exceptions::IllegalArgumentException("".to_owned()));
return Err(Exceptions::IllegalArgumentException(None));
}
// Figure out the number and size of data blocks used by this version and
@@ -109,26 +109,32 @@ impl DataBlock {
let mut rawCodewordsOffset = 0;
for i in 0..shorterBlocksNumDataCodewords {
// for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
for j in 0..numRXingResultBlocks {
for result_j in result.iter_mut().take(numRXingResultBlocks) {
// for j in 0..numRXingResultBlocks {
// for (int j = 0; j < numRXingResultBlocks; j++) {
result[j].codewords[i] = rawCodewords[rawCodewordsOffset];
result_j.codewords[i] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
}
// Fill out the last data block in the longer ones
for j in longerBlocksStartAt..numRXingResultBlocks {
for res in result
.iter_mut()
.take(numRXingResultBlocks)
.skip(longerBlocksStartAt)
{
// for j in longerBlocksStartAt..numRXingResultBlocks {
// for (int j = longerBlocksStartAt; j < numRXingResultBlocks; j++) {
result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset];
res.codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
// Now add in error correction blocks
let max = result[0].codewords.len();
for i in shorterBlocksNumDataCodewords..max {
// for (int i = shorterBlocksNumDataCodewords; i < max; i++) {
for j in 0..numRXingResultBlocks {
for (j, res) in result.iter_mut().enumerate().take(numRXingResultBlocks) {
// for (int j = 0; j < numRXingResultBlocks; j++) {
let iOffset = if j < longerBlocksStartAt { i } else { i + 1 };
result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset];
res.codewords[iOffset] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
}

View File

@@ -230,10 +230,10 @@ impl TryFrom<u8> for DataMask {
5 => Ok(DataMask::DATA_MASK_101),
6 => Ok(DataMask::DATA_MASK_110),
7 => Ok(DataMask::DATA_MASK_111),
_ => Err(Exceptions::IllegalArgumentException(format!(
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
"{} is not between 0 and 7",
value
))),
)))),
}
}
}

View File

@@ -37,12 +37,12 @@ const ALPHANUMERIC_CHARS: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
const GB2312_SUBSET: u32 = 1;
pub fn decode(
bytes: &Vec<u8>,
bytes: &[u8],
version: VersionRef,
ecLevel: ErrorCorrectionLevel,
hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> {
let mut bits = BitSource::new(bytes.clone());
let mut bits = BitSource::new(bytes.to_owned());
let mut result = String::with_capacity(50);
let mut byteSegments = vec![vec![0u8; 0]; 0];
let mut symbolSequence = -1i32;
@@ -77,10 +77,10 @@ pub fn decode(
}
Mode::STRUCTURED_APPEND => {
if bits.available() < 16 {
return Err(Exceptions::FormatException(format!(
return Err(Exceptions::FormatException(Some(format!(
"Mode::Structured append expected bits.available() < 16, found bits of {}",
bits.available()
)));
))));
}
// sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
@@ -92,10 +92,10 @@ pub fn decode(
let value = parseECIValue(&mut bits)?;
currentCharacterSetECI = Some(CharacterSetECI::getCharacterSetECIByValue(value)?);
if currentCharacterSetECI.is_none() {
return Err(Exceptions::FormatException(format!(
return Err(Exceptions::FormatException(Some(format!(
"Value of {} not valid",
value
)));
))));
}
}
Mode::HANZI => {
@@ -126,7 +126,7 @@ pub fn decode(
hints,
)?,
Mode::KANJI => decodeKanjiSegment(&mut bits, &mut result, count)?,
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
}
@@ -144,14 +144,12 @@ pub fn decode(
} else {
symbologyModifier = 2;
}
} else if hasFNC1first {
symbologyModifier = 3;
} else if hasFNC1second {
symbologyModifier = 5;
} else {
if hasFNC1first {
symbologyModifier = 3;
} else if hasFNC1second {
symbologyModifier = 5;
} else {
symbologyModifier = 1;
}
symbologyModifier = 1;
}
// } catch (IllegalArgumentException iae) {
@@ -160,7 +158,7 @@ pub fn decode(
// }
Ok(DecoderRXingResult::with_all(
bytes.clone(),
bytes.to_owned(),
result,
byteSegments.to_vec(),
format!("{}", u8::from(ecLevel)),
@@ -180,7 +178,7 @@ fn decodeHanziSegment(
) -> Result<(), Exceptions> {
// Don't crash trying to read more bits than we have available.
if count * 13 > bits.available() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -222,7 +220,7 @@ fn decodeKanjiSegment(
) -> Result<(), Exceptions> {
// Don't crash trying to read more bits than we have available.
if count * 13 > bits.available() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -266,25 +264,26 @@ fn decodeByteSegment(
) -> Result<(), Exceptions> {
// Don't crash trying to read more bits than we have available.
if 8 * count > bits.available() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let mut readBytes = vec![0u8; count];
for i in 0..count {
for byte in readBytes.iter_mut().take(count) {
// for i in 0..count {
// for (int i = 0; i < count; i++) {
readBytes[i] = bits.readBits(8)? as u8;
*byte = bits.readBits(8)? as u8;
}
let encoding;
if currentCharacterSetECI.is_none() {
let encoding = if currentCharacterSetECI.is_none() {
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils::guessCharset(&readBytes, &hints);
StringUtils::guessCharset(&readBytes, hints)
} else {
encoding = CharacterSetECI::getCharset(currentCharacterSetECI.as_ref().unwrap());
}
CharacterSetECI::getCharset(currentCharacterSetECI.as_ref().unwrap())
};
let encode_string = if currentCharacterSetECI.is_some()
&& currentCharacterSetECI.as_ref().unwrap() == &CharacterSetECI::Cp437
@@ -312,7 +311,7 @@ fn decodeByteSegment(
fn toAlphaNumericChar(value: u32) -> Result<char, Exceptions> {
if value as usize >= ALPHANUMERIC_CHARS.len() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
Ok(ALPHANUMERIC_CHARS.chars().nth(value as usize).unwrap())
}
@@ -328,7 +327,7 @@ fn decodeAlphanumericSegment(
let mut count = count;
while count > 1 {
if bits.available() < 11 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let nextTwoCharsBits = bits.readBits(11)?;
result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?);
@@ -338,7 +337,7 @@ fn decodeAlphanumericSegment(
if count == 1 {
// special case: one character left
if bits.available() < 6 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
result.push(toAlphaNumericChar(bits.readBits(6)?)?);
}
@@ -374,11 +373,11 @@ fn decodeNumericSegment(
while count >= 3 {
// Each 10 bits encodes three digits
if bits.available() < 10 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let threeDigitsBits = bits.readBits(10)?;
if threeDigitsBits >= 1000 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
result.push(toAlphaNumericChar(threeDigitsBits / 100)?);
result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?);
@@ -388,22 +387,22 @@ fn decodeNumericSegment(
if count == 2 {
// Two digits left over to read, encoded in 7 bits
if bits.available() < 7 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let twoDigitsBits = bits.readBits(7)?;
if twoDigitsBits >= 100 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
result.push(toAlphaNumericChar(twoDigitsBits / 10)?);
result.push(toAlphaNumericChar(twoDigitsBits % 10)?);
} else if count == 1 {
// One digit left over to read
if bits.available() < 4 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let digitBits = bits.readBits(4)?;
if digitBits >= 10 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
result.push(toAlphaNumericChar(digitBits)?);
}
@@ -428,5 +427,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result<u32, Exceptions> {
return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes);
}
Err(Exceptions::FormatException("".to_owned()))
Err(Exceptions::FormatException(None))
}

View File

@@ -124,8 +124,8 @@ pub fn decode_bitmatrix_with_hints(
Ok(res) => Ok(res),
Err(er) => match er {
Exceptions::FormatException(_) | Exceptions::ChecksumException(_) => {
if fe.is_some() {
Err(fe.unwrap())
if let Some(fe) = fe {
Err(fe)
} else {
Err(ce.unwrap())
}
@@ -170,9 +170,10 @@ fn decode_bitmatrix_parser_with_hints(
let mut codewordBytes = dataBlock.getCodewords().to_vec();
let numDataCodewords = dataBlock.getNumDataCodewords() as usize;
correctErrors(&mut codewordBytes, numDataCodewords)?;
for i in 0..numDataCodewords {
for codeword_byte in codewordBytes.iter().take(numDataCodewords) {
// for i in 0..numDataCodewords {
// for (int i = 0; i < numDataCodewords; i++) {
resultBytes[resultOffset] = codewordBytes[i];
resultBytes[resultOffset] = *codeword_byte; //codewordBytes[i];
resultOffset += 1;
}
}
@@ -193,20 +194,21 @@ fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<()
let numCodewords = codewordBytes.len();
// First read into an array of ints
let mut codewordsInts = vec![0u8; numCodewords];
for i in 0..numCodewords {
// for (int i = 0; i < numCodewords; i++) {
codewordsInts[i] = codewordBytes[i]; // & 0xFF;
}
// for i in 0..numCodewords {
// // for (int i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i]; // & 0xFF;
// }
codewordsInts[..numCodewords].copy_from_slice(&codewordBytes[..numCodewords]);
let mut sending_code_words: Vec<i32> = codewordsInts.iter().map(|x| *x as i32).collect();
if let Err(e) = RS_DECODER.decode(
if let Err(Exceptions::ReedSolomonException(error_str)) = RS_DECODER.decode(
&mut sending_code_words,
(codewordBytes.len() - numDataCodewords) as i32,
) {
if let Exceptions::ReedSolomonException(error_str) = e {
return Err(Exceptions::ChecksumException(error_str));
}
// if let Exceptions::ReedSolomonException(error_str) = e {
return Err(Exceptions::ChecksumException(error_str));
// }
}
// Copy back into array of bytes -- only need to worry about the bytes that were data

View File

@@ -47,10 +47,10 @@ impl ErrorCorrectionLevel {
1 => Ok(Self::L),
2 => Ok(Self::H),
3 => Ok(Self::Q),
_ => Err(Exceptions::IllegalArgumentException(format!(
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
"{} is not a valid bit selection",
bits
))),
)))),
}
}
@@ -101,19 +101,19 @@ impl FromStr for ErrorCorrectionLevel {
};
// If we find something, cool, return it, otherwise keep trying as numbers
if as_str.is_some() {
return Ok(as_str.unwrap());
if let Some(as_str) = as_str {
return Ok(as_str);
}
let number_possible = s.parse::<u8>();
if number_possible.is_ok() {
return number_possible.unwrap().try_into();
if let Ok(number_possible) = number_possible {
return number_possible.try_into();
}
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"could not parse {} into an ec level",
s
)));
))));
}
}

View File

@@ -68,10 +68,10 @@ impl Mode {
{
Ok(Self::HANZI)
}
_ => Err(Exceptions::IllegalArgumentException(format!(
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
"{} is not valid",
bits
))),
)))),
}
}

View File

@@ -45,9 +45,7 @@ impl QRCodeDecoderMetaData {
if !self.0 || points.is_empty() || points.len() < 3 {
return;
}
let bottom_left = points[0];
points[0] = points[2];
points[2] = bottom_left;
points.swap(0, 2);
// No need to 'fix' top-left and alignment pattern.
}
}

View File

@@ -105,9 +105,9 @@ impl Version {
dimension: u32,
) -> Result<&'static Version, Exceptions> {
if dimension % 4 != 1 {
return Err(Exceptions::FormatException(
return Err(Exceptions::FormatException(Some(
"dimension incorrect".to_owned(),
));
)));
}
Self::getVersionForNumber((dimension - 17) / 4)
// try {
@@ -118,10 +118,10 @@ impl Version {
}
pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> {
if versionNumber < 1 || versionNumber > 40 {
return Err(Exceptions::IllegalArgumentException(
if !(1..=40).contains(&versionNumber) {
return Err(Exceptions::IllegalArgumentException(Some(
"version out of spec".to_owned(),
));
)));
}
Ok(&VERSIONS[versionNumber as usize - 1])
}
@@ -150,7 +150,7 @@ impl Version {
return Self::getVersionForNumber(bestVersion);
}
// If we didn't find a close enough match, fail
Err(Exceptions::NotFoundException("could not find".to_owned()))
Err(Exceptions::NotFoundException(None))
}
/**

View File

@@ -64,7 +64,7 @@ impl AlignmentPattern {
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize;
}
return false;
false
}
/**

View File

@@ -124,9 +124,10 @@ impl AlignmentPatternFinder {
// A winner?
if self.foundPatternCross(&stateCount) {
// Yes
let confirmed = self.handlePossibleCenter(&stateCount, i, j);
if confirmed.is_some() {
return Ok(confirmed.unwrap());
if let Some(confirmed) =
self.handlePossibleCenter(&stateCount, i, j)
{
return Ok(confirmed);
}
}
stateCount[0] = stateCount[2];
@@ -149,9 +150,8 @@ impl AlignmentPatternFinder {
j += 1;
}
if self.foundPatternCross(&stateCount) {
let confirmed = self.handlePossibleCenter(&stateCount, i, maxJ);
if confirmed.is_some() {
return Ok(confirmed.unwrap());
if let Some(confirmed) = self.handlePossibleCenter(&stateCount, i, maxJ) {
return Ok(confirmed);
}
}
}
@@ -159,12 +159,10 @@ impl AlignmentPatternFinder {
// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if !self.possibleCenters.is_empty() {
return Ok(self.possibleCenters.get(0).unwrap().clone());
return Ok(*self.possibleCenters.get(0).unwrap());
}
Err(Exceptions::NotFoundException(
"nothing to locate".to_owned(),
))
Err(Exceptions::NotFoundException(None))
}
/**
@@ -183,13 +181,14 @@ impl AlignmentPatternFinder {
fn foundPatternCross(&self, stateCount: &[u32]) -> bool {
let moduleSize = self.moduleSize;
let maxVariance = moduleSize / 2.0;
for i in 0..3 {
for state in stateCount.iter().take(3) {
// for i in 0..3 {
// for (int i = 0; i < 3; i++) {
if (moduleSize - stateCount[i] as f32).abs() >= maxVariance {
if (moduleSize - *state as f32).abs() >= maxVariance {
return false;
}
}
return true;
true
}
/**
@@ -262,7 +261,7 @@ impl AlignmentPatternFinder {
let stateCountTotal = self.crossCheckStateCount[0]
+ self.crossCheckStateCount[1]
+ self.crossCheckStateCount[2];
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64).abs() as u32
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64).unsigned_abs() as u32
>= 2 * originalStateCountTotal
{
return f32::NAN;

View File

@@ -50,7 +50,7 @@ impl<'a> Detector<'_> {
}
pub fn getImage(&self) -> &BitMatrix {
&self.image
self.image
}
pub fn getRXingResultPointCallback(&self) -> &Option<RXingResultPointCallback> {
@@ -80,16 +80,17 @@ impl<'a> Detector<'_> {
&mut self,
hints: &DecodingHintDictionary,
) -> Result<QRCodeDetectorResult, Exceptions> {
self.resultPointCallback =
if let Some(nrpc) = hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK) {
if let DecodeHintValue::NeedResultPointCallback(cb) = nrpc {
Some(*cb)
} else {
None
}
} else {
None
};
self.resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) =
hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK)
{
// if let DecodeHintValue::NeedResultPointCallback(cb) = nrpc {
Some(*cb)
// } else {
// None
// }
} else {
None
};
// self.resultPointCallback = hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK);
// resultPointCallback = hints == null ? null :
@@ -112,7 +113,7 @@ impl<'a> Detector<'_> {
let moduleSize = self.calculateModuleSize(topLeft, topRight, bottomLeft);
if moduleSize < 1.0 {
return Err(Exceptions::NotFoundException("not found".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let dimension = Self::computeDimension(topLeft, topRight, bottomLeft, moduleSize)?;
let provisionalVersion = Version::getProvisionalVersionForDimension(dimension)?;
@@ -120,7 +121,7 @@ impl<'a> Detector<'_> {
let mut alignmentPattern = None;
// Anything above version 1 has an alignment pattern
if provisionalVersion.getAlignmentPatternCenters().len() > 0 {
if !provisionalVersion.getAlignmentPatternCenters().is_empty() {
// Guess where a "bottom right" finder pattern would have been
let bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
let bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
@@ -165,7 +166,7 @@ impl<'a> Detector<'_> {
let transform = Self::createTransform(topLeft, topRight, bottomLeft, ap_ref, dimension);
let bits = Detector::sampleGrid(&self.image, &transform, dimension)?;
let bits = Detector::sampleGrid(self.image, &transform, dimension)?;
let points = if alignmentPattern.is_none() {
vec![
@@ -211,7 +212,7 @@ impl<'a> Detector<'_> {
sourceBottomRightY = dimMinusThree;
}
return PerspectiveTransform::quadrilateralToQuadrilateral(
PerspectiveTransform::quadrilateralToQuadrilateral(
3.5,
3.5,
dimMinusThree,
@@ -228,7 +229,7 @@ impl<'a> Detector<'_> {
bottomRightY,
bottomLeft.getX(),
bottomLeft.getY(),
);
)
}
fn sampleGrid(
@@ -237,7 +238,7 @@ impl<'a> Detector<'_> {
dimension: u32,
) -> Result<BitMatrix, Exceptions> {
let sampler = DefaultGridSampler {};
return sampler.sample_grid(&image, dimension, dimension, transform);
sampler.sample_grid(image, dimension, dimension, transform)
}
/**
@@ -258,7 +259,7 @@ impl<'a> Detector<'_> {
match dimension & 0x03 {
0 => dimension += 1,
2 => dimension -= 1,
3 => return Err(Exceptions::NotFoundException("not found".to_owned())),
3 => return Err(Exceptions::NotFoundException(None)),
_ => {}
}
// switch (dimension & 0x03) { // mod 4
@@ -291,9 +292,9 @@ impl<'a> Detector<'_> {
bottomLeft: &T,
) -> f32 {
// Take the average
return (self.calculateModuleSizeOneWay(topLeft, topRight)
(self.calculateModuleSizeOneWay(topLeft, topRight)
+ self.calculateModuleSizeOneWay(topLeft, bottomLeft))
/ 2.0;
/ 2.0
}
/**
@@ -322,7 +323,7 @@ impl<'a> Detector<'_> {
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0;
(moduleSizeEst1 + moduleSizeEst2) / 14.0
}
/**
@@ -357,15 +358,10 @@ impl<'a> Detector<'_> {
}
otherToX = (fromX as f32 + (otherToX as f32 - fromX as f32) * scale).floor() as i32;
result += self.sizeOfBlackWhiteBlackRun(
fromX as u32,
fromY as u32,
otherToX as u32,
otherToY as u32,
);
result += self.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX as u32, otherToY as u32);
// Middle pixel is double-counted this way; subtract 1
return result - 1.0;
result - 1.0
}
/**
@@ -433,14 +429,14 @@ impl<'a> Detector<'_> {
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if state == 2 {
return MathUtils::distance_int(
toX as i32 + xstep as i32,
toX as i32 + xstep,
toY as i32,
fromX as i32,
fromY as i32,
);
}
// else we didn't find even black-white-black; no estimate is really possible
return f32::NAN;
f32::NAN
}
/**
@@ -467,13 +463,13 @@ impl<'a> Detector<'_> {
let alignmentAreaLeftX = 0.max(estAlignmentX as i32 - allowance as i32) as u32;
let alignmentAreaRightX = (self.image.getWidth() - 1).min(estAlignmentX + allowance);
if ((alignmentAreaRightX - alignmentAreaLeftX) as f32) < overallEstModuleSize * 3.0 {
return Err(Exceptions::NotFoundException("not found".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let alignmentAreaTopY = 0.max(estAlignmentY as i32 - allowance as i32) as u32;
let alignmentAreaBottomY = (self.image.getHeight() - 1).min(estAlignmentY + allowance);
if alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize as u32 * 3 {
return Err(Exceptions::NotFoundException("not found".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let mut alignmentFinder = AlignmentPatternFinder::new(

View File

@@ -56,5 +56,5 @@ fn make_larger(input: &BitMatrix, factor: u32) -> BitMatrix {
}
}
}
return output;
output
}

View File

@@ -77,7 +77,7 @@ impl FinderPattern {
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize;
}
return false;
false
}
/**

View File

@@ -202,25 +202,26 @@ impl FinderPatternFinder {
*/
pub fn foundPatternCross(stateCount: &[u32]) -> bool {
let mut totalModuleSize = 0;
for i in 0..5 {
for count in stateCount.iter().take(5) {
// for i in 0..5 {
// for (int i = 0; i < 5; i++) {
let count = stateCount[i];
if count == 0 {
// let count = *state;
if *count == 0 {
return false;
}
totalModuleSize += count;
totalModuleSize += *count;
}
if totalModuleSize < 7 {
return false;
}
let moduleSize = totalModuleSize as f64 / 7.0;
let maxVariance = moduleSize as f64 / 2.0;
let maxVariance = moduleSize / 2.0;
// Allow less than 50% variance from 1-1-3-1-1 proportions
return ((moduleSize - stateCount[0] as f64).abs()) < maxVariance
((moduleSize - stateCount[0] as f64).abs()) < maxVariance
&& ((moduleSize - stateCount[1] as f64).abs()) < maxVariance
&& ((3.0 * moduleSize - stateCount[2] as f64).abs()) < 3.0 * maxVariance
&& (moduleSize - stateCount[3] as f64).abs() < maxVariance
&& (moduleSize - stateCount[4] as f64).abs() < maxVariance;
&& (moduleSize - stateCount[4] as f64).abs() < maxVariance
}
/**
@@ -230,13 +231,13 @@ impl FinderPatternFinder {
*/
pub fn foundPatternDiagonal(stateCount: &[u32]) -> bool {
let mut totalModuleSize = 0;
for i in 0..5 {
for count in stateCount.iter().take(5) {
// for i in 0..5 {
// for (int i = 0; i < 5; i++) {
let count = stateCount[i];
if count == 0 {
if *count == 0 {
return false;
}
totalModuleSize += count;
totalModuleSize += *count;
}
if totalModuleSize < 7 {
return false;
@@ -244,11 +245,11 @@ impl FinderPatternFinder {
let moduleSize = totalModuleSize as f64 / 7.0;
let maxVariance = moduleSize / 1.333;
// Allow less than 75% variance from 1-1-3-1-1 proportions
return (moduleSize - stateCount[0] as f64).abs() < maxVariance
(moduleSize - stateCount[0] as f64).abs() < maxVariance
&& (moduleSize - stateCount[1] as f64).abs() < maxVariance
&& (3.0 * moduleSize - stateCount[2] as f64).abs() < 3.0 * maxVariance
&& (moduleSize - stateCount[3] as f64).abs() < maxVariance
&& (moduleSize - stateCount[4] as f64).abs() < maxVariance;
&& (moduleSize - stateCount[4] as f64).abs() < maxVariance
}
fn getCrossCheckStateCount(&mut self) -> &[u32; 5] {
@@ -488,7 +489,7 @@ impl FinderPatternFinder {
return f32::NAN;
}
while j >= 0
&& self.image.get(j as u32 as u32, centerI)
&& self.image.get(j as u32, centerI)
&& self.crossCheckStateCount[0] <= maxCount
{
self.crossCheckStateCount[0] += 1;
@@ -624,7 +625,7 @@ impl FinderPatternFinder {
return true;
}
}
return false;
false
}
/**
@@ -638,28 +639,27 @@ impl FinderPatternFinder {
if max <= 1 {
return 0;
}
let mut firstConfirmedCenter = None;
let mut firstConfirmedCenter: Option<&FinderPattern> = None;
for center in &self.possibleCenters {
// for (FinderPattern center : possibleCenters) {
if center.getCount() >= Self::CENTER_QUORUM {
if firstConfirmedCenter.is_none() {
firstConfirmedCenter = Some(center);
} else {
if let Some(fnp) = firstConfirmedCenter {
// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
self.hasSkipped = true;
let fnp = firstConfirmedCenter.unwrap();
return (((fnp.getX() - center.getX()).abs()
- (fnp.getY() - center.getY()).abs())
/ 2.0)
.floor() as u32;
} else {
firstConfirmedCenter = Some(center);
}
}
}
return 0;
0
}
/**
@@ -691,7 +691,7 @@ impl FinderPatternFinder {
// for (FinderPattern pattern : possibleCenters) {
totalDeviation += (pattern.getEstimatedModuleSize() - average).abs();
}
return totalDeviation <= 0.05 * totalModuleSize;
totalDeviation <= 0.05 * totalModuleSize
}
/**
@@ -713,7 +713,7 @@ impl FinderPatternFinder {
let startSize = self.possibleCenters.len();
if startSize < 3 {
// Couldn't find enough finder patterns
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
self.possibleCenters.sort_by(|x, y| {
@@ -733,7 +733,7 @@ impl FinderPatternFinder {
let fpi = if let Some(f) = self.possibleCenters.get(i) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
};
let minModuleSize = fpi.getEstimatedModuleSize();
@@ -742,7 +742,7 @@ impl FinderPatternFinder {
let fpj = if let Some(f) = self.possibleCenters.get(j) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
};
let squares0 = Self::squaredDistance(fpi, fpj);
@@ -751,7 +751,7 @@ impl FinderPatternFinder {
let fpk = if let Some(f) = self.possibleCenters.get(k) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
};
let maxModuleSize = fpk.getEstimatedModuleSize();
if maxModuleSize > minModuleSize * 1.4 {
@@ -775,19 +775,17 @@ impl FinderPatternFinder {
b = temp;
}
}
} else {
if b < c {
if a < c {
std::mem::swap(&mut a, &mut b)
} else {
let temp = a;
a = b;
b = c;
c = temp;
}
} else if b < c {
if a < c {
std::mem::swap(&mut a, &mut b)
} else {
std::mem::swap(&mut a, &mut c);
let temp = a;
a = b;
b = c;
c = temp;
}
} else {
std::mem::swap(&mut a, &mut c);
}
// a^2 + b^2 = c^2 (Pythagorean theorem), and a = b (isosceles triangle).
@@ -808,11 +806,11 @@ impl FinderPatternFinder {
}
if distortion == f64::MAX {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
if bestPatterns[0].is_none() {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let p1 = bestPatterns[0].unwrap();

View File

@@ -734,7 +734,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
let dataBytes = &[
67, 70, 22, 38, 54, 70, 86, 102, 118, 134, 150, 166, 182, 198, 214,
@@ -746,7 +746,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
// High-order zero coefficient case.
let dataBytes = &[32, 49, 205, 69, 42, 20, 0, 236, 17];
@@ -757,7 +757,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
}

View File

@@ -198,7 +198,7 @@ fn testGetDataMaskBitInternal(maskPattern: u32, expected: &Vec<Vec<u32>>) -> boo
}
}
}
return true;
true
}
// See mask patterns on the page 43 of JISX0510:2004.

View File

@@ -69,7 +69,7 @@ impl ByteMatrix {
// }
pub fn set_bool(&mut self, x: u32, y: u32, value: bool) {
self.bytes[y as usize][x as usize] = if value { 1 } else { 0 };
self.bytes[y as usize][x as usize] = u8::from(value); //if value { 1 } else { 0 };
}
pub fn clear(&mut self, value: u8) {
@@ -88,9 +88,10 @@ impl fmt::Display for ByteMatrix {
for y in 0..self.height as usize {
// for (int y = 0; y < height; ++y) {
let bytesY = &self.bytes[y];
for x in 0..self.width as usize {
for byte in bytesY.iter().take(self.width as usize) {
// for x in 0..self.width as usize {
// for (int x = 0; x < width; ++x) {
match bytesY[x] {
match *byte {
0 => result.push_str(" 0"),
1 => result.push_str(" 1"),
_ => result.push_str(" "),
@@ -119,7 +120,7 @@ impl From<ByteMatrix> for BitMatrix {
for y in 0..bm.getHeight() {
for x in 0..bm.getWidth() {
if bm.get(x, y) > 0 {
bit_matrix.set(x as u32, y as u32);
bit_matrix.set(x, y);
}
}
}

View File

@@ -55,10 +55,10 @@ pub const DEFAULT_BYTE_MODE_ENCODING: EncodingRef = encoding::all::ISO_8859_1;
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 {
return mask_util::applyMaskPenaltyRule1(matrix)
mask_util::applyMaskPenaltyRule1(matrix)
+ mask_util::applyMaskPenaltyRule2(matrix)
+ mask_util::applyMaskPenaltyRule3(matrix)
+ mask_util::applyMaskPenaltyRule4(matrix);
+ mask_util::applyMaskPenaltyRule4(matrix)
}
/**
@@ -69,7 +69,7 @@ pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 {
* or configuration
*/
pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result<QRCode, Exceptions> {
return encode_with_hints(content, ecLevel, &HashMap::new());
encode_with_hints(content, ecLevel, &HashMap::new())
}
pub fn encode_with_hints(
@@ -127,17 +127,15 @@ pub fn encode_with_hints(
version = rn.getVersion();
} else {
//Switch to default encoding
let encoding = if encoding.is_some() {
encoding.unwrap()
let encoding = if let Some(encoding) = encoding {
encoding
} else if let Ok(_encs) =
DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict)
{
DEFAULT_BYTE_MODE_ENCODING
} else {
if let Ok(_encs) =
DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict)
{
DEFAULT_BYTE_MODE_ENCODING
} else {
has_encoding_hint = true;
encoding::all::UTF_8
}
has_encoding_hint = true;
encoding::all::UTF_8
};
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
@@ -186,9 +184,9 @@ pub fn encode_with_hints(
version = Version::getVersionForNumber(versionNumber)?;
let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version);
if !willFit(bitsNeeded, version, &ec_level) {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data too big for requested version".to_owned(),
));
)));
}
} else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -317,7 +315,7 @@ pub fn getAlphanumericCode(code: u32) -> i8 {
}
pub fn chooseMode(content: &str) -> Mode {
return chooseModeWithEncoding(content, encoding::all::ISO_8859_1);
chooseModeWithEncoding(content, encoding::all::ISO_8859_1)
}
/**
@@ -335,7 +333,7 @@ fn chooseModeWithEncoding(content: &str, encoding: EncodingRef) -> Mode {
for i in 0..content.len() {
// for (int i = 0; i < content.length(); ++i) {
let c = content.chars().nth(i).unwrap();
if c >= '0' && c <= '9' {
if ('0'..='9').contains(&c) {
has_numeric = true;
} else if getAlphanumericCode(c as u32) != -1 {
has_alphanumeric = true;
@@ -349,7 +347,7 @@ fn chooseModeWithEncoding(content: &str, encoding: EncodingRef) -> Mode {
if has_numeric {
return Mode::NUMERIC;
}
return Mode::BYTE;
Mode::BYTE
}
pub fn isOnlyDoubleByteKanji(content: &str) -> bool {
@@ -366,12 +364,12 @@ pub fn isOnlyDoubleByteKanji(content: &str) -> bool {
while i < length {
// for (int i = 0; i < length; i += 2) {
let byte1 = bytes[i];
if (byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB) {
if !(0x81..=0x9F).contains(&byte1) && !(0xE0..=0xEB).contains(&byte1) {
return false;
}
i += 2;
}
return true;
true
}
fn chooseMaskPattern(
@@ -407,7 +405,7 @@ fn chooseVersion(
return Ok(version);
}
}
Err(Exceptions::WriterException("Data too big".to_owned()))
Err(Exceptions::WriterException(Some("Data too big".to_owned())))
}
/**
@@ -424,7 +422,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
// getNumDataBytes = 196 - 130 = 66
let num_data_bytes = num_bytes - num_ec_bytes;
let total_input_bytes = (numInputBits + 7) / 8;
return num_data_bytes >= total_input_bytes;
num_data_bytes >= total_input_bytes
}
/**
@@ -433,10 +431,10 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> {
let capacity = num_data_bytes * 8;
if bits.getSize() > capacity as usize {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"data bits cannot fit in the QR Code{} > ",
capacity
)));
))));
// throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " > " +
// capacity);
}
@@ -468,9 +466,9 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc
bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?;
}
if bits.getSize() != capacity as usize {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Bits size does not equal capacity".to_owned(),
));
)));
// throw new WriterException("Bits size does not equal capacity");
}
Ok(())
@@ -490,7 +488,9 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32), Exceptions> {
if block_id >= num_rsblocks {
return Err(Exceptions::WriterException("Block ID too large".to_owned()));
return Err(Exceptions::WriterException(Some(
"Block ID too large".to_owned(),
)));
// throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
@@ -512,12 +512,16 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// Sanity checks.
// 26 = 26
if num_ec_bytes_in_group1 != numEcBytesInGroup2 {
return Err(Exceptions::WriterException("EC bytes mismatch".to_owned()));
return Err(Exceptions::WriterException(Some(
"EC bytes mismatch".to_owned(),
)));
// throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 {
return Err(Exceptions::WriterException("RS blocks mismatch".to_owned()));
return Err(Exceptions::WriterException(Some(
"RS blocks mismatch".to_owned(),
)));
// throw new WriterException("RS blocks mismatch");
}
@@ -526,9 +530,9 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
!= ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) * num_rs_blocks_in_group1)
+ ((num_data_bytes_in_group2 + numEcBytesInGroup2) * num_rs_blocks_in_group2)
{
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Total bytes mismatch".to_owned(),
));
)));
// throw new WriterException("Total bytes mismatch");
}
@@ -552,9 +556,9 @@ pub fn interleaveWithECBytes(
) -> Result<BitArray, Exceptions> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Number of bits and data bytes does not match".to_owned(),
));
)));
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
@@ -590,9 +594,9 @@ pub fn interleaveWithECBytes(
data_bytes_offset += numDataBytesInBlock as usize;
}
if num_data_bytes != data_bytes_offset as u32 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data bytes does not match offset".to_owned(),
));
)));
}
let mut result = BitArray::new();
@@ -621,11 +625,11 @@ pub fn interleaveWithECBytes(
}
if num_total_bytes != result.getSizeInBytes() as u32 {
// Should be same.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"Interleaving error: {} and {} differ.",
num_total_bytes,
result.getSizeInBytes()
)));
))));
// throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
// result.getSizeInBytes() + " differ.");
}
@@ -652,7 +656,7 @@ pub fn generateECBytes(dataBytes: &[u8], num_ec_bytes_in_block: usize) -> Vec<u8
// for (int i = 0; i < numEcBytesInBlock; i++) {
ecBytes[i] = to_encode[num_data_bytes + i] as u8;
}
return ecBytes;
ecBytes
}
/**
@@ -674,11 +678,11 @@ pub fn appendLengthInfo(
) -> Result<(), Exceptions> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"{} is bigger than {}",
num_letters,
((1 << numBits) - 1)
)));
))));
}
bits.appendBits(num_letters, numBits as usize)?;
Ok(())
@@ -698,10 +702,10 @@ pub fn appendBytes(
Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits),
Mode::BYTE => append8BitBytes(content, bits, encoding),
Mode::KANJI => appendKanjiBytes(content, bits),
_ => Err(Exceptions::WriterException(format!(
_ => Err(Exceptions::WriterException(Some(format!(
"Invalid mode: {:?}",
mode
))),
)))),
}
// switch (mode) {
// case NUMERIC:
@@ -752,12 +756,12 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(),
while i < length {
let code1 = getAlphanumericCode(content.chars().nth(i).unwrap() as u32);
if code1 == -1 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
if i + 1 < length {
let code2 = getAlphanumericCode(content.chars().nth(i + 1).unwrap() as u32);
if code2 == -1 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?;
@@ -795,9 +799,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
.expect("should encode fine");
// let bytes = content.getBytes(StringUtils::SHIFT_JIS_CHARSET);
if bytes.len() % 2 != 0 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Kanji byte size not even".to_owned(),
));
)));
}
let max_i = bytes.len() - 1; // bytes.length must be even
let mut i = 0;
@@ -807,15 +811,15 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
let byte2 = bytes[i + 1]; // & 0xFF;
let code: u16 = ((byte1 as u16) << 8u16) | byte2 as u16;
let mut subtracted: i32 = -1;
if code >= 0x8140 && code <= 0x9ffc {
if (0x8140..=0x9ffc).contains(&code) {
subtracted = code as i32 - 0x8140;
} else if code >= 0xe040 && code <= 0xebbf {
} else if (0xe040..=0xebbf).contains(&code) {
subtracted = code as i32 - 0xc140;
}
if subtracted == -1 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Invalid byte sequence".to_owned(),
));
)));
}
let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded as u32, 13)?;

View File

@@ -85,8 +85,8 @@ pub fn applyMaskPenaltyRule3(matrix: &ByteMatrix) -> u32 {
&& arrayY[x + 4] == 1
&& arrayY[x + 5] == 0
&& arrayY[x + 6] == 1
&& (isWhiteHorizontal(&arrayY, x as i32 - 4, x as u32)
|| isWhiteHorizontal(&arrayY, x as i32 + 7, x as u32 + 11))
&& (isWhiteHorizontal(arrayY, x as i32 - 4, x as u32)
|| isWhiteHorizontal(arrayY, x as i32 + 7, x as u32 + 11))
{
numPenalties += 1;
}
@@ -118,7 +118,7 @@ pub fn isWhiteHorizontal(rowArray: &[u8], from: i32, to: u32) -> bool {
return false;
}
}
return true;
true
}
pub fn isWhiteVertical(array: &Vec<Vec<u8>>, col: u32, from: i32, to: u32) -> bool {
@@ -131,7 +131,7 @@ pub fn isWhiteVertical(array: &Vec<Vec<u8>>, col: u32, from: i32, to: u32) -> bo
return false;
}
}
return true;
true
}
/**
@@ -143,20 +143,22 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 {
let array = matrix.getArray();
let width = matrix.getWidth();
let height = matrix.getHeight();
for y in 0..height as usize {
for val_y in array.iter().take(height as usize) {
// for y in 0..height as usize {
// for (int y = 0; y < height; y++) {
let arrayY = &array[y];
for x in 0..width as usize {
// let arrayY = val_y;
for val_x in val_y.iter().take(width as usize) {
// for x in 0..width as usize {
// for (int x = 0; x < width; x++) {
if arrayY[x] == 1 {
if val_x == &1 {
numDarkCells += 1;
}
}
}
let numTotalCells = matrix.getHeight() * matrix.getWidth();
let fivePercentVariances =
(numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells;
return fivePercentVariances * N4;
(numDarkCells as i64 * 2 - numTotalCells as i64).unsigned_abs() as u32 * 10 / numTotalCells;
fivePercentVariances * N4
}
/**
@@ -183,10 +185,10 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result<bool, Exceptio
((temp % 3) + ((y + x) & 0x1)) & 0x1
}
_ => {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Invalid mask pattern: {}",
maskPattern
)))
))))
}
};
// switch (maskPattern) {
@@ -266,5 +268,5 @@ fn applyMaskPenaltyRule1Internal(matrix: &ByteMatrix, isHorizontal: bool) -> u32
penalty += N1 + (numSameBitCells - 5);
}
}
return penalty;
penalty
}

View File

@@ -171,14 +171,18 @@ pub fn embedTypeInfo(
let mut typeInfoBits = BitArray::new();
makeTypeInfoBits(ecLevel, maskPattern as u32, &mut typeInfoBits)?;
for i in 0..typeInfoBits.getSize() {
for (i, coordinates) in TYPE_INFO_COORDINATES
.iter()
.enumerate()
.take(typeInfoBits.getSize())
{
// for (int i = 0; i < typeInfoBits.getSize(); ++i) {
// Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
// "typeInfoBits".
let bit = typeInfoBits.get(typeInfoBits.getSize() - 1 - i);
// Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
let coordinates = TYPE_INFO_COORDINATES[i];
// let coordinates = TYPE_INFO_COORDINATES[i];
let x1 = coordinates[0];
let y1 = coordinates[1];
matrix.set_bool(x1, y1, bit);
@@ -216,9 +220,7 @@ pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Resu
// for (int j = 0; j < 3; ++j) {
// Place bits in LSB (least significant bit) to MSB order.
let bit = versionInfoBits.get(bitIndex);
if bitIndex != 0 {
bitIndex -= 1;
}
bitIndex = bitIndex.saturating_sub(1);
// Left bottom corner.
matrix.set_bool(i, matrix.getHeight() - 11 + j, bit);
// Right bottom corner.
@@ -280,11 +282,11 @@ pub fn embedDataBits(
}
// All bits should be consumed.
if bitIndex != dataBits.getSize() {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"Not all bits consumed: {}/{}",
bitIndex,
dataBits.getSize()
)));
))));
}
Ok(())
}
@@ -325,9 +327,9 @@ pub fn findMSBSet(value: u32) -> u32 {
// operations. We don't care if coefficients are positive or negative.
pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32, Exceptions> {
if poly == 0 {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"0 polynomial".to_owned(),
));
)));
}
let mut value = value;
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
@@ -351,9 +353,9 @@ pub fn makeTypeInfoBits(
bits: &mut BitArray,
) -> Result<(), Exceptions> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Invalid mask pattern".to_owned(),
));
)));
}
let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
bits.appendBits(typeInfo, 5)?;
@@ -367,10 +369,10 @@ pub fn makeTypeInfoBits(
if bits.getSize() != 15 {
// Just in case.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"should not happen but we got: {}",
bits.getSize()
)));
))));
}
Ok(())
}
@@ -384,17 +386,17 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(),
if bits.getSize() != 18 {
// Just in case.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"should not happen but we got: {}",
bits.getSize()
)));
))));
}
Ok(())
}
// Check if "value" is empty.
pub fn isEmpty(value: u8) -> bool {
return value == -1i8 as u8;
value == -1i8 as u8
}
pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
@@ -417,7 +419,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<(), Exceptions> {
if matrix.get(8, matrix.getHeight() - 8) == 0 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
matrix.set(8, matrix.getHeight() - 8, 1);
Ok(())
@@ -431,7 +433,7 @@ pub fn embedHorizontalSeparationPattern(
for x in 0..8 {
// for (int x = 0; x < 8; ++x) {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
matrix.set(xStart + x, yStart, 0);
}
@@ -446,7 +448,7 @@ pub fn embedVerticalSeparationPattern(
for y in 0..7 {
// for (int y = 0; y < 7; ++y) {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
// throw new WriterException();
}
matrix.set(xStart, yStart + y, 0);
@@ -455,9 +457,10 @@ pub fn embedVerticalSeparationPattern(
}
pub fn embedPositionAdjustmentPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
for y in 0..5 {
for (y, patternY) in POSITION_ADJUSTMENT_PATTERN.iter().enumerate() {
// for y in 0..5 {
// for (int y = 0; y < 5; ++y) {
let patternY = POSITION_ADJUSTMENT_PATTERN[y];
// let patternY = POSITION_ADJUSTMENT_PATTERN[y];
for x in 0..5 {
// for (int x = 0; x < 5; ++x) {
matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);
@@ -466,9 +469,10 @@ pub fn embedPositionAdjustmentPattern(xStart: u32, yStart: u32, matrix: &mut Byt
}
pub fn embedPositionDetectionPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
for y in 0..7 {
for (y, patternY) in POSITION_DETECTION_PATTERN.iter().enumerate() {
// for y in 0..7 {
// for (int y = 0; y < 7; ++y) {
let patternY = POSITION_DETECTION_PATTERN[y];
// let patternY = POSITION_DETECTION_PATTERN[y];
for x in 0..7 {
// for (int x = 0; x < 7; ++x) {
matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);

View File

@@ -117,7 +117,7 @@ impl MinimalEncoder {
.map(|p| p.to_owned())
.collect::<Vec<String>>(),
isGS1,
encoders: ECIEncoderSet::new(&stringToEncode, priorityCharset, None),
encoders: ECIEncoderSet::new(stringToEncode, priorityCharset, None),
ecLevel,
}
@@ -152,7 +152,21 @@ impl MinimalEncoder {
}
pub fn encode(&self, version: Option<VersionRef>) -> Result<RXingResultList, Exceptions> {
if version.is_none() {
if let Some(version) = version {
// compute minimal encoding for a given version
let result = self.encodeSpecificVersion(version)?;
if !encoder::willFit(
result.getSize(),
Self::getVersion(Self::getVersionSize(result.getVersion())),
&self.ecLevel,
) {
return Err(Exceptions::WriterException(Some(format!(
"Data too big for version {}",
version
))));
}
Ok(result)
} else {
// compute minimal encoding trying the three version sizes.
let versions = [
Self::getVersion(VersionSize::SMALL),
@@ -160,9 +174,9 @@ impl MinimalEncoder {
Self::getVersion(VersionSize::LARGE),
];
let results = [
self.encodeSpecificVersion(&versions[0])?,
self.encodeSpecificVersion(&versions[1])?,
self.encodeSpecificVersion(&versions[2])?,
self.encodeSpecificVersion(versions[0])?,
self.encodeSpecificVersion(versions[1])?,
self.encodeSpecificVersion(versions[2])?,
];
let mut smallestSize = u32::MAX;
let mut smallestRXingResult: i32 = -1;
@@ -175,39 +189,22 @@ impl MinimalEncoder {
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data too big for any version".to_owned(),
));
}
Ok(results[smallestRXingResult as usize].clone())
} else {
// compute minimal encoding for a given version
let version = version.unwrap();
let result = self.encodeSpecificVersion(version)?;
if !encoder::willFit(
result.getSize(),
Self::getVersion(Self::getVersionSize(result.getVersion())),
&self.ecLevel,
) {
return Err(Exceptions::WriterException(format!(
"Data too big for version {}",
version
)));
}
Ok(result)
Ok(results[smallestRXingResult as usize].clone())
}
}
pub fn getVersionSize(version: VersionRef) -> VersionSize {
return if version.getVersionNumber() <= 9 {
if version.getVersionNumber() <= 9 {
VersionSize::SMALL
} else if version.getVersionNumber() <= 26 {
VersionSize::MEDIUM
} else {
if version.getVersionNumber() <= 26 {
VersionSize::MEDIUM
} else {
VersionSize::LARGE
}
};
VersionSize::LARGE
}
}
pub fn getVersion(versionSize: VersionSize) -> VersionRef {
@@ -229,8 +226,8 @@ impl MinimalEncoder {
pub fn isNumeric(c: &str) -> bool {
if c.len() == 1 {
let ch = c.chars().nth(0).unwrap();
ch >= '0' && ch <= '9'
let ch = c.chars().next().unwrap();
('0'..='9').contains(&ch)
} else {
false
}
@@ -238,12 +235,12 @@ impl MinimalEncoder {
}
pub fn isDoubleByteKanji(c: &str) -> bool {
return encoder::isOnlyDoubleByteKanji(&c);
encoder::isOnlyDoubleByteKanji(c)
}
pub fn isAlphanumeric(c: &str) -> bool {
if c.len() == 1 {
let ch = c.chars().nth(0).unwrap();
let ch = c.chars().next().unwrap();
encoder::getAlphanumericCode(ch as u32) != -1
} else {
false
@@ -271,10 +268,10 @@ impl MinimalEncoder {
Mode::ALPHANUMERIC => Ok(1),
Mode::BYTE => Ok(3),
Mode::KANJI => Ok(0),
_ => Err(Exceptions::IllegalArgumentException(format!(
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal mode {:?}",
mode
))),
)))),
}
// switch (mode) {
// case KANJI:
@@ -292,13 +289,12 @@ impl MinimalEncoder {
pub fn addEdge(
&self,
edges: &mut Vec<Vec<Vec<Option<Rc<Edge>>>>>,
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
position: usize,
edge: Option<Rc<Edge>>,
) {
let vertexIndex = position + edge.as_ref().unwrap().characterLength as usize;
let modeEdges =
&mut edges[vertexIndex as usize][edge.as_ref().unwrap().charsetEncoderIndex as usize];
let modeEdges = &mut edges[vertexIndex][edge.as_ref().unwrap().charsetEncoderIndex];
let modeOrdinal =
Self::getCompactedOrdinal(Some(edge.as_ref().unwrap().mode)).expect("value") as usize;
if modeEdges[modeOrdinal].is_none()
@@ -312,7 +308,7 @@ impl MinimalEncoder {
pub fn addEdges(
&self,
version: VersionRef,
edges: &mut Vec<Vec<Vec<Option<Rc<Edge>>>>>,
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
from: usize,
previous: Option<Rc<Edge>>,
) {
@@ -322,7 +318,7 @@ impl MinimalEncoder {
if priorityEncoderIndex.is_some()
&& self.encoders.canEncode(
// self.stringToEncode.chars().nth(from as usize).unwrap() as i16,
&self.stringToEncode[from as usize],
&self.stringToEncode[from],
priorityEncoderIndex.unwrap(),
)
{
@@ -334,7 +330,7 @@ impl MinimalEncoder {
// for (int i = start; i < end; i++) {
if self
.encoders
.canEncode(&self.stringToEncode.get(from).unwrap(), i)
.canEncode(self.stringToEncode.get(from).unwrap(), i)
{
self.addEdge(
edges,
@@ -353,7 +349,7 @@ impl MinimalEncoder {
}
}
if self.canEncode(&Mode::KANJI, &self.stringToEncode.get(from).unwrap()) {
if self.canEncode(&Mode::KANJI, self.stringToEncode.get(from).unwrap()) {
self.addEdge(
edges,
from,
@@ -410,19 +406,15 @@ impl MinimalEncoder {
.canEncode(&Mode::NUMERIC, self.stringToEncode.get(from + 1).unwrap())
{
1
} else if from + 2 >= inputLength
|| !self
.canEncode(&Mode::NUMERIC, self.stringToEncode.get(from + 2).unwrap())
{
2
} else {
if from + 2 >= inputLength
|| !self.canEncode(
&Mode::NUMERIC,
self.stringToEncode.get(from + 2).unwrap(),
)
{
2
} else {
3
}
3
},
previous.clone(),
previous,
version,
self.encoders.clone(),
self.stringToEncode.clone(),
@@ -587,13 +579,13 @@ impl MinimalEncoder {
}
}
if minimalJ.is_none() {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
r#"Internal error: failed to encode "{}"#,
self.stringToEncode
.iter()
.map(|x| String::from(x))
.map(String::from)
.collect::<String>() //fold("", |acc,x| [acc,&x].concat())
)));
))));
}
Ok(RXingResultList::new(
version,
@@ -654,31 +646,27 @@ impl Edge {
(previous.is_some() && nci != previous.as_ref().unwrap().charsetEncoderIndex);
if previous.is_none() || mode != previous.as_ref().unwrap().mode || needECI {
size += 4 + mode.getCharacterCountBits(&version) as u32;
size += 4 + mode.getCharacterCountBits(version) as u32;
}
match mode {
Mode::NUMERIC => {
size += if characterLength == 1 {
4
} else if characterLength == 2 {
7
} else {
if characterLength == 2 {
7
} else {
10
}
10
}
}
Mode::ALPHANUMERIC => size += if characterLength == 1 { 6 } else { 11 },
Mode::BYTE => {
let n: String = stringToEncode
.iter()
.skip(fromPosition as usize)
.skip(fromPosition)
.take(characterLength as usize)
.map(|x| String::from(x))
.map(String::from)
.collect();
size += 8 * encoders
.encode_string(&n, charsetEncoderIndex as usize)
.len() as u32;
size += 8 * encoders.encode_string(&n, charsetEncoderIndex).len() as u32;
// size += 8 * encoders
// .encode_string(
// &stringToEncode[fromPosition as usize
@@ -849,8 +837,8 @@ impl RXingResultList {
0,
0,
0,
encoders.clone(),
stringToEncode.clone(),
encoders,
stringToEncode,
version,
),
);
@@ -868,7 +856,7 @@ impl RXingResultList {
// set version to smallest version into which the bits fit.
let mut versionNumber = version.getVersionNumber();
let (lowerLimit, upperLimit) = match MinimalEncoder::getVersionSize(&version) {
let (lowerLimit, upperLimit) = match MinimalEncoder::getVersionSize(version) {
VersionSize::SMALL => (1, 9),
VersionSize::MEDIUM => (10, 26),
_ => (27, 40),
@@ -928,7 +916,7 @@ impl RXingResultList {
for resultNode in &self.list {
result += resultNode.getSize(version);
}
return result;
result
}
fn internal_static_get_size(version: VersionRef, list: &Vec<RXingResultNode>) -> u32 {
@@ -936,7 +924,7 @@ impl RXingResultList {
for resultNode in list {
result += resultNode.getSize(version);
}
return result;
result
}
/**
@@ -961,7 +949,7 @@ impl fmt::Display for RXingResultList {
for current in &self.list {
// for (RXingResultNode current : list) {
if previous.is_some() {
result.push_str(",");
result.push(',');
}
result.push_str(&current.to_string());
previous = Some(current);
@@ -1013,12 +1001,10 @@ impl RXingResultNode {
let rest = self.characterLength % 3;
size += if rest == 1 {
4
} else if rest == 2 {
7
} else {
if rest == 2 {
7
} else {
0
}
0
};
}
Mode::ALPHANUMERIC => {
@@ -1066,8 +1052,8 @@ impl RXingResultNode {
.encode_string(
// &self.stringToEncode[self.fromPosition as usize
// ..(self.fromPosition + self.characterLength as usize)],
&self.stringToEncode.get(self.fromPosition as usize).unwrap(),
self.charsetEncoderIndex as usize,
self.stringToEncode.get(self.fromPosition).unwrap(),
self.charsetEncoderIndex,
)
.len() as u32
} else {
@@ -1088,19 +1074,16 @@ impl RXingResultNode {
)?;
}
if self.mode == Mode::ECI {
bits.appendBits(
self.encoders.getECIValue(self.charsetEncoderIndex as usize),
8,
)?;
bits.appendBits(self.encoders.getECIValue(self.charsetEncoderIndex), 8)?;
} else if self.characterLength > 0 {
// append data
encoder::appendBytes(
// &self.stringToEncode[self.fromPosition as usize
// ..(self.fromPosition + self.characterLength as usize)],
&self.stringToEncode.get(self.fromPosition).unwrap(),
self.stringToEncode.get(self.fromPosition).unwrap(),
self.mode,
bits,
self.encoders.getCharset(self.charsetEncoderIndex as usize),
self.encoders.getCharset(self.charsetEncoderIndex),
)?;
}
Ok(())
@@ -1126,18 +1109,14 @@ impl fmt::Display for RXingResultNode {
result.push_str(&format!("{:?}", self.mode));
result.push('(');
if self.mode == Mode::ECI {
result.push_str(
self.encoders
.getCharset(self.charsetEncoderIndex as usize)
.name(),
);
result.push_str(self.encoders.getCharset(self.charsetEncoderIndex).name());
} else {
let sub_string: String = self
.stringToEncode
.iter()
.skip(self.fromPosition as usize)
.skip(self.fromPosition)
.take(self.characterLength as usize)
.map(|x| String::from(x))
.map(String::from)
.collect();
// result.push_str(&Self::makePrintable(
// &self.stringToEncode[self.fromPosition as usize

View File

@@ -92,7 +92,7 @@ impl QRCode {
// Check if "mask_pattern" is valid.
pub fn isValidMaskPattern(maskPattern: i32) -> bool {
maskPattern >= 0 && maskPattern < Self::NUM_MASK_PATTERNS
(0..Self::NUM_MASK_PATTERNS).contains(&maskPattern)
}
}
@@ -137,3 +137,9 @@ impl fmt::Display for QRCode {
write!(f, "{}", result)
}
}
impl Default for QRCode {
fn default() -> Self {
Self::new()
}
}

View File

@@ -64,13 +64,13 @@ impl Reader for QRCodeReader {
let mut points: Vec<RXingResultPoint>;
if hints.contains_key(&DecodeHintType::PURE_BARCODE) {
let bits = Self::extractPureBits(image.getBlackMatrix())?;
decoderRXingResult = decoder::decode_bitmatrix_with_hints(&bits, &hints)?;
decoderRXingResult = decoder::decode_bitmatrix_with_hints(&bits, hints)?;
points = Vec::new();
} else {
let detectorRXingResult =
Detector::new(image.getBlackMatrix()).detect_with_hints(&hints)?;
Detector::new(image.getBlackMatrix()).detect_with_hints(hints)?;
decoderRXingResult =
decoder::decode_bitmatrix_with_hints(detectorRXingResult.getBits(), &hints)?;
decoder::decode_bitmatrix_with_hints(detectorRXingResult.getBits(), hints)?;
points = detectorRXingResult.getPoints().clone();
}
@@ -151,7 +151,7 @@ impl QRCodeReader {
let leftTopBlack = image.getTopLeftOnBit();
let rightBottomBlack = image.getBottomRightOnBit();
if leftTopBlack.is_none() || rightBottomBlack.is_none() {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let leftTopBlack = leftTopBlack.unwrap();
@@ -166,7 +166,7 @@ impl QRCodeReader {
// Sanity check!
if left >= right || top >= bottom {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
if bottom - top != right - left {
@@ -175,17 +175,17 @@ impl QRCodeReader {
right = left + (bottom - top);
if right >= image.getWidth() as i32 {
// Abort if that would not make sense -- off image
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
}
let matrixWidth = ((right as f32 - left as f32 + 1.0) / moduleSize).round() as u32;
let matrixHeight = ((bottom as f32 - top as f32 + 1.0) / moduleSize).round() as u32;
if matrixWidth == 0 || matrixHeight == 0 {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
if matrixHeight != matrixWidth {
// Only possibly decode square regions
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
// Push in the "border" by half the module width so that we start
@@ -198,13 +198,12 @@ impl QRCodeReader {
// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
let nudgedTooFarRight = left as i32
+ ((matrixWidth as i32 - 1) as f32 * moduleSize as f32) as i32
- right as i32;
let nudgedTooFarRight =
left + ((matrixWidth as i32 - 1) as f32 * moduleSize) as i32 - right;
if nudgedTooFarRight > 0 {
if nudgedTooFarRight > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
left -= nudgedTooFarRight;
}
@@ -213,7 +212,7 @@ impl QRCodeReader {
if nudgedTooFarDown > 0 {
if nudgedTooFarDown > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
top -= nudgedTooFarDown;
}
@@ -252,7 +251,7 @@ impl QRCodeReader {
y += 1;
}
if x == width || y == height {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
Ok((x - leftTopBlack[0]) as f32 / 7.0)
}

View File

@@ -58,25 +58,25 @@ impl Writer for QRCodeWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"Found empty contents".to_owned(),
));
)));
// throw new IllegalArgumentException("Found empty contents");
}
if format != &BarcodeFormat::QR_CODE {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can only encode QR_CODE, but got {:?}",
format
)));
))));
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
}
if width < 0 || height < 0 {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Requested dimensions are too small: {}x{}",
width, height
)));
))));
// throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' +
// height);
}
@@ -102,7 +102,7 @@ impl Writer for QRCodeWriter {
}
// }
let code = encoder::encode_with_hints(contents, errorCorrectionLevel, &hints)?;
let code = encoder::encode_with_hints(contents, errorCorrectionLevel, hints)?;
Self::renderRXingResult(&code, width, height, quietZone)
}
@@ -119,9 +119,9 @@ impl QRCodeWriter {
) -> Result<BitMatrix, Exceptions> {
let input = code.getMatrix();
if input.is_none() {
return Err(Exceptions::IllegalStateException(
return Err(Exceptions::IllegalStateException(Some(
"matrix is empty".to_owned(),
));
)));
// throw new IllegalStateException();
}