diff --git a/Cargo.toml b/Cargo.toml index 15b8fe9..dc9931e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,8 +26,8 @@ image = {version = "0.24", optional = true} imageproc = {version = "0.23.0", optional = true} unicode-segmentation = "1.10.0" codepage-437 = "0.1.0" -rxing-one-d-proc-derive = "0.2" -#rxing-one-d-proc-derive = {path ="../rxing-one-d-proc-derive"} +#rxing-one-d-proc-derive = "0.2.1" +rxing-one-d-proc-derive = {path ="../rxing-one-d-proc-derive"} num = "0.4.0" [dev-dependencies] diff --git a/src/RGBLuminanceSourceTestCase.rs b/src/RGBLuminanceSourceTestCase.rs index d2f915a..1c0a5f5 100644 --- a/src/RGBLuminanceSourceTestCase.rs +++ b/src/RGBLuminanceSourceTestCase.rs @@ -32,7 +32,7 @@ const SRC_DATA: [u32; 9] = [ #[test] fn testCrop() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref()); assert!(SOURCE.isCropSupported()); let cropped = SOURCE.crop(1, 1, 1, 1).unwrap(); @@ -43,7 +43,7 @@ fn testCrop() { #[test] fn testMatrix() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref()); assert_eq!( vec![0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F], @@ -60,7 +60,7 @@ fn testMatrix() { #[test] fn testGetRow() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref()); assert_eq!(vec![0x3F, 0x7F, 0x3F], SOURCE.getRow(2)); } diff --git a/src/aztec/DetectorTest.rs b/src/aztec/DetectorTest.rs index 236ebc6..34b3eff 100644 --- a/src/aztec/DetectorTest.rs +++ b/src/aztec/DetectorTest.rs @@ -101,14 +101,30 @@ fn test_error_in_parameter_locator(data: &str) { clone(&matrix) }; copy.flip_coords( - orientation_points.get(error1).unwrap().get_x().abs() as u32, - orientation_points.get(error1).unwrap().get_y().abs() as u32, + orientation_points + .get(error1) + .unwrap() + .get_x() + .unsigned_abs(), + orientation_points + .get(error1) + .unwrap() + .get_y() + .unsigned_abs(), ); if error2 > error1 { // if error2 == error1, we only test a single error copy.flip_coords( - orientation_points.get(error2).unwrap().get_x().abs() as u32, - orientation_points.get(error2).unwrap().get_y().abs() as u32, + orientation_points + .get(error2) + .unwrap() + .get_x() + .unsigned_abs(), + orientation_points + .get(error2) + .unwrap() + .get_y() + .unsigned_abs(), ); } // dbg!(copy.to_string()); @@ -180,7 +196,7 @@ fn make_larger(input: &BitMatrix, factor: u32) -> BitMatrix { } } } - return output; + output } // Returns a list of the four rotations of the BitMatrix. @@ -209,7 +225,7 @@ fn rotate_right(input: &BitMatrix) -> BitMatrix { } } } - return result; + result } // Returns the transpose of a bit matrix, which is equivalent to rotating the @@ -226,7 +242,7 @@ fn transpose(input: &BitMatrix) -> BitMatrix { } } } - return result; + result } fn clone(input: &BitMatrix) -> BitMatrix { @@ -268,7 +284,7 @@ fn get_orientation_points(code: &AztecCode) -> Vec { } xSign += 2; } - return result; + result } const TEST_BARCODE: &str = r" X X X X X X X X X X X X X X X X X X X X X X X X X diff --git a/src/aztec/EncoderTest.rs b/src/aztec/EncoderTest.rs index 0653581..6de0ddf 100644 --- a/src/aztec/EncoderTest.rs +++ b/src/aztec/EncoderTest.rs @@ -446,16 +446,12 @@ fn testHighLevelEncodeBinary() { let expected_length = (8 * i) + if i <= 31 { 10 + } else if i <= 62 { + 20 + } else if i <= 2078 { + 21 } else { - if i <= 62 { - 20 - } else { - if i <= 2078 { - 21 - } else { - 31 - } - } + 31 }; // ( (i <= 31) ? 10 : (i <= 62) ? 20 : (i <= 2078) ? 21 : 31); // Verify that we are correct about the length. diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index b04dc85..3c36460 100644 --- a/src/aztec/aztec_reader.rs +++ b/src/aztec/aztec_reader.rs @@ -53,8 +53,7 @@ impl Reader for AztecReader { // let notFoundException = None; // let formatException = None; let mut detector = Detector::new(image.getBlackMatrix()); - let points; - let decoderRXingResult: DecoderRXingResult; + // try { let detectorRXingResult = if let Ok(det) = detector.detect(false) { @@ -62,13 +61,11 @@ impl Reader for AztecReader { } else if let Ok(det) = detector.detect(true) { det } else { - return Err(Exceptions::NotFoundException( - "barcode not found".to_owned(), - )); + return Err(Exceptions::NotFoundException(None)); }; - points = detectorRXingResult.getPoints(); - decoderRXingResult = decoder::decode(&detectorRXingResult)?; + let points = detectorRXingResult.getPoints(); + let decoderRXingResult: DecoderRXingResult = decoder::decode(&detectorRXingResult)?; // } catch (NotFoundException e) { // notFoundException = e; // } catch (FormatException e) { diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index 7335fa0..0f1fc24 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -106,10 +106,10 @@ fn encode( layers: i32, ) -> Result { if format != BarcodeFormat::AZTEC { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode AZTEC, but got {:?}", format - ))); + )))); } let aztec = if let Some(cset) = charset { // dbg!(cset.name(), cset.whatwg_name()); diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index 7cba097..3c7282c 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -35,12 +35,12 @@ use super::AztecDetectorResult::AztecDetectorRXingResult; #[derive(PartialEq, Eq, Copy, Clone)] enum Table { - UPPER, - LOWER, - MIXED, - DIGIT, - PUNCT, - BINARY, + Upper, + Lower, + Mixed, + Digit, + Punct, + Binary, } const UPPER_TABLE: [&str; 32] = [ @@ -78,8 +78,8 @@ pub fn decode( ) -> Result { //let mut detectorRXingResult = detectorRXingResult.clone(); let matrix = detectorRXingResult.getBits(); - let rawbits = extract_bits(&detectorRXingResult, matrix); - let corrected_bits = correct_bits(&detectorRXingResult, &rawbits)?; + let rawbits = extract_bits(detectorRXingResult, matrix); + let corrected_bits = correct_bits(detectorRXingResult, &rawbits)?; let raw_bytes = convertBoolArrayToByteArray(&corrected_bits.correct_bits); let result = get_encoded_data(&corrected_bits.correct_bits); let mut decoder_rxing_result = DecoderRXingResult::new( @@ -105,8 +105,8 @@ pub fn highLevelDecode(correctedBits: &[bool]) -> Result { */ fn get_encoded_data(corrected_bits: &[bool]) -> Result { let end_index = corrected_bits.len(); - let mut latch_table = Table::UPPER; // table most recently latched to - let mut shift_table = Table::UPPER; // table to use for the next read + let mut latch_table = Table::Upper; // table most recently latched to + let mut shift_table = Table::Upper; // table to use for the next read // Final decoded string result // (correctedBits-5) / 4 is an upper bound on the size (all-digit result) @@ -121,7 +121,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { let mut index = 0; 'main: while index < end_index { - if shift_table == Table::BINARY { + if shift_table == Table::Binary { if end_index - index < 5 { break; } @@ -147,7 +147,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { // Go back to whatever mode we had been in shift_table = latch_table; } else { - let size = if shift_table == Table::DIGIT { 4 } else { 5 }; + let size = if shift_table == Table::Digit { 4 } else { 5 }; if end_index - index < size { break; } @@ -171,9 +171,9 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { match n { 0 => result.push(29 as char), // translate FNC1 as ASCII 29 7 => { - return Err(Exceptions::FormatException( + return Err(Exceptions::FormatException(Some( "FLG(7) is reserved and illegal".to_owned(), - )) + ))) } // FLG(7) is reserved and illegal _ => { // ECI is decimal integer encoded as 1-6 codes in DIGIT mode @@ -185,19 +185,19 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { //while (n-- > 0) { let next_digit = read_code(corrected_bits, index, 4); index += 4; - if next_digit < 2 || next_digit > 11 { - return Err(Exceptions::FormatException( + if !(2..=11).contains(&next_digit) { + return Err(Exceptions::FormatException(Some( "Not a decimal digit".to_owned(), - )); // Not a decimal digit + ))); // Not a decimal digit } eci = eci * 10 + (next_digit - 2); n -= 1; } let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); if charset_eci.is_err() { - return Err(Exceptions::FormatException( + return Err(Exceptions::FormatException(Some( "Charset must exist".to_owned(), - )); + ))); } encdr = CharacterSetECI::getCharset(&charset_eci?); } @@ -232,7 +232,9 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) { result.push_str(&str); } else { - return Err(Exceptions::IllegalStateException("bad encoding".to_owned())); + return Err(Exceptions::IllegalStateException(Some( + "bad encoding".to_owned(), + ))); } // result.push_str(decodedBytes.toString(encoding.name())); //} catch (UnsupportedEncodingException uee) { @@ -247,12 +249,12 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { */ fn getTable(t: char) -> Table { match t { - 'L' => Table::LOWER, - 'P' => Table::PUNCT, - 'M' => Table::MIXED, - 'D' => Table::DIGIT, - 'B' => Table::BINARY, - _ => Table::UPPER, + 'L' => Table::Lower, + 'P' => Table::Punct, + 'M' => Table::Mixed, + 'D' => Table::Digit, + 'B' => Table::Binary, + _ => Table::Upper, } // switch (t) { // case 'L': @@ -279,12 +281,14 @@ fn getTable(t: char) -> Table { */ fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { match table { - Table::UPPER => Ok(UPPER_TABLE[code as usize]), - Table::LOWER => Ok(LOWER_TABLE[code as usize]), - Table::MIXED => Ok(MIXED_TABLE[code as usize]), - Table::DIGIT => Ok(DIGIT_TABLE[code as usize]), - Table::PUNCT => Ok(PUNCT_TABLE[code as usize]), - _ => Err(Exceptions::IllegalStateException("Bad table".to_owned())), + Table::Upper => Ok(UPPER_TABLE[code as usize]), + Table::Lower => Ok(LOWER_TABLE[code as usize]), + Table::Mixed => Ok(MIXED_TABLE[code as usize]), + Table::Digit => Ok(DIGIT_TABLE[code as usize]), + Table::Punct => Ok(PUNCT_TABLE[code as usize]), + _ => Err(Exceptions::IllegalStateException(Some( + "Bad table".to_owned(), + ))), } // switch (table) { // case UPPER: @@ -345,17 +349,18 @@ fn correct_bits( let num_data_codewords = ddata.getNbDatablocks(); let num_codewords = rawbits.len() / codeword_size; if num_codewords < num_data_codewords as usize { - return Err(Exceptions::FormatException(format!( + return Err(Exceptions::FormatException(Some(format!( "numCodewords {}< numDataCodewords{}", num_codewords, num_data_codewords - ))); + )))); } let mut offset = rawbits.len() % codeword_size; let mut data_words = vec![0i32; num_codewords]; - for i in 0..num_codewords { + for word in data_words.iter_mut().take(num_codewords) { + // for i in 0..num_codewords { // for (int i = 0; i < numCodewords; i++, offset += codewordSize) { - data_words[i] = read_code(rawbits, offset, codeword_size) as i32; + *word = read_code(rawbits, offset, codeword_size) as i32; offset += codeword_size; } @@ -373,15 +378,14 @@ fn correct_bits( // First, count how many bits are going to be thrown out as stuffing let mask = (1 << codeword_size) - 1; let mut stuffed_bits = 0; - for i in 0..num_data_codewords as usize { + for data_word in data_words.iter().take(num_data_codewords as usize) { + // for i in 0..num_data_codewords as usize { // for (int i = 0; i < numDataCodewords; i++) { - let data_word = data_words[i]; - if data_word == 0 || data_word == mask { - return Err(Exceptions::FormatException( - "dataWord == 0 || dataWord == mask".to_owned(), - )); + // let data_word = data_words[i]; + if data_word == &0 || data_word == &mask { + return Err(Exceptions::FormatException(None)); //throw FormatException.getFormatInstance(); - } else if data_word == 1 || data_word == mask - 1 { + } else if data_word == &1 || data_word == &(mask - 1) { stuffed_bits += 1; } } @@ -389,21 +393,22 @@ fn correct_bits( let mut corrected_bits = vec![false; (num_data_codewords * codeword_size as u32 - stuffed_bits) as usize]; let mut index = 0; - for i in 0..num_data_codewords as usize { + for data_word in data_words.iter().take(num_data_codewords as usize) { + // for i in 0..num_data_codewords as usize { // for (int i = 0; i < numDataCodewords; i++) { - let data_word = data_words[i]; - if data_word == 1 || data_word == mask - 1 { + // let data_word = data_words[i]; + if *data_word == 1 || *data_word == mask - 1 { // next codewordSize-1 bits are all zeros or all ones corrected_bits.splice( index..index + codeword_size - 1, - vec![data_word > 1; codeword_size - 1], + vec![*data_word > 1; codeword_size - 1], ); // Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1); index += codeword_size - 1; } else { for bit in (0..codeword_size).rev() { // for (int bit = codewordSize - 1; bit >= 0; --bit) { - corrected_bits[index] = (data_word & (1 << bit)) != 0; + corrected_bits[index] = (*data_word & (1 << bit)) != 0; index += 1; } } @@ -428,9 +433,9 @@ fn extract_bits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec Vec Vec u32 { let mut res = 0; - for i in start_index..start_index + length { + for bit in rawbits.iter().skip(start_index).take(length) { + // for i in start_index..start_index + length { // for (int i = startIndex; i < startIndex + length; i++) { res <<= 1; - if rawbits[i] { + if *bit { res |= 0x01; } } - return res; + res } /** @@ -507,7 +513,7 @@ fn read_byte(rawbits: &[bool], start_index: usize) -> u8 { if n >= 8 { return read_code(rawbits, start_index, 8) as u8; } - return (read_code(rawbits, start_index, n) << (8 - n)) as u8; + (read_code(rawbits, start_index, n) << (8 - n)) as u8 } /** @@ -515,11 +521,12 @@ fn read_byte(rawbits: &[bool], start_index: usize) -> u8 { */ pub fn convertBoolArrayToByteArray(bool_arr: &[bool]) -> Vec { let mut byte_arr = vec![0u8; (bool_arr.len() + 7) / 8]; - for i in 0..byte_arr.len() { + // for i in 0..byte_arr.len() { + for (i, byte) in byte_arr.iter_mut().enumerate() { // for (int i = 0; i < byteArr.length; i++) { - byte_arr[i] = read_byte(bool_arr, 8 * i); + *byte = read_byte(bool_arr, 8 * i); } - return byte_arr; + byte_arr } fn total_bits_in_layer(layers: usize, compact: bool) -> usize { diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index 8b6935f..55399dc 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -93,7 +93,7 @@ impl<'a> Detector<'_> { // 4. Sample the grid let bits = self.sample_grid( - &self.image, + self.image, &bulls_eye_corners[self.shift as usize % 4], &bulls_eye_corners[(self.shift as usize + 1) % 4], &bulls_eye_corners[(self.shift as usize + 2) % 4], @@ -127,7 +127,9 @@ impl<'a> Detector<'_> { || !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[3]) { - return Err(Exceptions::NotFoundException("no valid points".to_owned())); + return Err(Exceptions::NotFoundException(Some( + "no valid points".to_owned(), + ))); } let length = 2 * self.nb_center_layers; // Get the bits around the bull's eye @@ -208,7 +210,9 @@ impl<'a> Detector<'_> { return Ok(shift); } } - Err(Exceptions::NotFoundException("rotation failure".to_owned())) + Err(Exceptions::NotFoundException(Some( + "rotation failure".to_owned(), + ))) } /** @@ -302,8 +306,7 @@ impl<'a> Detector<'_> { // &pind.to_rxing_result_point(), // &pina.to_rxing_result_point(), // ) * (nbCenterLayers + 2) as f32); - if q < 0.75 - || q > 1.25 + if !(0.75..=1.25).contains(&q) || !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd) { break; @@ -321,7 +324,7 @@ impl<'a> Detector<'_> { } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } self.compact = self.nb_center_layers == 5; @@ -360,7 +363,7 @@ impl<'a> Detector<'_> { let mut fnd = false; //Get a white rectangle that can be the border of the matrix in center bull's eye or - if let Ok(wrd) = WhiteRectangleDetector::new_from_image(&self.image) { + if let Ok(wrd) = WhiteRectangleDetector::new_from_image(self.image) { if let Ok(cornerPoints) = wrd.detect() { point_a = cornerPoints[0]; point_b = cornerPoints[1]; @@ -421,7 +424,7 @@ impl<'a> Detector<'_> { // This will ensure that we end up with a white rectangle in center bull's eye // in order to compute a more accurate center. let mut fnd = false; - if let Ok(wrd) = WhiteRectangleDetector::new(&self.image, 15, cx, cy) { + if let Ok(wrd) = WhiteRectangleDetector::new(self.image, 15, cx, cy) { if let Ok(cornerPoints) = wrd.detect() { point_a = cornerPoints[0]; point_b = cornerPoints[1]; @@ -557,7 +560,7 @@ impl<'a> Detector<'_> { result |= 1 << (size - i - 1); } } - return result; + result } /** @@ -607,7 +610,7 @@ impl<'a> Detector<'_> { let c = self.get_color(&p3, &p4); - return c == c_init; + c == c_init } /** diff --git a/src/aztec/encoder/encoder.rs b/src/aztec/encoder/encoder.rs index dfc9857..6b6b1a8 100644 --- a/src/aztec/encoder/encoder.rs +++ b/src/aztec/encoder/encoder.rs @@ -171,25 +171,25 @@ pub fn encode_bytes_with_charset( MAX_NB_BITS }) { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Illegal value {} for layers", user_specified_layers - ))); + )))); } total_bits_in_layer_var = total_bits_in_layer(layers, compact); word_size = WORD_SIZE[layers as usize]; let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size); stuffed_bits = stuffBits(&bits, word_size as usize); if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Data to large for user specified layer".to_owned(), - )); + ))); } if compact && stuffed_bits.getSize() as u32 > word_size * 64 { // Compact format only allows 64 data words, though C4 can hold more words than that - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Data to large for user specified layer".to_owned(), - )); + ))); } } else { word_size = 0; @@ -201,14 +201,14 @@ pub fn encode_bytes_with_charset( loop { // for (int i = 0; ; i++) { if i > MAX_NB_BITS { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Data too large for an Aztec code".to_owned(), - )); + ))); } compact = i <= 3; layers = if compact { i + 1 } else { i }; total_bits_in_layer_var = total_bits_in_layer(layers, compact); - if total_size_bits > total_bits_in_layer_var as u32 { + if total_size_bits > total_bits_in_layer_var { i += 1; continue; } @@ -239,7 +239,7 @@ pub fn encode_bytes_with_charset( // generate mode message let messageSizeInWords = stuffed_bits.getSize() as u32 / word_size; - let modeMessage = generateModeMessage(compact, layers as u32, messageSizeInWords); + let modeMessage = generateModeMessage(compact, layers, messageSizeInWords); // allocate symbol let baseMatrixSize = (if compact { 11 } else { 14 }) + layers * 4; // not including alignment lines @@ -248,10 +248,8 @@ pub fn encode_bytes_with_charset( if compact { // no alignment marks in compact mode, alignmentMap is a no-op matrixSize = baseMatrixSize; - for i in 0..alignmentMap.len() { - // for (int i = 0; i < alignmentMap.length; i++) { - alignmentMap[i] = i as u32; - } + // for i in 0..alignmentMap.len() { + alignmentMap[..].copy_from_slice(&(0..baseMatrixSize).collect::>()[..]); } else { matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15); let origCenter = (baseMatrixSize / 2) as usize; @@ -259,11 +257,11 @@ pub fn encode_bytes_with_charset( for i in 0..origCenter { // for (int i = 0; i < origCenter; i++) { let newOffset = (i + i / 15) as u32; - alignmentMap[origCenter - i - 1] = center as u32 - newOffset - 1; - alignmentMap[origCenter + i] = center as u32 + newOffset + 1; + alignmentMap[origCenter - i - 1] = center - newOffset - 1; + alignmentMap[origCenter + i] = center + newOffset + 1; } } - let mut matrix = BitMatrix::with_single_dimension(matrixSize as u32); + let mut matrix = BitMatrix::with_single_dimension(matrixSize); // dbg!(matrix.to_string()); @@ -306,25 +304,25 @@ pub fn encode_bytes_with_charset( // dbg!(matrix.to_string()); // draw mode message - drawModeMessage(&mut matrix, compact, matrixSize as u32, modeMessage); + drawModeMessage(&mut matrix, compact, matrixSize, modeMessage); // dbg!(matrix.to_string()); // draw alignment marks if compact { - drawBullsEye(&mut matrix, matrixSize as u32 / 2, 5); + drawBullsEye(&mut matrix, matrixSize / 2, 5); } else { - drawBullsEye(&mut matrix, matrixSize as u32 / 2, 7); + drawBullsEye(&mut matrix, matrixSize / 2, 7); let mut i = 0; let mut j = 0; while i < baseMatrixSize / 2 - 1 { let mut k = (matrixSize / 2) & 1; while k < matrixSize { // for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) { - matrix.set(matrixSize as u32 / 2 - j, k as u32); - matrix.set(matrixSize as u32 / 2 + j, k as u32); - matrix.set(k as u32, matrixSize as u32 / 2 - j); - matrix.set(k as u32, matrixSize as u32 / 2 + j); + matrix.set(matrixSize / 2 - j, k); + matrix.set(matrixSize / 2 + j, k); + matrix.set(k, matrixSize / 2 - j); + matrix.set(k, matrixSize / 2 + j); k += 2; } @@ -344,13 +342,7 @@ pub fn encode_bytes_with_charset( // dbg!(matrix.to_string()); - let aztec = AztecCode::new( - compact, - matrixSize as u32, - layers, - messageSizeInWords as u32, - matrix, - ); + let aztec = AztecCode::new(compact, matrixSize, layers, messageSizeInWords, matrix); // aztec.setCompact(compact); // aztec.setSize(matrixSize); // aztec.setLayers(layers); @@ -399,7 +391,7 @@ pub fn generateModeMessage(compact: bool, layers: u32, messageSizeInWords: u32) .expect("should append"); mode_message = generateCheckWords(&mode_message, 40, 4); } - return mode_message; + mode_message } fn drawModeMessage(matrix: &mut BitMatrix, compact: bool, matrixSize: u32, modeMessage: BitArray) { @@ -459,7 +451,7 @@ fn generateCheckWords(bitArray: &BitArray, totalBits: usize, wordSize: usize) -> .expect("must append"); } // dbg!(message_bits.to_string()); - return message_bits; + message_bits } fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Vec { @@ -472,7 +464,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve for j in 0..wordSize { // for (int j = 0; j < wordSize; j++) { value |= if stuffedBits.get(i * wordSize + j) { - 1 << wordSize - j - 1 + 1 << (wordSize - j - 1) } else { 0 }; @@ -481,7 +473,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve i += 1; } - return message; + message } fn getGF(wordSize: usize) -> Result { @@ -491,10 +483,10 @@ fn getGF(wordSize: usize) -> Result { 8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)), 10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)), 12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)), - _ => Err(Exceptions::IllegalArgumentException(format!( + _ => Err(Exceptions::IllegalArgumentException(Some(format!( "Unsupported word size {}", wordSize - ))), + )))), } // switch (wordSize) { // case 4: @@ -539,7 +531,7 @@ pub fn stuffBits(bits: &BitArray, word_size: usize) -> BitArray { i += word_size as isize; } - return out; + out } fn total_bits_in_layer(layers: u32, compact: bool) -> u32 { diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index e8b9e94..75cce52 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -14,8 +14,6 @@ * limitations under the License. */ -use std::cmp::Ordering; - use crate::{ common::{BitArray, CharacterSetECI}, exceptions::Exceptions, @@ -250,9 +248,9 @@ impl HighLevelEncoder { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "No ECI code for character set".to_owned(), - )); + ))); } // if self.charset != null { // CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset); @@ -266,13 +264,13 @@ impl HighLevelEncoder { while index < self.text.len() { // for index in 0..self.text.len() { // for (int index = 0; index < text.length; index++) { - let pair_code; + let next_char = if index + 1 < self.text.len() { self.text[index + 1] } else { 0 }; - pair_code = match self.text[index] { + let pair_code = match self.text[index] { b'\r' if next_char == b'\n' => 2, b'.' if next_char == b' ' => 3, b',' if next_char == b' ' => 4, @@ -301,13 +299,19 @@ impl HighLevelEncoder { .into_iter() .min_by(|a, b| { let diff: i64 = a.getBitCount() as i64 - b.getBitCount() as i64; - if diff < 0 { - Ordering::Less - } else if diff == 0 { - Ordering::Equal - } else { - Ordering::Greater - } + diff.cmp(&0) + // match diff { + // ..0 => Ordering::Less, + // 0 => Ordering::Equal, + // 0.. => Ordering::Greater, + // } + // if diff < 0 { + // Ordering::Less + // } else if diff == 0 { + // Ordering::Equal + // } else { + // Ordering::Greater + // } // a.getBitCount() - b.getBitCount() }) .unwrap(); @@ -344,7 +348,7 @@ impl HighLevelEncoder { let mut state_no_binary = None; for mode in 0..=Self::MODE_PUNCT { // for (int mode = 0; mode <= MODE_PUNCT; mode++) { - let char_in_mode = Self::CHAR_MAP[mode as usize][ch as usize]; + let char_in_mode = Self::CHAR_MAP[mode][ch as usize]; if char_in_mode > 0 { if state_no_binary.is_none() { // Only create stateNoBinary the first time it's required. @@ -446,7 +450,7 @@ impl HighLevelEncoder { add = false; break; } - if newState.isBetterThanOrEqualTo(&oldState) { + if newState.isBetterThanOrEqualTo(oldState) { result.remove(i); } } @@ -455,6 +459,6 @@ impl HighLevelEncoder { result.push(newState); } } - return result; + result } } diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index 0871fc3..ec646b3 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -80,9 +80,9 @@ impl State { token.add(0, 3); // 0: FNC1 } else */ if eci > 999999 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "ECI code must be between 0 and 999999".to_owned(), - )); + ))); // throw new IllegalArgumentException("ECI code must be between 0 and 999999"); } else { let eci_digits = encoding::all::ISO_8859_1 @@ -155,12 +155,10 @@ impl State { let deltaBitCount = if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 { 18 + } else if self.binary_shift_byte_count == 62 { + 9 } else { - if self.binary_shift_byte_count == 62 { - 9 - } else { - 8 - } + 8 }; let mut result = State::new( token, @@ -240,7 +238,7 @@ impl State { if binary_shift_byte_count > 0 { return 10; // one B/S } - return 0; + 0 } } diff --git a/src/aztec/encoder/token.rs b/src/aztec/encoder/token.rs index 1acc189..131f91e 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -115,3 +115,9 @@ impl IntoIterator for Token { // fn appendTo(&self, bitArray: BitArray, text: &[u8]); // } + +impl Default for Token { + fn default() -> Self { + Self::new() + } +} diff --git a/src/aztec/shared_test_methods.rs b/src/aztec/shared_test_methods.rs index edd5a6d..9ca8602 100644 --- a/src/aztec/shared_test_methods.rs +++ b/src/aztec/shared_test_methods.rs @@ -24,9 +24,10 @@ pub fn toBitArray(bits: &str) -> BitArray { #[allow(dead_code)] pub fn toBooleanArray(bitArray: &BitArray) -> Vec { let mut result = vec![false; bitArray.getSize()]; - for i in 0..result.len() { + // for i in 0..result.len() { + for (i, res) in result.iter_mut().enumerate() { // for (int i = 0; i < result.length; i++) { - result[i] = bitArray.get(i); + *res = bitArray.get(i); } result } diff --git a/src/binary_bitmap.rs b/src/binary_bitmap.rs index 409e10b..ca97f30 100644 --- a/src/binary_bitmap.rs +++ b/src/binary_bitmap.rs @@ -39,7 +39,7 @@ impl BinaryBitmap { pub fn new(binarizer: Rc>) -> Self { Self { matrix: None, - binarizer: binarizer, + binarizer, } } @@ -123,7 +123,7 @@ impl BinaryBitmap { .clone(), ) } - &self.matrix.as_ref().unwrap() + self.matrix.as_ref().unwrap() } /** @@ -132,8 +132,8 @@ impl BinaryBitmap { pub fn isCropSupported(&self) -> bool { let b = self.binarizer.borrow(); let r = b.getLuminanceSource(); - let isCropOk = r.isCropSupported(); - return isCropOk; + + r.isCropSupported() } /** diff --git a/src/buffered_image_luminance_source.rs b/src/buffered_image_luminance_source.rs index 53f81ee..731f971 100644 --- a/src/buffered_image_luminance_source.rs +++ b/src/buffered_image_luminance_source.rs @@ -102,7 +102,7 @@ impl BufferedImageLuminanceSource { for y in 0..image.height() { let pixel = img.get_pixel(x, y); let [red, green, blue, alpha] = pixel.0; - if (alpha & 0xFF) == 0 { + if alpha == 0 { // white, so we know its luminance is 255 raster.put_pixel(x, y, Luma([0xFF])) } else { @@ -147,10 +147,10 @@ impl BufferedImageLuminanceSource { Self { image: Rc::new(DynamicImage::from(raster)), - width: width, - height: height, - left: left, - top: top, + width, + height, + left, + top, } // Self { @@ -206,13 +206,12 @@ impl LuminanceSource for BufferedImageLuminanceSource { let data = unmanaged .chunks(self.image.width() as usize) .into_iter() // Get rows - .map(|f| { - f.into_iter() + .flat_map(|f| { + f.iter() .skip(row_skip as usize) - .take(total_row_take as usize) + .take(total_row_take) .copied() - }) // Take data from each row - .flatten() // flatten this all out + }) // flatten this all out .copied() // copy it over so that it's u8 .collect(); // collect into a vec @@ -235,7 +234,7 @@ impl LuminanceSource for BufferedImageLuminanceSource { } fn isCropSupported(&self) -> bool { - return true; + true } fn crop( @@ -266,7 +265,7 @@ impl LuminanceSource for BufferedImageLuminanceSource { } fn isRotateSupported(&self) -> bool { - return true; + true } fn rotateCounterClockwise( diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index 86a09fe..57f9c2f 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -118,20 +118,20 @@ impl AddressBookParsedRXingResult { urls: Vec, geo: Vec, ) -> Result { - if phone_numbers.len() != phone_types.len() && phone_types.len() > 0 { - return Err(Exceptions::IllegalArgumentException( + if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { + return Err(Exceptions::IllegalArgumentException(Some( "Phone numbers and types lengths differ".to_owned(), - )); + ))); } - if emails.len() != email_types.len() && email_types.len() > 0 { - return Err(Exceptions::IllegalArgumentException( + if emails.len() != email_types.len() && !email_types.is_empty() { + return Err(Exceptions::IllegalArgumentException(Some( "Emails and types lengths differ".to_owned(), - )); + ))); } - if addresses.len() != address_types.len() && address_types.len() > 0 { - return Err(Exceptions::IllegalArgumentException( + if addresses.len() != address_types.len() && !address_types.is_empty() { + return Err(Exceptions::IllegalArgumentException(Some( "Addresses and types lengths differ".to_owned(), - )); + ))); } Ok(Self { names, diff --git a/src/client/result/AddressBookParsedResultTestCase.rs b/src/client/result/AddressBookParsedResultTestCase.rs index 3453ae5..6a77d77 100644 --- a/src/client/result/AddressBookParsedResultTestCase.rs +++ b/src/client/result/AddressBookParsedResultTestCase.rs @@ -37,7 +37,7 @@ fn testAddressBookDocomo() { doTest( "MECARD:N:Sean Owen;;", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", &Vec::new(), &Vec::new(), @@ -51,14 +51,14 @@ fn testAddressBookDocomo() { doTest( "MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;;", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", &Vec::new(), - &vec!["srowen@example.org"], + &["srowen@example.org"], &Vec::new(), &Vec::new(), "", - &vec!["google.com"], + &["google.com"], "", "ZXing Team", ); @@ -69,11 +69,11 @@ fn testAddressBookAU() { doTest( "MEMORY:foo\r\nNAME1:Sean\r\nTEL1:+12125551212\r\n", "", - &vec!["Sean"], + &["Sean"], "", &Vec::new(), &Vec::new(), - &vec!["+12125551212"], + &["+12125551212"], &Vec::new(), "", &Vec::new(), @@ -87,9 +87,9 @@ fn testVCard() { doTest( "BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", - &vec!["123 Main St"], + &["123 Main St"], &Vec::new(), &Vec::new(), &Vec::new(), @@ -105,7 +105,7 @@ fn testVCardFullN() { doTest( "BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;T;Mr.;Esq.\r\nEND:VCARD", "", - &vec!["Mr. Sean T Owen Esq."], + &["Mr. Sean T Owen Esq."], "", &Vec::new(), &Vec::new(), @@ -123,7 +123,7 @@ fn testVCardFullN2() { doTest( "BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;;;\r\nEND:VCARD", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", &Vec::new(), &Vec::new(), @@ -141,7 +141,7 @@ fn testVCardFullN3() { doTest( "BEGIN:VCARD\r\nVERSION:2.1\r\nN:;Sean;;;\r\nEND:VCARD", "", - &vec!["Sean"], + &["Sean"], "", &Vec::new(), &Vec::new(), @@ -159,9 +159,9 @@ fn testVCardCaseInsensitive() { doTest( "begin:vcard\r\nadr;HOME:123 Main St\r\nVersion:2.1\r\nn:Owen;Sean\r\nEND:VCARD", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", - &vec!["123 Main St"], + &["123 Main St"], &Vec::new(), &Vec::new(), &Vec::new(), @@ -175,7 +175,7 @@ fn testVCardCaseInsensitive() { #[test] fn testEscapedVCard() { doTest("BEGIN:VCARD\r\nADR;HOME:123\\;\\\\ Main\\, St\\nHome\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", - "", &vec!["Sean Owen"], "", &vec!["123;\\ Main, St\nHome"], + "", &["Sean Owen"], "", &["123;\\ Main, St\nHome"], &Vec::new(), &Vec::new(), &Vec::new(), "", &Vec::new(), "", ""); } @@ -184,11 +184,11 @@ fn testBizcard() { doTest( "BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12125551212;E:srowen@example.org;", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", - &vec!["123 Main St"], - &vec!["srowen@example.org"], - &vec!["+12125551212"], + &["123 Main St"], + &["srowen@example.org"], + &["+12125551212"], &Vec::new(), "Google", &Vec::new(), @@ -200,9 +200,9 @@ fn testBizcard() { #[test] fn testSeveralAddresses() { doTest("MECARD:N:Foo Bar;ORG:Company;TEL:5555555555;EMAIL:foo.bar@xyz.com;ADR:City, 10001;ADR:City, 10001;NOTE:This is the memo.;;", - "", &vec!["Foo Bar"], "", &vec!["City, 10001", "City, 10001"], - &vec!["foo.bar@xyz.com"], - &vec!["5555555555" ], &Vec::new(), "Company", &Vec::new(), "", "This is the memo."); + "", &["Foo Bar"], "", &["City, 10001", "City, 10001"], + &["foo.bar@xyz.com"], + &["5555555555"], &Vec::new(), "Company", &Vec::new(), "", "This is the memo."); } #[test] @@ -212,7 +212,7 @@ fn testQuotedPrintable() { "", &Vec::new(), "", - &vec!["88 Lynbrook\r\nCO 69999"], + &["88 Lynbrook\r\nCO 69999"], &Vec::new(), &Vec::new(), &Vec::new(), @@ -292,8 +292,8 @@ fn testVCardValueURI() { "", &Vec::new(), &Vec::new(), - &vec!["+1-555-555-1212"], - &vec![""], + &["+1-555-555-1212"], + &[""], "", &Vec::new(), "", @@ -303,7 +303,7 @@ fn testVCardValueURI() { doTest( "BEGIN:VCARD\r\nN;VALUE=text:Owen;Sean\r\nEND:VCARD", "", - &vec!["Sean Owen"], + &["Sean Owen"], "", &Vec::new(), &Vec::new(), @@ -325,8 +325,8 @@ fn testVCardTypes() { "", &Vec::new(), &Vec::new(), - &vec!["10", "20", "30"], - &vec!["WORK", "", "CELL"], + &["10", "20", "30"], + &["WORK", "", "CELL"], "", &Vec::new(), "", diff --git a/src/client/result/BizcardResultParser.rs b/src/client/result/BizcardResultParser.rs index b1933f6..bb95629 100644 --- a/src/client/result/BizcardResultParser.rs +++ b/src/client/result/BizcardResultParser.rs @@ -120,11 +120,9 @@ fn buildPhoneNumbers(number1: String, number2: String, number3: String) -> Vec String { if firstName.is_empty() { lastName.to_owned() + } else if lastName.is_empty() { + firstName.to_owned() } else { - if lastName.is_empty() { - firstName.to_owned() - } else { - format!("{} {}", firstName, lastName) - } + format!("{} {}", firstName, lastName) } } diff --git a/src/client/result/BookmarkDoCoMoResultParser.rs b/src/client/result/BookmarkDoCoMoResultParser.rs index a61d1ea..4d99f84 100644 --- a/src/client/result/BookmarkDoCoMoResultParser.rs +++ b/src/client/result/BookmarkDoCoMoResultParser.rs @@ -32,14 +32,12 @@ pub fn parse(result: &RXingResult) -> Option { } let title = ResultParser::match_single_do_co_mo_prefixed_field("TITLE:", rawText, true); let rawUri = ResultParser::match_do_co_mo_prefixed_field("URL:", rawText); - if rawUri.is_none() { - return None; - } + rawUri.as_ref()?; let uri = rawUri?[0].clone(); if URIResultParser::is_basically_valid_uri(&uri) { Some(ParsedClientResult::URIResult(URIParsedRXingResult::new( uri, - title.unwrap_or("".to_owned()), + title.unwrap_or_else(|| "".to_owned()), ))) } else { None diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index a2616c7..17be512 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -120,8 +120,6 @@ impl CalendarParsedRXingResult { } else { Self::parseDate(endString.clone())? }; - let startAllDay; - let endAllDay; // try { // this.start = parseDate(startString); @@ -140,8 +138,8 @@ impl CalendarParsedRXingResult { // } // } - startAllDay = startString.len() == 8; - endAllDay = !endString.is_empty() && endString.len() == 8; + let startAllDay = startString.len() == 8; + let endAllDay = !endString.is_empty() && endString.len() == 8; Ok(Self { summary, @@ -168,7 +166,7 @@ impl CalendarParsedRXingResult { fn parseDate(when: String) -> Result { // let date_time_regex = Regex::new(DATE_TIME).unwrap(); if !DATE_TIME.is_match(&when) { - return Err(Exceptions::ParseException(when)); + return Err(Exceptions::ParseException(Some(when))); } if when.len() == 8 { // Show only year/month/day @@ -196,10 +194,10 @@ impl CalendarParsedRXingResult { if when.len() == 16 && when.chars().nth(15).unwrap() == 'Z' { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") { Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()), - Err(e) => Err(Exceptions::ParseException(format!( + Err(e) => Err(Exceptions::ParseException(Some(format!( "couldn't parse string: {}", e - ))), + )))), }; // let dtm = DateTime::parse_from_str(&when, "%Y%m%dT%H%M%S").unwrap().with_timezone(&Utc); // //let milliseconds = Self::parseDateTimeString(&when[0..15]); @@ -219,18 +217,18 @@ impl CalendarParsedRXingResult { let tz_parsed: Tz = match tz_part.parse() { Ok(time_zone) => time_zone, Err(e) => { - return Err(Exceptions::ParseException(format!( + return Err(Exceptions::ParseException(Some(format!( "couldn't parse timezone '{}': {}", tz_part, e - ))) + )))) } }; return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") { Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()), - Err(e) => Err(Exceptions::ParseException(format!( + Err(e) => Err(Exceptions::ParseException(Some(format!( "couldn't parse string: {}", e - ))), + )))), }; } @@ -238,10 +236,10 @@ impl CalendarParsedRXingResult { if when.len() == 15 { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") { Ok(dtm) => Ok(dtm.timestamp()), - Err(e) => Err(Exceptions::ParseException(format!( + Err(e) => Err(Exceptions::ParseException(Some(format!( "couldn't parse local time: {}", e - ))), + )))), }; } Self::parseDateTimeString(&when) @@ -270,12 +268,13 @@ impl CalendarParsedRXingResult { // let regex = Regex::new(RFC2445_DURATION).unwrap(); if let Some(m) = RFC2445_DURATION.captures(durationString) { let mut durationMS = 0i64; - for i in 0..RFC2445_DURATION_FIELD_UNITS.len() { + for (i, unit) in RFC2445_DURATION_FIELD_UNITS.iter().enumerate() { + // for i in 0..RFC2445_DURATION_FIELD_UNITS.len() { // for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.length; i++) { let fieldValue = m.get(i + 1); - if fieldValue.is_some() { - let z = fieldValue.unwrap().as_str().parse::().unwrap(); - durationMS += RFC2445_DURATION_FIELD_UNITS[i] * z; + if let Some(parseable) = fieldValue { + let z = parseable.as_str().parse::().unwrap(); + durationMS += unit * z; } } durationMS @@ -299,10 +298,10 @@ impl CalendarParsedRXingResult { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { Ok(dtm.timestamp()) } else { - Err(Exceptions::ParseException(format!( + Err(Exceptions::ParseException(Some(format!( "Couldn't parse {}", dateTimeString - ))) + )))) } // DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH); // return format.parse(dateTimeString).getTime(); diff --git a/src/client/result/CalendarParsedResultTestCase.rs b/src/client/result/CalendarParsedResultTestCase.rs index 5fe9f34..131699b 100644 --- a/src/client/result/CalendarParsedResultTestCase.rs +++ b/src/client/result/CalendarParsedResultTestCase.rs @@ -150,7 +150,7 @@ fn testAttendees() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20080504T123456Z\r\nATTENDEE:mailto:bob@example.org\r\nATTENDEE:mailto:alice@example.org\r\nEND:VEVENT\r\nEND:VCALENDAR", "", "", "", "20080504T123456Z", "", "", - &vec!["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN); + &["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN); } #[test] diff --git a/src/client/result/EmailAddressParsedResultTestCase.rs b/src/client/result/EmailAddressParsedResultTestCase.rs index 253719b..a52179a 100644 --- a/src/client/result/EmailAddressParsedResultTestCase.rs +++ b/src/client/result/EmailAddressParsedResultTestCase.rs @@ -42,7 +42,7 @@ fn testEmailAddress() { fn testTos() { do_test( "mailto:srowen@example.org,bob@example.org", - &vec!["srowen@example.org", "bob@example.org"], + &["srowen@example.org", "bob@example.org"], &Vec::new(), &Vec::new(), "", @@ -50,7 +50,7 @@ fn testTos() { ); do_test( "mailto:?to=srowen@example.org,bob@example.org", - &vec!["srowen@example.org", "bob@example.org"], + &["srowen@example.org", "bob@example.org"], &Vec::new(), &Vec::new(), "", @@ -63,7 +63,7 @@ fn testCCs() { do_test( "mailto:?cc=srowen@example.org", &Vec::new(), - &vec!["srowen@example.org"], + &["srowen@example.org"], &Vec::new(), "", "", @@ -71,7 +71,7 @@ fn testCCs() { do_test( "mailto:?cc=srowen@example.org,bob@example.org", &Vec::new(), - &vec!["srowen@example.org", "bob@example.org"], + &["srowen@example.org", "bob@example.org"], &Vec::new(), "", "", @@ -84,7 +84,7 @@ fn testBCCs() { "mailto:?bcc=srowen@example.org", &Vec::new(), &Vec::new(), - &vec!["srowen@example.org"], + &["srowen@example.org"], "", "", ); @@ -92,7 +92,7 @@ fn testBCCs() { "mailto:?bcc=srowen@example.org,bob@example.org", &Vec::new(), &Vec::new(), - &vec!["srowen@example.org", "bob@example.org"], + &["srowen@example.org", "bob@example.org"], "", "", ); @@ -102,9 +102,9 @@ fn testBCCs() { fn testAll() { do_test( "mailto:bob@example.org?cc=foo@example.org&bcc=srowen@example.org&subject=baz&body=buzz", - &vec!["bob@example.org"], - &vec!["foo@example.org"], - &vec!["srowen@example.org"], + &["bob@example.org"], + &["foo@example.org"], + &["srowen@example.org"], "baz", "buzz", ); @@ -151,7 +151,7 @@ fn testSMTP() { } fn do_test_single(contents: &str, to: &str, subject: &str, body: &str) { - do_test(contents, &vec![to], &Vec::new(), &Vec::new(), subject, body); + do_test(contents, &[to], &Vec::new(), &Vec::new(), subject, body); } fn do_test(contents: &str, tos: &[&str], ccs: &[&str], bccs: &[&str], subject: &str, body: &str) { diff --git a/src/client/result/EmailAddressResultParser.rs b/src/client/result/EmailAddressResultParser.rs index d61d30b..255b087 100644 --- a/src/client/result/EmailAddressResultParser.rs +++ b/src/client/result/EmailAddressResultParser.rs @@ -120,22 +120,16 @@ pub fn parse(result: &RXingResult) -> Option { subject = nv.get("subject").unwrap_or(&"".to_owned()).clone(); body = nv.get("body").unwrap_or(&"".to_owned()).clone(); } - return Some(ParsedClientResult::EmailResult( - EmailAddressParsedRXingResult::with_details( - tos, - ccs, - bccs, - subject.to_owned(), - body.to_owned(), - ), - )); + Some(ParsedClientResult::EmailResult( + EmailAddressParsedRXingResult::with_details(tos, ccs, bccs, subject, body), + )) } else { // let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) { return None; } - return Some(ParsedClientResult::EmailResult( + Some(ParsedClientResult::EmailResult( EmailAddressParsedRXingResult::new(rawText), - )); + )) } } diff --git a/src/client/result/EmailDoCoMoResultParser.rs b/src/client/result/EmailDoCoMoResultParser.rs index 6bb0611..6a05b82 100644 --- a/src/client/result/EmailDoCoMoResultParser.rs +++ b/src/client/result/EmailDoCoMoResultParser.rs @@ -48,7 +48,7 @@ pub fn parse(result: &RXingResult) -> Option { let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?; for to in &tos { - if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) { + if !isBasicallyValidEmailAddress(to, &ATEXT_ALPHANUMERIC) { return None; } } diff --git a/src/client/result/ExpandedProductResultParser.rs b/src/client/result/ExpandedProductResultParser.rs index ba5aaad..95b0d76 100644 --- a/src/client/result/ExpandedProductResultParser.rs +++ b/src/client/result/ExpandedProductResultParser.rs @@ -251,7 +251,7 @@ fn findAIvalue(i: usize, rawText: &str) -> Option { if currentChar == ')' { return Some(buf); } - if currentChar < '0' || currentChar > '9' { + if !('0'..='9').contains(¤tChar) { return None; } buf.push(currentChar); @@ -270,7 +270,7 @@ fn findValue(i: usize, rawText: &str) -> String { if c == '(' { // We look for a new AI. If it doesn't exist (ERROR), we continue // with the iteration - if let Some(_) = findAIvalue(index, rawTextAux) { + if findAIvalue(index, rawTextAux).is_some() { break; } // if findAIvalue(index, rawTextAux) != null { diff --git a/src/client/result/GeoResultParser.rs b/src/client/result/GeoResultParser.rs index 0080cdc..2eaa550 100644 --- a/src/client/result/GeoResultParser.rs +++ b/src/client/result/GeoResultParser.rs @@ -29,7 +29,7 @@ lazy_static! { static ref GEO_URL: regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap(); } -const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?"; +const GEO_URL_PATTERN: &str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?"; /** * Parses a "geo:" URI result, which specifies a location on the surface of @@ -54,7 +54,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option() { - if laf64 > 90.0 || laf64 < -90.0 { + if !(-90.0..=90.0).contains(&laf64) { return None; } laf64 @@ -67,7 +67,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option() { - if lof64 > 180.0 || lof64 < -180.0 { + if !(-180.0..=180.0).contains(&lof64) { return None; } lof64 @@ -119,7 +119,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option 0 { + if !result.is_empty() { result.push('\n'); } result.push_str(value); diff --git a/src/client/result/ProductResultParser.rs b/src/client/result/ProductResultParser.rs index f1cb654..53b8606 100644 --- a/src/client/result/ProductResultParser.rs +++ b/src/client/result/ProductResultParser.rs @@ -46,14 +46,14 @@ pub fn parse(result: &RXingResult) -> Option { } // Not actually checking the checksum again here - let normalizedProductID; + let normalizedProductID= // Expand UPC-E for purposes of searching if format == &BarcodeFormat::UPC_E && rawText.len() == 8 { // unimplemented!("UPCEReader is required to parse this"); - normalizedProductID = crate::oned::convertUPCEtoUPCA(&rawText); + crate::oned::convertUPCEtoUPCA(&rawText) } else { - normalizedProductID = rawText.clone(); - } + rawText.clone() + }; Some(ParsedClientResult::ProductResult( ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID), diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index 0dfcbfb..106406a 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -97,9 +97,9 @@ lazy_static! { } // const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+"); -const AMPERSAND: &'static str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&"); -const EQUALS: &'static str = "="; //private static final Pattern EQUALS = Pattern.compile("="); -const BYTE_ORDER_MARK: &'static str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff"; +const AMPERSAND: &str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&"); +const EQUALS: &str = "="; //private static final Pattern EQUALS = Pattern.compile("="); +const BYTE_ORDER_MARK: &str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff"; // const EMPTY_STR_ARRAY: &'static str = ""; @@ -108,7 +108,7 @@ pub fn getMassagedText(result: &RXingResult) -> String { if text.starts_with(BYTE_ORDER_MARK) { text = text[1..].to_owned(); } - return text; + text } pub fn parse_result_with_parsers( @@ -117,8 +117,8 @@ pub fn parse_result_with_parsers( ) -> ParsedClientResult { for parser in parsers { let result = parser(the_rxing_result); - if result.is_some() { - return result.unwrap(); + if let Some(res) = result { + return res; } } parseRXingResult(the_rxing_result) @@ -150,8 +150,8 @@ pub fn parseRXingResult(the_rxing_result: &RXingResult) -> ParsedClientResult { for parser in PARSERS { let result = parser(the_rxing_result); - if result.is_some() { - return result.unwrap(); + if let Some(res) = result { + return res; } } // ParsedRXingResult result = parser.parse(theRXingResult); @@ -193,7 +193,7 @@ pub fn maybeWrap(value: Option) -> Option> { if value.is_none() { None } else { - Some(vec![value.unwrap().to_owned()]) + Some(vec![value.unwrap()]) } } @@ -222,16 +222,16 @@ pub fn unescapeBackslash(escaped: &str) -> String { } pub fn parseHexDigit(c: char) -> i32 { - if c >= '0' && c <= '9' { - return (c as u8 - '0' as u8) as i32; + if ('0'..='9').contains(&c) { + return (c as u8 - b'0') as i32; } - if c >= 'a' && c <= 'f' { - return 10 + (c as u8 - 'a' as u8) as i32; + if ('a'..='f').contains(&c) { + return 10 + (c as u8 - b'a') as i32; } - if c >= 'A' && c <= 'F' { - return 10 + (c as u8 - 'A' as u8) as i32; + if ('A'..='F').contains(&c) { + return 10 + (c as u8 - b'A') as i32; } - return -1; + -1 } pub fn isStringOfDigits(value: &str, length: usize) -> bool { @@ -242,16 +242,12 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool { if value.is_empty() || length == 0 { return false; } - let max = offset as usize + length; + let max = offset + length; - let sub_seq = &value[offset as usize..max]; + let sub_seq = &value[offset..max]; let is_a_match = if let Some(mtch) = DIGITS.find(sub_seq) { - if mtch.start() == 0 && mtch.end() == sub_seq.len() { - true - } else { - false - } + mtch.start() == 0 && mtch.end() == sub_seq.len() } else { false }; @@ -261,9 +257,7 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool { pub fn parseNameValuePairs(uri: &str) -> Option> { let paramStart = uri.find('?'); - if paramStart.is_none() { - return None; - } + paramStart?; let mut result = HashMap::with_capacity(3); let paramStart = paramStart.unwrap_or(0); @@ -285,7 +279,7 @@ pub fn appendKeyValue(keyValue: &str, result: &mut HashMap) { let kvp: Vec<&str> = keyValueTokens.take(2).collect(); if let [key, value] = kvp[..] { - let p_value = urlDecode(value).unwrap_or("".to_owned()); + let p_value = urlDecode(value).unwrap_or_else(|_| "".to_owned()); result.insert(key.to_owned(), p_value); } @@ -305,9 +299,9 @@ pub fn urlDecode(encoded: &str) -> Result { if let Ok(decoded) = decode(encoded) { Ok(decoded.to_string()) } else { - Err(Exceptions::IllegalStateException( + Err(Exceptions::IllegalStateException(Some( "UnsupportedEncodingException".to_owned(), - )) + ))) } } @@ -334,14 +328,13 @@ pub fn matchPrefixedField( let start = i; // Found the start of a match here let mut more = true; while more { - let next_index = rawText[i..].find(endChar); - if next_index.is_none() { + if let Some(next_index) = rawText[i..].find(endChar) { + i += next_index; + } else { // No terminating end character? uh, done. Set i such that loop terminates and break i = rawText.len(); more = false; continue; - } else { - i += next_index.unwrap(); } if countPrecedingBackslashes(rawText, i) % 2 != 0 { @@ -399,7 +392,7 @@ pub fn countPrecedingBackslashes(s: &str, pos: usize) -> u32 { break; } } - return count; + count } pub fn matchSinglePrefixedField( @@ -409,11 +402,7 @@ pub fn matchSinglePrefixedField( trim: bool, ) -> Option { let matches = matchPrefixedField(prefix, rawText, endChar, trim); - if let Some(m) = matches { - Some(m[0].clone()) - } else { - None - } + matches.map(|m| m[0].clone()) // return matches == null ? null : matches[0]; } diff --git a/src/client/result/SMSMMSResultParser.rs b/src/client/result/SMSMMSResultParser.rs index 4bf47e9..e5f9e66 100644 --- a/src/client/result/SMSMMSResultParser.rs +++ b/src/client/result/SMSMMSResultParser.rs @@ -69,13 +69,13 @@ pub fn parse(result: &RXingResult) -> Option { // Drop sms, query portion let query_start = raw_text[4..].find('?'); - let sms_uriwithout_query; + let sms_uriwithout_query= // If it's not query syntax, the question mark is part of the subject or message if query_start.is_none() || !querySyntax { - sms_uriwithout_query = &raw_text[4..]; + &raw_text[4..] } else { - sms_uriwithout_query = &raw_text[4..4 + query_start.unwrap_or(0)]; - } + &raw_text[4..4 + query_start.unwrap_or(0)] + }; let mut last_comma: i32 = -1; let mut comma: i32 = sms_uriwithout_query[(last_comma + 1) as usize..] @@ -103,7 +103,7 @@ pub fn parse(result: &RXingResult) -> Option { ); Some(ParsedClientResult::SMSResult( - SMSParsedRXingResult::with_arrays(numbers, vias, subject.to_owned(), body.to_owned()), + SMSParsedRXingResult::with_arrays(numbers, vias, subject, body), )) // return new SMSParsedRXingResult(numbers.toArray(EMPTY_STR_ARRAY), @@ -120,8 +120,8 @@ fn add_number_via(numbers: &mut Vec, vias: &mut Vec, number_part // if numberEnd < 0 { numbers.push(number_part[..number_end].to_string()); let maybe_via = &number_part[number_end + 1..]; - let via = if maybe_via.starts_with("via=") { - &maybe_via[4..] + let via = if let Some(stripped) = maybe_via.strip_prefix("via=") { + stripped } else { "" }; diff --git a/src/client/result/TelParsedResult.rs b/src/client/result/TelParsedResult.rs index ce9ca43..e4de718 100644 --- a/src/client/result/TelParsedResult.rs +++ b/src/client/result/TelParsedResult.rs @@ -60,6 +60,6 @@ impl TelParsedRXingResult { } pub fn getTitle(&self) -> &str { - &&self.title + &self.title } } diff --git a/src/client/result/TelResultParser.rs b/src/client/result/TelResultParser.rs index 023d3fb..37370e9 100644 --- a/src/client/result/TelResultParser.rs +++ b/src/client/result/TelResultParser.rs @@ -35,8 +35,8 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option return None; } // Normalize "TEL:" to "tel:" - let telURI = if rawText.starts_with("TEL:") { - format!("tel:{}", &rawText[4..]) + let telURI = if let Some(stripped) = rawText.strip_prefix("TEL:") { + format!("tel:{}", stripped) } else { rawText.clone() }; @@ -50,7 +50,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option // let number = queryStart < 0 ? : ; Some(ParsedClientResult::TelResult(TelParsedRXingResult::new( number.to_owned(), - telURI.to_owned(), + telURI, "".to_owned(), ))) } diff --git a/src/client/result/URIParsedResult.rs b/src/client/result/URIParsedResult.rs index dc76340..f1b3b2b 100644 --- a/src/client/result/URIParsedResult.rs +++ b/src/client/result/URIParsedResult.rs @@ -63,7 +63,7 @@ impl URIParsedRXingResult { */ #[deprecated] pub fn is_possibly_malicious_uri(&self) -> bool { - return URIResultParser::is_possibly_malicious_uri(&self.uri); + URIResultParser::is_possibly_malicious_uri(&self.uri) } /** @@ -98,6 +98,6 @@ impl URIParsedRXingResult { // if (nextSlash < 0) { // nextSlash = uri.length(); // } - return ResultParser::isSubstringOfDigits(uri, start, nextSlash - start); + ResultParser::isSubstringOfDigits(uri, start, nextSlash - start) } } diff --git a/src/client/result/URIResultParser.rs b/src/client/result/URIResultParser.rs index 8a5d4cb..9593474 100644 --- a/src/client/result/URIResultParser.rs +++ b/src/client/result/URIResultParser.rs @@ -44,7 +44,7 @@ lazy_static! { Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap(); } -const ALLOWED_URI_CHARS_PATTERN: &'static str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+"; +const ALLOWED_URI_CHARS_PATTERN: &str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+"; // const USER_IN_HOST: &'static str = ":/*([^/@]+)@[^/]+"; /// See http://www.ietf.org/rfc/rfc2396.txt // const URL_WITH_PROTOCOL_PATTERN: &'static str = "[a-zA-Z][a-zA-Z0-9+-.]+:"; @@ -83,11 +83,7 @@ pub fn parse(result: &RXingResult) -> Option { */ pub fn is_possibly_malicious_uri(uri: &str) -> bool { let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) { - if fnd.start() == 0 && fnd.end() == uri.len() { - true - } else { - false - } + fnd.start() == 0 && fnd.end() == uri.len() } else { false }; @@ -97,7 +93,7 @@ pub fn is_possibly_malicious_uri(uri: &str) -> bool { } pub fn is_basically_valid_uri(uri: &str) -> bool { - if uri.contains(" ") { + if uri.contains(' ') { // Quick hack check for a common case return false; } @@ -111,12 +107,7 @@ pub fn is_basically_valid_uri(uri: &str) -> bool { // let m = Regex::new(URL_WITHOUT_PROTOCOL_PATTERN).expect("Regex patterns should always copile"); //.matcher(uri); if let Some(found) = URL_WITHOUT_PROTOCOL_PATTERN.find(uri) { - if found.start() == 0 { - // match at start only - true - } else { - false - } + found.start() == 0 } else { false } diff --git a/src/client/result/VCardResultParser.rs b/src/client/result/VCardResultParser.rs index 21f1ea3..6b4e298 100644 --- a/src/client/result/VCardResultParser.rs +++ b/src/client/result/VCardResultParser.rs @@ -58,9 +58,9 @@ lazy_static! { // const NEWLINE_ESCAPE: &'static str = "\\\\[nN]"; // const VCARD_ESCAPES: &'static str = "\\\\([,;\\\\])"; // const EQUALS: &'static str = "="; -const SEMICOLON: &'static str = ";"; +const SEMICOLON: &str = ";"; // const UNESCAPED_SEMICOLONS: &'static str = "(? Option { let urls = matchVCardPrefixedField("URL", &rawText, true, false); let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false); let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false); - let geo = if geoString.is_none() { - Vec::new() - } else { + let geo = if let Some(geo_string) = geoString { SEMICOLON_OR_COMMA - .split(&geoString.unwrap()[0]) + .split(&geo_string[0]) .map(|x| x.to_owned()) .collect() // SEMICOLON_OR_COMMA.split(geoString.unwrap()[0]) + } else { + Vec::new() }; // if geo.len() != 2 { // geo = null; @@ -322,7 +322,7 @@ pub fn matchVCardPrefixedField( // matches.add(match); // } else { metadata.push(element); - matches.push(metadata.into_iter().map(|s| s.to_owned()).collect()); + matches.push(metadata.into_iter().collect()); // } i += 1; } else { @@ -414,29 +414,22 @@ fn decodeQuotedPrintable(value: &str, charset: &str) -> String { } fn maybeAppendFragment(fragmentBuffer: &mut Vec, charset: &str, result: &mut String) { - if fragmentBuffer.len() > 0 { + if !fragmentBuffer.is_empty() { let fragmentBytes = fragmentBuffer.clone(); let fragment; if charset.is_empty() { - fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned()); + fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned()); // fragment = new String(fragmentBytes, StandardCharsets.UTF_8); - } else { - if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) { - fragment = if let Ok(encoded_result) = - enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict) - { - encoded_result - } else { - String::from_utf8(fragmentBytes).unwrap_or("".to_owned()) - } + } else if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) { + fragment = if let Ok(encoded_result) = + enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict) + { + encoded_result } else { - fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned()) + String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned()) } - // try { - // fragment = new String(fragmentBytes, charset); - // } catch (UnsupportedEncodingException e) { - // fragment = new String(fragmentBytes, StandardCharsets.UTF_8); - // } + } else { + fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned()) } fragmentBuffer.clear(); result.push_str(&fragment); @@ -505,7 +498,7 @@ fn toTypes(lists: Option>>) -> Vec { if let Some(value) = list.get(0) { if !value.is_empty() { let mut v_type = String::new(); - let final_value = list.get(list.len() - 1).unwrap_or(&"".to_owned()).clone(); + let final_value = list.last().unwrap_or(&"".to_owned()).clone(); if !final_value.is_empty() { for i in 0..list.len() - 1 { // for (int i = 1; i < list.size(); i++) { @@ -553,7 +546,7 @@ fn formatNames(names: &mut Vec>) { for list in names { // for (List list : names) { let mut pos = 0; - while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find("=") { + while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find('=') { pos += 1; } let name = list.get(pos).unwrap_or(&"".to_owned()).clone(); @@ -584,9 +577,9 @@ fn formatNames(names: &mut Vec>) { } } -fn maybeAppendComponent(components: &Vec, i: usize, newName: &mut String) { +fn maybeAppendComponent(components: &[String], i: usize, newName: &mut String) { if !components[i].is_empty() { - if newName.len() > 0 { + if !newName.is_empty() { newName.push(' '); } newName.push_str(&components[i]); diff --git a/src/client/result/VEventResultParser.rs b/src/client/result/VEventResultParser.rs index 2840011..7bae8ca 100644 --- a/src/client/result/VEventResultParser.rs +++ b/src/client/result/VEventResultParser.rs @@ -32,7 +32,7 @@ use super::{CalendarParsedRXingResult, ParsedClientResult, ResultParser, VCardRe */ pub fn parse(result: &RXingResult) -> Option { let rawText = ResultParser::getMassagedText(result); - if let None = rawText.find("BEGIN:VEVENT") { + if !rawText.contains("BEGIN:VEVENT") { return None; } // if (vEventStart < 0) { @@ -51,9 +51,10 @@ pub fn parse(result: &RXingResult) -> Option { let mut attendees = matchVCardPrefixedField("ATTENDEE", &rawText); if !attendees.is_empty() { - for i in 0..attendees.len() { + for attendee in &mut attendees { + // for i in 0..attendees.len() { // for (int i = 0; i < attendees.length; i++) { - attendees[i] = stripMailto(&attendees[i]); + *attendee = stripMailto(attendee); } } let description = matchSingleVCardPrefixedField("DESCRIPTION", &rawText); @@ -64,30 +65,19 @@ pub fn parse(result: &RXingResult) -> Option { if geoString.is_empty() { latitude = f64::NAN; longitude = f64::NAN; - } else { - if let Some(semicolon) = geoString.find(';') { - latitude = if let Ok(l) = geoString[..semicolon].parse() { - l - } else { - return None; - }; - longitude = if let Ok(l) = geoString[semicolon + 1..].parse() { - l - } else { - return None; - } + } else if let Some(semicolon) = geoString.find(';') { + latitude = if let Ok(l) = geoString[..semicolon].parse() { + l + } else { + return None; + }; + longitude = if let Ok(l) = geoString[semicolon + 1..].parse() { + l } else { return None; } - // if (semicolon < 0) { - // return null; - // } - // try { - // latitude = Double.parseDouble(geoString.substring(0, semicolon)); - // longitude = Double.parseDouble(geoString.substring(semicolon + 1)); - // } catch (NumberFormatException ignored) { - // return null; - // } + } else { + return None; } if let Ok(cpr) = CalendarParsedRXingResult::new( @@ -159,9 +149,10 @@ fn matchVCardPrefixedField(prefix: &str, rawText: &str) -> Vec { } else { let size = values.len(); let mut result = vec!["".to_owned(); size]; //new String[size]; - for i in 0..size { + for (i, res) in result.iter_mut().enumerate().take(size) { + // for i in 0..size { // for (int i = 0; i < size; i++) { - result[i] = values.get(i).unwrap().get(0).unwrap().clone(); + *res = values.get(i).unwrap().get(0).unwrap().clone(); } result } diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 11abae3..d82e704 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -49,9 +49,7 @@ pub fn parse(result: &RXingResult) -> Option { let raw_text_res = result.getText().trim(); let raw_text = IOQ_MATCHER.replace_all(raw_text_res, "").to_string(); // rawText = IOQ.matcher(rawText).replaceAll("").trim(); - if let None = AZ09_MATCHER.find(&raw_text) { - return None; - } + AZ09_MATCHER.find(&raw_text)?; // if !AZ09.matcher(rawText).matches() { // return null; // } @@ -95,8 +93,8 @@ pub fn parse(result: &RXingResult) -> Option { // } } -const IOQ: &'static str = "[IOQ]"; -const AZ09: &'static str = "[A-Z0-9]{17}"; +const IOQ: &str = "[IOQ]"; +const AZ09: &str = "[A-Z0-9]{17}"; fn check_checksum(vin: &str) -> Result { let mut sum = 0; @@ -111,13 +109,13 @@ fn check_checksum(vin: &str) -> Result { fn vin_char_value(c: char) -> Result { match c { - 'A'..='I' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 1), - 'J'..='R' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1), - 'S'..='Z' => Ok((c as u8 as u32 - 'S' as u8 as u32) + 2), - '0'..='9' => Ok(c as u8 as u32 - '0' as u8 as u32), - _ => Err(Exceptions::IllegalArgumentException( + 'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1), + 'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1), + 'S'..='Z' => Ok((c as u8 as u32 - b'S' as u32) + 2), + '0'..='9' => Ok(c as u8 as u32 - b'0' as u32), + _ => Err(Exceptions::IllegalArgumentException(Some( "vin char out of range".to_owned(), - )), + ))), } // if c >= 'A' && c <= 'I' { // return Ok((c as u8 as u32 - 'A' as u8 as u32) + 1); @@ -142,9 +140,9 @@ fn vin_position_weight(position: usize) -> Result { 8 => Ok(10), 9 => Ok(0), 10..=17 => Ok(19 - position), - _ => Err(Exceptions::IllegalArgumentException( + _ => Err(Exceptions::IllegalArgumentException(Some( "vin position weight out of bounds".to_owned(), - )), + ))), } // if position >= 1 && position <= 7 { // return 9 - position; @@ -163,11 +161,11 @@ fn vin_position_weight(position: usize) -> Result { fn check_char(remainder: u8) -> Result { match remainder { - 0..=9 => Ok(('0' as u8 + remainder) as char), + 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), - _ => Err(Exceptions::IllegalArgumentException( + _ => Err(Exceptions::IllegalArgumentException(Some( "remainder too high".to_owned(), - )), + ))), } // if remainder < 10 { // return Ok(('0' as u8 + remainder) as char); @@ -182,16 +180,16 @@ fn check_char(remainder: u8) -> Result { fn model_year(c: char) -> Result { match c { - 'E'..='H' => Ok((c as u8 as u32 - 'E' as u8 as u32) + 1984), - 'J'..='N' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1988), + 'E'..='H' => Ok((c as u8 as u32 - b'E' as u32) + 1984), + 'J'..='N' => Ok((c as u8 as u32 - b'J' as u32) + 1988), 'P' => Ok(1993), - 'R'..='T' => Ok((c as u8 as u32 - 'R' as u8 as u32) + 1994), - 'V'..='Y' => Ok((c as u8 as u32 - 'V' as u8 as u32) + 1997), - '1'..='9' => Ok((c as u8 as u32 - '1' as u8 as u32) + 2001), - 'A'..='D' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 2010), - _ => Err(Exceptions::IllegalArgumentException(String::from( + 'R'..='T' => Ok((c as u8 as u32 - b'R' as u32) + 1994), + 'V'..='Y' => Ok((c as u8 as u32 - b'V' as u32) + 1997), + '1'..='9' => Ok((c as u8 as u32 - b'1' as u32) + 2001), + 'A'..='D' => Ok((c as u8 as u32 - b'A' as u32) + 2010), + _ => Err(Exceptions::IllegalArgumentException(Some(String::from( "model year argument out of range", - ))), + )))), } // if c >= 'E' && c <= 'H' { // return (c - 'E') + 1984; @@ -218,24 +216,24 @@ fn model_year(c: char) -> Result { } fn country_code(wmi: &str) -> Option<&'static str> { - let c1 = wmi.chars().nth(0).unwrap(); + let c1 = wmi.chars().next().unwrap(); let c2 = wmi.chars().nth(1).unwrap(); match c1 { '1' | '4' | '5' => Some("US"), '2' => Some("CA"), - '3' if c2 >= 'A' && c2 <= 'W' => Some("MX"), - '9' if ((c2 >= 'A' && c2 <= 'E') || (c2 >= '3' && c2 <= '9')) => Some("BR"), - 'J' if (c2 >= 'A' && c2 <= 'T') => Some("JP"), - 'K' if (c2 >= 'L' && c2 <= 'R') => Some("KO"), + '3' if ('A'..='W').contains(&c2) => Some("MX"), + '9' if (('A'..='E').contains(&c2) || ('3'..='9').contains(&c2)) => Some("BR"), + 'J' if ('A'..='T').contains(&c2) => Some("JP"), + 'K' if ('L'..='R').contains(&c2) => Some("KO"), 'L' => Some("CN"), - 'M' if (c2 >= 'A' && c2 <= 'E') => Some("IN"), - 'S' if (c2 >= 'A' && c2 <= 'M') => Some("UK"), - 'S' if (c2 >= 'N' && c2 <= 'T') => Some("DE"), - 'V' if (c2 >= 'F' && c2 <= 'R') => Some("FR"), - 'V' if (c2 >= 'S' && c2 <= 'W') => Some("ES"), + 'M' if ('A'..='E').contains(&c2) => Some("IN"), + 'S' if ('A'..='M').contains(&c2) => Some("UK"), + 'S' if ('N'..='T').contains(&c2) => Some("DE"), + 'V' if ('F'..='R').contains(&c2) => Some("FR"), + 'V' if ('S'..='W').contains(&c2) => Some("ES"), 'W' => Some("DE"), - 'X' if (c2 == '0' || (c2 >= '3' && c2 <= '9')) => Some("RU"), - 'Z' if (c2 >= 'A' && c2 <= 'R') => Some("IT"), + 'X' if (c2 == '0' || ('3'..='9').contains(&c2)) => Some("RU"), + 'Z' if ('A'..='R').contains(&c2) => Some("IT"), _ => None, } } diff --git a/src/client/result/WifiResultParser.rs b/src/client/result/WifiResultParser.rs index ad18218..3e38642 100644 --- a/src/client/result/WifiResultParser.rs +++ b/src/client/result/WifiResultParser.rs @@ -44,7 +44,7 @@ use super::ResultParser; // impl RXingResultParser for WifiRXingResultParser { pub fn parse(theRXingResult: &crate::RXingResult) -> Option { - const WIFI_TEST: &'static str = "WIFI:"; + const WIFI_TEST: &str = "WIFI:"; let rawText_unstripped = ResultParser::getMassagedText(theRXingResult); if !rawText_unstripped.starts_with(WIFI_TEST) { @@ -52,12 +52,12 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option Option Option Vec { for i in 0..size { // for (int i = 0; i < size; i++) { if bit_set(oldBits, size - i - 1) { - newBits[i / 32 as usize] |= 1 << (i & 0x1F); + newBits[i / 32_usize] |= 1 << (i & 0x1F); } } - return newBits; + newBits } fn bit_set(bits: &[u32], i: usize) -> bool { - return (bits[i / 32] & (1 << (i & 0x1F))) != 0; + (bits[i / 32] & (1 << (i & 0x1F))) != 0 } fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool { @@ -293,7 +293,7 @@ fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool { return false; } } - return true; + true } // } diff --git a/src/common/BitMatrixTestCase.rs b/src/common/BitMatrixTestCase.rs index 107a232..b75ae28 100644 --- a/src/common/BitMatrixTestCase.rs +++ b/src/common/BitMatrixTestCase.rs @@ -61,7 +61,10 @@ fn test_set_region() { // for (int y = 0; y < 5; y++) { for x in 0..5 { // for (int x = 0; x < 5; x++) { - assert_eq!(y >= 1 && y <= 3 && x >= 1 && x <= 3, matrix.get(x, y)); + assert_eq!( + (1..=3).contains(&y) && (1..=3).contains(&x), + matrix.get(x, y) + ); } } } @@ -133,7 +136,10 @@ fn test_rectangular_set_region() { // for (int y = 0; y < 240; y++) { for x in 0..320 { // for (int x = 0; x < 320; x++) { - assert_eq!(y >= 22 && y < 34 && x >= 105 && x < 185, matrix.get(x, y)); + assert_eq!( + (22..34).contains(&y) && (105..185).contains(&x), + matrix.get(x, y) + ); } } } @@ -302,7 +308,7 @@ fn test_xor_case() { centerMatrix.setRegion(1, 1, 1, 1).expect("must set"); let mut invertedCenterMatrix = fullMatrix.clone(); invertedCenterMatrix.unset(1, 1); - let badMatrix = BitMatrix::new(4, 4).unwrap(); + let mut badMatrix = BitMatrix::new(4, 4).unwrap(); test_XOR(&emptyMatrix, &emptyMatrix, &emptyMatrix); test_XOR(&emptyMatrix, ¢erMatrix, ¢erMatrix); @@ -328,7 +334,7 @@ fn test_xor_case() { // // good // } - assert!(badMatrix.clone().xor(&emptyMatrix).is_err()); + assert!(badMatrix.xor(&emptyMatrix).is_err()); // try { // badMatrix.clone().xor(emptyMatrix); // fail(); @@ -344,7 +350,7 @@ pub fn matrix_to_string(result: &BitMatrix) -> String { // for (int i = 0; i < result.getWidth(); i++) { builder.push(if result.get(i, 0) { '1' } else { '0' }); } - return builder; + builder } fn test_XOR(dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) { @@ -378,7 +384,7 @@ fn get_expected(width: u32, height: u32) -> BitMatrix { ); i += 2; } - return result; + result } fn get_input(width: u32, height: u32) -> BitMatrix { @@ -389,7 +395,7 @@ fn get_input(width: u32, height: u32) -> BitMatrix { result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]); i += 2; } - return result; + result } // } diff --git a/src/common/StringUtilsTestCase.rs b/src/common/StringUtilsTestCase.rs index 4148b4f..a7b08ed 100644 --- a/src/common/StringUtilsTestCase.rs +++ b/src/common/StringUtilsTestCase.rs @@ -33,9 +33,10 @@ use crate::common::StringUtils; fn test_random() { let mut r = rand::thread_rng(); let mut bytes: Vec = vec![0; 1000]; - for i in 0..bytes.len() { - bytes[i] = r.gen(); - } + bytes.fill_with(|| r.gen()); + // for byte in &mut bytes { + // *byte = r.gen(); + // } assert_eq!( encoding::all::UTF_8.name(), StringUtils::guessCharset(&bytes, &HashMap::new()).name() @@ -102,7 +103,7 @@ fn test_utf16_le() { ); } -fn do_test(bytes: &Vec, charset: EncodingRef, encoding: &str) { +fn do_test(bytes: &[u8], charset: EncodingRef, encoding: &str) { let guessedCharset = StringUtils::guessCharset(bytes, &HashMap::new()); let guessedEncoding = StringUtils::guessEncoding(bytes, &HashMap::new()); assert_eq!(charset.name(), guessedCharset.name()); diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index ffa4c64..bc05ac1 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -47,16 +47,13 @@ impl BitArray { pub fn with_size(size: usize) -> Self { Self { bits: BitArray::makeArray(size), - size: size, + size, } } // For testing only pub fn with_initial_values(bits: Vec, size: usize) -> Self { - Self { - bits: bits, - size: size, - } + Self { bits, size } } pub fn getSize(&self) -> usize { @@ -64,7 +61,7 @@ impl BitArray { } pub fn getSizeInBytes(&self) -> usize { - return (self.size + 7) / 8; + (self.size + 7) / 8 } fn ensure_capacity(&mut self, newSize: usize) { @@ -148,7 +145,7 @@ impl BitArray { currentBits = !self.bits[bitsOffset] as i64; } let result = (bitsOffset * 32) + currentBits.trailing_zeros() as usize; - return cmp::min(result, self.size); + cmp::min(result, self.size) } /** @@ -171,9 +168,7 @@ impl BitArray { pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::IllegalArgumentException( - "end < start || start < 0 || end > self.size".to_owned(), - )); + return Err(Exceptions::IllegalArgumentException(None)); } if end == start { return Ok(()); @@ -216,9 +211,7 @@ impl BitArray { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::IllegalArgumentException( - "end < start || start < 0 || end > self.size".to_owned(), - )); + return Err(Exceptions::IllegalArgumentException(None)); } if end == start { return Ok(true); // empty range matches @@ -239,7 +232,7 @@ impl BitArray { return Ok(false); } } - return Ok(true); + Ok(true) } pub fn appendBit(&mut self, bit: bool) { @@ -260,9 +253,9 @@ impl BitArray { */ pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { if num_bits > 32 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Num bits must be between 0 and 32".to_owned(), - )); + ))); } if num_bits == 0 { @@ -293,9 +286,9 @@ impl BitArray { pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { if self.size != other.size { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Sizes don't match".to_owned(), - )); + ))); } for i in 0..self.bits.len() { //for (int i = 0; i < bits.length; i++) { @@ -335,7 +328,7 @@ impl BitArray { * significant bit is bit 0. */ pub fn getBitArray(&self) -> &Vec { - return &self.bits; + &self.bits } /** @@ -367,7 +360,7 @@ impl BitArray { } fn makeArray(size: usize) -> Vec { - return vec![0; (size + 31) / 32]; + vec![0; (size + 31) / 32] } // @Override @@ -396,10 +389,16 @@ impl fmt::Display for BitArray { for i in 0..self.size { //for (int i = 0; i < size; i++) { if (i & 0x07) == 0 { - _str.push_str(" "); + _str.push(' '); } _str.push_str(if self.get(i) { "X" } else { "." }); } write!(f, "{}", _str) } } + +impl Default for BitArray { + fn default() -> Self { + Self::new() + } +} diff --git a/src/common/bit_matrix.rs b/src/common/bit_matrix.rs index 6a6ea14..221641e 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -65,9 +65,9 @@ impl BitMatrix { */ pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Both dimensions must be greater than 0".to_owned(), - )); + ))); } Ok(Self { width, @@ -101,17 +101,19 @@ impl BitMatrix { let height: u32 = image.len().try_into().unwrap(); let width: u32 = image[0].len().try_into().unwrap(); let mut bits = BitMatrix::new(width, height).unwrap(); - for i in 0..height as usize { + for (i, imageI) in image.iter().enumerate().take(height as usize) { + // for i in 0..height as usize { //for (int i = 0; i < height; i++) { - let imageI = &image[i]; - for j in 0..width as usize { + // let imageI = &image[i]; + for (j, imageI_j) in imageI.iter().enumerate().take(width as usize) { + // for j in 0..width as usize { //for (int j = 0; j < width; j++) { - if imageI[j] { + if *imageI_j { bits.set(j as u32, i as u32); } } } - return bits; + bits } pub fn parse_strings( @@ -141,9 +143,9 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "row lengths do not match".to_owned(), - )); + ))); } rowStartPos = bitsPos; nRows += 1; @@ -158,10 +160,10 @@ impl BitMatrix { bits[bitsPos] = false; bitsPos += 1; } else { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "illegal character encountered: {}", string_representation[pos..].to_owned() - ))); + )))); } } @@ -172,24 +174,25 @@ impl BitMatrix { // first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "row lengths do not match".to_owned(), - )); + ))); } nRows += 1; } let mut matrix = BitMatrix::new(rowLength.try_into().unwrap(), nRows)?; - for i in 0..bitsPos { + for (i, bit) in bits.iter().enumerate().take(bitsPos) { + // for i in 0..bitsPos { //for (int i = 0; i < bitsPos; i++) { - if bits[i] { + if *bit { matrix.set( (i % rowLength).try_into().unwrap(), (i / rowLength).try_into().unwrap(), ); } } - return Ok(matrix); + Ok(matrix) } /** @@ -201,15 +204,15 @@ impl BitMatrix { */ pub fn get(&self, x: u32, y: u32) -> bool { let offset = y as usize * self.row_size + (x as usize / 32); - return ((self.bits[offset] >> (x & 0x1f)) & 1) != 0; + ((self.bits[offset] >> (x & 0x1f)) & 1) != 0 } pub fn try_get(&self, x: u32, y: u32) -> Result { let offset = y as usize * self.row_size + (x as usize / 32); if offset > self.bits.len() { - return Err(Exceptions::IndexOutOfBoundsException("".to_owned())); + return Err(Exceptions::IndexOutOfBoundsException(None)); } - return Ok(((self.bits[offset] >> (x & 0x1f)) & 1) != 0); + Ok(((self.bits[offset] >> (x & 0x1f)) & 1) != 0) } pub fn check_in_bounds(&self, x: u32, y: u32) -> bool { @@ -263,9 +266,9 @@ impl BitMatrix { pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "input matrix dimensions do not match".to_owned(), - )); + ))); } // let mut rowArray = BitArray::with_size(self.width as usize); for y in 0..self.height { @@ -273,9 +276,10 @@ impl BitMatrix { let offset = y as usize * self.row_size; let rowArray = mask.getRow(y); let row = rowArray.getBitArray(); - for x in 0..self.row_size { + for (x, row_x) in row.iter().enumerate().take(self.row_size) { + // for x in 0..self.row_size { //for (int x = 0; x < rowSize; x++) { - self.bits[offset + x] ^= row[x]; + self.bits[offset + x] ^= *row_x; } } Ok(()) @@ -314,16 +318,16 @@ impl BitMatrix { // )); // } if height < 1 || width < 1 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Height and width must be at least 1".to_owned(), - )); + ))); } let right = left + width; let bottom = top + height; if bottom > self.height || right > self.width { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "The region must fit inside the matrix".to_owned(), - )); + ))); } for y in top..bottom { //for (int y = top; y < bottom; y++) { @@ -361,7 +365,7 @@ impl BitMatrix { //for (int x = 0; x < rowSize; x++) { rw.setBulk(x * 32, self.bits[offset + x]); } - return rw; + rw } /** @@ -395,9 +399,9 @@ impl BitMatrix { self.rotate180(); Ok(()) } - _ => Err(Exceptions::IllegalArgumentException( + _ => Err(Exceptions::IllegalArgumentException(Some( "degrees must be a multiple of 0, 90, 180, or 270".to_owned(), - )), + ))), } } @@ -497,7 +501,7 @@ impl BitMatrix { return None; } - return Some(vec![left, top, right - left + 1, bottom - top + 1]); + Some(vec![left, top, right - left + 1, bottom - top + 1]) } /** @@ -522,7 +526,7 @@ impl BitMatrix { bit += 1; } x += bit; - return Some(vec![x as u32, y as u32]); + Some(vec![x as u32, y as u32]) } pub fn getBottomRightOnBit(&self) -> Option> { @@ -544,28 +548,28 @@ impl BitMatrix { } x += bit; - return Some(vec![x as u32, y as u32]); + Some(vec![x as u32, y as u32]) } /** * @return The width of the matrix */ pub fn getWidth(&self) -> u32 { - return self.width; + self.width } /** * @return The height of the matrix */ pub fn getHeight(&self) -> u32 { - return self.height; + self.height } /** * @return The row size of the matrix */ pub fn getRowSize(&self) -> usize { - return self.row_size; + self.row_size } // @Override @@ -594,7 +598,7 @@ impl BitMatrix { * @return string representation of entire matrix utilizing given strings */ pub fn toString(&self, setString: &str, unsetString: &str) -> String { - return self.buildToString(setString, unsetString, "\n"); + self.buildToString(setString, unsetString, "\n") } /** @@ -624,7 +628,7 @@ impl BitMatrix { } result.push_str(lineSeparator); } - return result; + result } // @Override diff --git a/src/common/bit_source.rs b/src/common/bit_source.rs index efbcad2..1c64f84 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -52,14 +52,14 @@ impl BitSource { * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}. */ pub fn getBitOffset(&self) -> usize { - return self.bit_offset; + self.bit_offset } /** * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}. */ pub fn getByteOffset(&self) -> usize { - return self.byte_offset; + self.byte_offset } /** @@ -69,8 +69,10 @@ impl BitSource { * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available */ pub fn readBits(&mut self, numBits: usize) -> Result { - if numBits < 1 || numBits > 32 || numBits > self.available() { - return Err(Exceptions::IllegalArgumentException(numBits.to_string())); + if !(1..=32).contains(&numBits) || numBits > self.available() { + return Err(Exceptions::IllegalArgumentException(Some( + numBits.to_string(), + ))); } let mut result: u32 = 0; @@ -96,7 +98,7 @@ impl BitSource { // Next read whole bytes if num_bits > 0 { while num_bits >= 8 { - result = (result << 8) | (self.bytes[self.byte_offset] & 0xFF) as u32; + result = (result << 8) | self.bytes[self.byte_offset] as u32; // result = ((result as u16) << 8) as u8 | (self.bytes[self.byte_offset]); self.byte_offset += 1; num_bits -= 8; @@ -112,13 +114,13 @@ impl BitSource { } } - return Ok(result); + Ok(result) } /** * @return number of bits that can be read successfully */ pub fn available(&self) -> usize { - return 8 * (self.bytes.len() - self.byte_offset) - self.bit_offset; + 8 * (self.bytes.len() - self.byte_offset) - self.bit_offset } } diff --git a/src/common/bit_source_builder.rs b/src/common/bit_source_builder.rs index 8826556..2925a36 100644 --- a/src/common/bit_source_builder.rs +++ b/src/common/bit_source_builder.rs @@ -65,3 +65,9 @@ impl BitSourceBuilder { &self.output } } + +impl Default for BitSourceBuilder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/common/character_set_eci.rs b/src/common/character_set_eci.rs index 1360ace..6276b46 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -244,7 +244,9 @@ impl CharacterSetECI { 28 => Ok(CharacterSetECI::Big5), 29 => Ok(CharacterSetECI::GB18030), 30 => Ok(CharacterSetECI::EUC_KR), - _ => Err(Exceptions::NotFoundException("Bad ECI Value".to_owned())), + _ => Err(Exceptions::NotFoundException(Some( + "Bad ECI Value".to_owned(), + ))), } } diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index 807c6b6..af48c34 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -66,9 +66,7 @@ impl GridSampler for DefaultGridSampler { transform: &PerspectiveTransform, ) -> Result { if dimensionX == 0 || dimensionY == 0 { - return Err(Exceptions::NotFoundException( - "getNotFoundInstance".to_owned(), - )); + return Err(Exceptions::NotFoundException(None)); } let mut bits = BitMatrix::new(dimensionX, dimensionY)?; let mut points = vec![0_f32; 2 * dimensionX as usize]; @@ -94,9 +92,9 @@ impl GridSampler for DefaultGridSampler { if points[x].floor() as u32 >= image.getWidth() || points[x + 1].floor() as u32 >= image.getHeight() { - return Err(Exceptions::NotFoundException( + return Err(Exceptions::NotFoundException(Some( "index out of bounds, see documentation in file for explanation".to_owned(), - )); + ))); } if image.get(points[x].floor() as u32, points[x + 1].floor() as u32) { // Black(-ish) pixel @@ -115,6 +113,6 @@ impl GridSampler for DefaultGridSampler { // throw NotFoundException.getNotFoundInstance(); // } } - return Ok(bits); + Ok(bits) } } diff --git a/src/common/detector/MathUtils.rs b/src/common/detector/MathUtils.rs index 9feaa18..d6183a0 100644 --- a/src/common/detector/MathUtils.rs +++ b/src/common/detector/MathUtils.rs @@ -31,7 +31,7 @@ use std::{f32, i32}; * @return nearest {@code int} */ pub fn round(d: f32) -> i32 { - return (d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32; + (d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32 } /** @@ -44,7 +44,7 @@ pub fn round(d: f32) -> i32 { pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 { let xDiff: f64 = (aX - bX).into(); let yDiff: f64 = (aY - bY).into(); - return (xDiff * xDiff + yDiff * yDiff).sqrt() as f32; + (xDiff * xDiff + yDiff * yDiff).sqrt() as f32 } /** @@ -57,7 +57,7 @@ pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 { pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 { let xDiff: f64 = (aX - bX).into(); let yDiff: f64 = (aY - bY).into(); - return (xDiff * xDiff + yDiff * yDiff).sqrt() as f32; + (xDiff * xDiff + yDiff * yDiff).sqrt() as f32 } /** @@ -69,7 +69,7 @@ pub fn sum(array: &[i32]) -> i32 { for a in array { count += a; } - return count; + count } #[cfg(test)] @@ -120,7 +120,7 @@ mod tests { #[test] fn testSum() { - assert_eq!(0, MathUtils::sum(&vec![])); + assert_eq!(0, MathUtils::sum(&[])); assert_eq!(1, MathUtils::sum(&[1])); assert_eq!(4, MathUtils::sum(&[1, 3])); assert_eq!(0, MathUtils::sum(&[-1, 1])); diff --git a/src/common/detector/monochrome_rectangle_detector.rs b/src/common/detector/monochrome_rectangle_detector.rs index dbbd022..1ddbf54 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -55,8 +55,8 @@ impl MonochromeRectangleDetector { let width = self.image.getWidth() as i32; let halfHeight = height / 2; let halfWidth = width / 2; - let deltaY = 1.max(height as i32 / (MAX_MODULES * 8)); - let deltaX = 1.max(width as i32 / (MAX_MODULES * 8)); + let deltaY = 1.max(height / (MAX_MODULES * 8)); + let deltaX = 1.max(width / (MAX_MODULES * 8)); let mut top = 0; let mut bottom = height; @@ -124,7 +124,7 @@ impl MonochromeRectangleDetector { halfWidth / 4, )?; - return Ok(vec![pointA, pointB, pointC, pointD]); + Ok(vec![pointA, pointB, pointC, pointD]) } /** @@ -161,14 +161,13 @@ impl MonochromeRectangleDetector { let mut y: i32 = centerY; let mut x: i32 = centerX; while y < bottom && y >= top && x < right && x >= left { - let range: Option>; - if deltaX == 0 { + let range: Option> = if deltaX == 0 { // horizontal slices, up and down - range = self.blackWhiteRange(y, maxWhiteRun, left, right, true); + self.blackWhiteRange(y, maxWhiteRun, left, right, true) } else { // vertical slices, left and right - range = self.blackWhiteRange(x, maxWhiteRun, top, bottom, false); - } + self.blackWhiteRange(x, maxWhiteRun, top, bottom, false) + }; if range.is_none() { if let Some(lastRange) = lastRange_z { // lastRange was found @@ -178,7 +177,7 @@ impl MonochromeRectangleDetector { if lastRange[1] > centerX { // straddle, choose one or the other based on direction return Ok(RXingResultPoint::new( - lastRange[if deltaY > 0 { 0 } else { 1 }] as f32, + lastRange[usize::from(deltaY <= 0)] as f32, lastY as f32, )); } @@ -192,7 +191,7 @@ impl MonochromeRectangleDetector { if lastRange[1] > centerY { return Ok(RXingResultPoint::new( lastX as f32, - lastRange[if deltaX < 0 { 0 } else { 1 }] as f32, + lastRange[usize::from(deltaX >= 0)] as f32, )); } return Ok(RXingResultPoint::new(lastX as f32, lastRange[0] as f32)); @@ -202,13 +201,13 @@ impl MonochromeRectangleDetector { } } } else { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } lastRange_z = range; y += deltaY; x += deltaX } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } /** @@ -243,10 +242,10 @@ impl MonochromeRectangleDetector { } else { self.image.get(fixedDimension as u32, start as u32) } { - start = start - 1; + start -= 1; } else { let whiteRunStart = start; - start = start - 1; + start -= 1; while start >= minDim && !(if horizontal { self.image.get(start as u32, fixedDimension as u32) @@ -254,7 +253,7 @@ impl MonochromeRectangleDetector { self.image.get(fixedDimension as u32, start as u32) }) { - start = start - 1; + start -= 1; } let whiteRunSize = whiteRunStart - start; if start < minDim || whiteRunSize > maxWhiteRun { @@ -263,7 +262,7 @@ impl MonochromeRectangleDetector { } } } - start = start + 1; + start += 1; // Then try right/down let mut end = center; @@ -273,10 +272,10 @@ impl MonochromeRectangleDetector { } else { self.image.get(fixedDimension as u32, end as u32) } { - end = end + 1; + end += 1; } else { let whiteRunStart = end; - end = end + 1; + end += 1; while end < maxDim && !(if horizontal { self.image.get(end as u32, fixedDimension as u32) @@ -284,7 +283,7 @@ impl MonochromeRectangleDetector { self.image.get(fixedDimension as u32, end as u32) }) { - end = end + 1; + end += 1; } let whiteRunSize = end - whiteRunStart; if end >= maxDim || whiteRunSize > maxWhiteRun { @@ -293,12 +292,12 @@ impl MonochromeRectangleDetector { } } } - end = end - 1; + end -= 1; - return if end > start { + if end > start { Some(vec![start, end]) } else { None - }; + } } } diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index 8b16976..c38337f 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -72,17 +72,17 @@ impl WhiteRectangleDetector { || downInit >= image.getHeight() as i32 || rightInit >= image.getWidth() as i32 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(Self { image: image.clone(), height: image.getHeight() as i32, width: image.getWidth() as i32, - leftInit: leftInit, - rightInit: rightInit, - downInit: downInit, - upInit: upInit, + leftInit, + rightInit, + downInit, + upInit, }) } @@ -218,7 +218,7 @@ impl WhiteRectangleDetector { } if z.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let mut t: Option = None; @@ -236,7 +236,7 @@ impl WhiteRectangleDetector { } if t.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let mut x: Option = None; @@ -254,7 +254,7 @@ impl WhiteRectangleDetector { } if x.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let mut y: Option = None; @@ -272,12 +272,12 @@ impl WhiteRectangleDetector { } if y.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } - return Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())); + Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())) } else { - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } @@ -299,7 +299,7 @@ impl WhiteRectangleDetector { return Some(RXingResultPoint::new(x as f32, y as f32)); } } - return None; + None } /** @@ -339,19 +339,19 @@ impl WhiteRectangleDetector { let tj = t.getY(); if yi < self.width as f32 / 2.0f32 { - return vec![ + vec![ RXingResultPoint::new(ti - CORR as f32, tj + CORR as f32), RXingResultPoint::new(zi + CORR as f32, zj + CORR as f32), RXingResultPoint::new(xi - CORR as f32, xj - CORR as f32), RXingResultPoint::new(yi + CORR as f32, yj - CORR as f32), - ]; + ] } else { - return vec![ + vec![ RXingResultPoint::new(ti + CORR as f32, tj + CORR as f32), RXingResultPoint::new(zi + CORR as f32, zj - CORR as f32), RXingResultPoint::new(xi - CORR as f32, xj + CORR as f32), RXingResultPoint::new(yi - CORR as f32, yj - CORR as f32), - ]; + ] } } @@ -379,6 +379,6 @@ impl WhiteRectangleDetector { } } - return false; + false } } diff --git a/src/common/eci_encoder_set.rs b/src/common/eci_encoder_set.rs index f8661e2..b27494c 100644 --- a/src/common/eci_encoder_set.rs +++ b/src/common/eci_encoder_set.rs @@ -141,7 +141,7 @@ impl ECIEncoderSet { // for (CharsetEncoder encoder : ENCODERS) { if encoder .encode( - &stringToEncode.get(i).unwrap(), + stringToEncode.get(i).unwrap(), encoding::EncoderTrap::Strict, ) .is_ok() @@ -185,9 +185,10 @@ impl ECIEncoderSet { //Compute priorityEncoderIndex by looking up priorityCharset in encoders // if priorityCharset != null { if priorityCharset.is_some() { - for i in 0..encoders.len() { + // for i in 0..encoders.len() { + for (i, encoder) in encoders.iter().enumerate() { // for (int i = 0; i < encoders.length; i++) { - if priorityCharset.as_ref().unwrap().name() == encoders[i].name() { + if priorityCharset.as_ref().unwrap().name() == encoder.name() { priorityEncoderIndexValue = Some(i); break; } @@ -197,13 +198,17 @@ impl ECIEncoderSet { //invariants assert_eq!(encoders[0].name(), encoding::all::ISO_8859_1.name()); Self { - encoders: encoders, + encoders, priorityEncoderIndex: priorityEncoderIndexValue, } } pub fn len(&self) -> usize { - return self.encoders.len(); + self.encoders.len() + } + + pub fn is_empty(&self) -> bool { + self.encoders.is_empty() } pub fn getCharsetName(&self, index: usize) -> &'static str { @@ -213,7 +218,7 @@ impl ECIEncoderSet { pub fn getCharset(&self, index: usize) -> EncodingRef { assert!(index < self.len()); - return self.encoders[index]; + self.encoders[index] } pub fn getECIValue(&self, encoderIndex: usize) -> u32 { @@ -240,9 +245,9 @@ impl ECIEncoderSet { pub fn encode_char(&self, c: &str, encoderIndex: usize) -> Vec { assert!(encoderIndex < self.len()); let encoder = self.encoders[encoderIndex]; - let enc_data = encoder.encode(&c.to_string(), encoding::EncoderTrap::Strict); + let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict); assert!(enc_data.is_ok()); - return enc_data.unwrap(); + enc_data.unwrap() } pub fn encode_string(&self, s: &str, encoderIndex: usize) -> Vec { diff --git a/src/common/eci_string_builder.rs b/src/common/eci_string_builder.rs index 924d434..57e435b 100644 --- a/src/common/eci_string_builder.rs +++ b/src/common/eci_string_builder.rs @@ -163,8 +163,8 @@ impl ECIStringBuilder { /** * @return true iff nothing has been appended */ - pub fn is_empty(&self) -> bool { - return self.current_bytes.is_empty() && self.result.is_empty(); + pub fn is_empty(&mut self) -> bool { + self.current_bytes.is_empty() && self.result.is_empty() } pub fn build_result(mut self) -> Self { @@ -180,3 +180,9 @@ impl fmt::Display for ECIStringBuilder { write!(f, "{}", self.result) } } + +impl Default for ECIStringBuilder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index f737121..3ea3d59 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -72,9 +72,10 @@ impl Binarizer for GlobalHistogramBinarizer { if width < 3 { // Special case for very small images - for x in 0..width { + for (x, lum) in localLuminances.iter().enumerate().take(width) { + // for x in 0..width { // for (int x = 0; x < width; x++) { - if (localLuminances[x] as u32) < blackPoint { + if (*lum as u32) < blackPoint { row.set(x); } } @@ -109,7 +110,7 @@ impl Binarizer for GlobalHistogramBinarizer { &self, source: Box, ) -> Rc> { - return Rc::new(RefCell::new(GlobalHistogramBinarizer::new(source))); + Rc::new(RefCell::new(GlobalHistogramBinarizer::new(source))) } fn getWidth(&self) -> usize { @@ -134,7 +135,7 @@ impl GlobalHistogramBinarizer { height: source.getHeight(), black_matrix: None, black_row_cache: vec![None; source.getHeight()], - source: source, + source, } } @@ -172,7 +173,7 @@ impl GlobalHistogramBinarizer { let offset = y * width; for x in 0..width { // for (int x = 0; x < width; x++) { - let pixel = localLuminances[offset + x] & 0xff; + let pixel = localLuminances[offset + x]; if (pixel as u32) < blackPoint { matrix.set(x as u32, y as u32); } @@ -198,25 +199,27 @@ impl GlobalHistogramBinarizer { let mut maxBucketCount = 0; let mut firstPeak = 0; let mut firstPeakSize = 0; - for x in 0..numBuckets { + for (x, bucket) in buckets.iter().enumerate().take(numBuckets) { + // for x in 0..numBuckets { // for (int x = 0; x < numBuckets; x++) { - if buckets[x] > firstPeakSize { + if *bucket > firstPeakSize { firstPeak = x; - firstPeakSize = buckets[x]; + firstPeakSize = *bucket; } - if buckets[x] > maxBucketCount { - maxBucketCount = buckets[x]; + if *bucket > maxBucketCount { + maxBucketCount = *bucket; } } // Find the second-tallest peak which is somewhat far from the tallest peak. let mut secondPeak = 0; let mut secondPeakScore = 0; - for x in 0..numBuckets { + for (x, bucket) in buckets.iter().enumerate().take(numBuckets) { + // for x in 0..numBuckets { // for (int x = 0; x < numBuckets; x++) { - let distanceToBiggest = (x as i32 - firstPeak as i32).abs() as u32; + let distanceToBiggest = (x as i32 - firstPeak as i32).unsigned_abs(); // Encourage more distant second peaks by multiplying by square of distance. - let score = buckets[x] * distanceToBiggest as u32 * distanceToBiggest as u32; + let score = *bucket * distanceToBiggest * distanceToBiggest; if score > secondPeakScore { secondPeak = x; secondPeakScore = score; @@ -231,9 +234,9 @@ impl GlobalHistogramBinarizer { // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if secondPeak - firstPeak <= numBuckets / 16 { - return Err(Exceptions::NotFoundException( + return Err(Exceptions::NotFoundException(Some( "secondPeak - firstPeak <= numBuckets / 16 ".to_owned(), - )); + ))); } // Find a valley between them that is low and closer to the white peak. diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index 1bcd1bd..29594d1 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -144,9 +144,7 @@ pub trait GridSampler { let x = points[offset] as i32; let y = points[offset + 1] as i32; if x < -1 || x > width.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() { - return Err(Exceptions::NotFoundException( - "getNotFoundInstance".to_owned(), - )); + return Err(Exceptions::NotFoundException(None)); } nudged = false; if x == -1 { @@ -173,9 +171,7 @@ pub trait GridSampler { let x = points[offset as usize] as i32; let y = points[offset as usize + 1] as i32; if x < -1 || x > width.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() { - return Err(Exceptions::NotFoundException( - "getNotFoundInstance".to_owned(), - )); + return Err(Exceptions::NotFoundException(None)); } nudged = false; if x == -1 { diff --git a/src/common/hybrid_binarizer.rs b/src/common/hybrid_binarizer.rs index 7322f5a..6d6e75f 100644 --- a/src/common/hybrid_binarizer.rs +++ b/src/common/hybrid_binarizer.rs @@ -99,16 +99,16 @@ impl HybridBinarizer { let ghb = GlobalHistogramBinarizer::new(source); Self { black_matrix: None, - ghb: ghb, + ghb, } } fn calculateBlackMatrix(ghb: &mut GlobalHistogramBinarizer) -> Result { - let matrix; + // let matrix; let source = ghb.getLuminanceSource(); let width = source.getWidth(); let height = source.getHeight(); - if width >= HybridBinarizer::MINIMUM_DIMENSION + let matrix = if width >= HybridBinarizer::MINIMUM_DIMENSION && height >= HybridBinarizer::MINIMUM_DIMENSION { let luminances = source.getMatrix(); @@ -138,12 +138,12 @@ impl HybridBinarizer { &black_points, &mut new_matrix, ); - matrix = Ok(new_matrix); + Ok(new_matrix) } else { // If the image is too small, fall back to the global histogram approach. let m = ghb.getBlackMatrix()?; - matrix = Ok(m.clone()); - } + Ok(m.clone()) + }; // dbg!(matrix.to_string()); matrix } @@ -159,7 +159,7 @@ impl HybridBinarizer { sub_height: u32, width: u32, height: u32, - black_points: &Vec>, + black_points: &[Vec], matrix: &mut BitMatrix, ) { let maxYOffset = height - HybridBinarizer::BLOCK_SIZE as u32; diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index bfa48e1..feb22f9 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -52,7 +52,7 @@ impl ECIInput for MinimalECIInput { * @return the number of {@code char}s in this sequence */ fn length(&self) -> usize { - return self.bytes.len(); + self.bytes.len() } /** @@ -73,13 +73,15 @@ impl ECIInput for MinimalECIInput { */ fn charAt(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); + return Err(Exceptions::IndexOutOfBoundsException(Some( + index.to_string(), + ))); } if self.isECI(index as u32)? { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "value at {} is not a character but an ECI", index - ))); + )))); } if self.isFNC1(index)? { Ok(self.fnc1 as u8 as char) @@ -110,16 +112,18 @@ impl ECIInput for MinimalECIInput { */ fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { if start > end || end > self.length() { - return Err(Exceptions::IndexOutOfBoundsException(start.to_string())); + return Err(Exceptions::IndexOutOfBoundsException(Some( + start.to_string(), + ))); } let mut result = String::new(); for i in start..end { // for (int i = start; i < end; i++) { if self.isECI(i as u32)? { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "value at {} is not a character but an ECI", i - ))); + )))); } result.push_str(&self.charAt(i)?.to_string()); } @@ -139,7 +143,9 @@ impl ECIInput for MinimalECIInput { */ fn isECI(&self, index: u32) -> Result { if index >= self.length() as u32 { - return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); + return Err(Exceptions::IndexOutOfBoundsException(Some( + index.to_string(), + ))); } Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) } @@ -164,19 +170,21 @@ impl ECIInput for MinimalECIInput { */ fn getECIValue(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); + return Err(Exceptions::IndexOutOfBoundsException(Some( + index.to_string(), + ))); } if !self.isECI(index as u32)? { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "value at {} is not an ECI but a character", index - ))); + )))); } Ok((self.bytes[index] as u32 - 256) as i32) } fn haveNCharacters(&self, index: usize, n: usize) -> bool { - if index + n - 1 >= self.bytes.len() { + if index + n > self.bytes.len() { return false; } for i in 0..n { @@ -185,7 +193,7 @@ impl ECIInput for MinimalECIInput { return false; } } - return true; + true } } impl MinimalECIInput { @@ -210,13 +218,14 @@ impl MinimalECIInput { let bytes = if encoderSet.len() == 1 { //optimization for the case when all can be encoded without ECI in ISO-8859-1 let mut bytes_hld = vec![0; stringToEncode.len()]; - for i in 0..stringToEncode.len() { + for (i, byt) in bytes_hld.iter_mut().enumerate().take(stringToEncode.len()) { + // for i in 0..stringToEncode.len() { // for (int i = 0; i < bytes.length; i++) { let c = stringToEncode.get(i).unwrap(); - bytes_hld[i] = if fnc1.is_some() && c == fnc1.as_ref().unwrap() { + *byt = if fnc1.is_some() && c == fnc1.as_ref().unwrap() { 1000 } else { - c.chars().nth(0).unwrap() as u16 + c.chars().next().unwrap() as u16 }; } bytes_hld @@ -225,10 +234,10 @@ impl MinimalECIInput { }; Self { - bytes: bytes, + bytes, fnc1: if let Some(fnc1_exists) = fnc1 { //}.as_ref().unwrap().chars().nth(0).unwrap() as u16, - fnc1_exists.chars().nth(0).unwrap() as u16 + fnc1_exists.chars().next().unwrap() as u16 } else { 1000 }, @@ -252,12 +261,14 @@ impl MinimalECIInput { */ pub fn isFNC1(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); + return Err(Exceptions::IndexOutOfBoundsException(Some( + index.to_string(), + ))); } Ok(self.bytes[index] == 1000) } - fn addEdge(edges: &mut Vec>>>, to: usize, edge: Rc) { + fn addEdge(edges: &mut [Vec>>], to: usize, edge: Rc) { if edges[to][edge.encoderIndex].is_none() || edges[to][edge.encoderIndex] .clone() @@ -272,7 +283,7 @@ impl MinimalECIInput { fn addEdges( stringToEncode: &str, encoderSet: &ECIEncoderSet, - edges: &mut Vec>>>, + edges: &mut [Vec>>], from: usize, previous: Option>, fnc1: Option<&str>, @@ -285,7 +296,7 @@ impl MinimalECIInput { //if let Some(fnc1) = fnc1 { if encoderSet.getPriorityEncoderIndex().is_some() && ((fnc1.is_some() - && ch.chars().nth(0).unwrap() == fnc1.as_ref().unwrap().chars().nth(0).unwrap()) + && ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap()) || encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex().unwrap())) { start = encoderSet.getPriorityEncoderIndex().unwrap(); @@ -296,7 +307,7 @@ impl MinimalECIInput { for i in start..end { // for (int i = start; i < end; i++) { if (fnc1.is_some() - && ch.chars().nth(0).unwrap() == fnc1.as_ref().unwrap().chars().nth(0).unwrap()) + && ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap()) || encoderSet.canEncode(ch, i) { Self::addEdge( @@ -380,19 +391,17 @@ impl MinimalECIInput { // 0..0, // [256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16], // ); - intsAL.insert( - 0, - 256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16, - ); + intsAL.insert(0, 256_u16 + encoderSet.getECIValue(c.encoderIndex) as u16); } current = c.previous.clone(); } let mut ints = vec![0; intsAL.len()]; - for i in 0..ints.len() { - // for (int i = 0; i < ints.length; i++) { - ints[i] = *intsAL.get(i).unwrap() as u16; - } - return ints; + // for i in 0..ints.len() { + // // for (int i = 0; i < ints.length; i++) { + // ints[i] = *intsAL.get(i).unwrap(); + // } + ints[..].copy_from_slice(&intsAL[..]); + ints } } @@ -432,7 +441,7 @@ impl InputEdge { String::from(c) }, encoderIndex, - previous: Some(prev.clone()), + previous: Some(prev), cachedTotalSize: size, } } else { diff --git a/src/common/perspective_transform.rs b/src/common/perspective_transform.rs index f5f293e..7bde969 100644 --- a/src/common/perspective_transform.rs +++ b/src/common/perspective_transform.rs @@ -81,7 +81,7 @@ impl PerspectiveTransform { let q_to_s = PerspectiveTransform::quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); let s_to_q = PerspectiveTransform::squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); - return s_to_q.times(&q_to_s); + s_to_q.times(&q_to_s) } pub fn transform_points_single(&self, points: &mut [f32]) { @@ -133,7 +133,7 @@ impl PerspectiveTransform { let dy3 = y0 - y1 + y2 - y3; if dx3 == 0.0f32 && dy3 == 0.0f32 { // Affine - return PerspectiveTransform::new( + PerspectiveTransform::new( x1 - x0, x2 - x1, x0, @@ -143,7 +143,7 @@ impl PerspectiveTransform { 0.0f32, 0.0f32, 1.0f32, - ); + ) } else { let dx1 = x1 - x2; let dx2 = x3 - x2; @@ -152,7 +152,7 @@ impl PerspectiveTransform { let denominator = dx1 * dy2 - dx2 * dy1; let a13 = (dx3 * dy2 - dx2 * dy3) / denominator; let a23 = (dx1 * dy3 - dx3 * dy1) / denominator; - return PerspectiveTransform::new( + PerspectiveTransform::new( x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, @@ -162,7 +162,7 @@ impl PerspectiveTransform { a13, a23, 1.0f32, - ); + ) } } @@ -177,13 +177,12 @@ impl PerspectiveTransform { y3: f32, ) -> Self { // Here, the adjoint serves as the inverse - return PerspectiveTransform::squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3) - .buildAdjoint(); + PerspectiveTransform::squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint() } fn buildAdjoint(&self) -> Self { // Adjoint is the transpose of the cofactor matrix: - return PerspectiveTransform::new( + PerspectiveTransform::new( self.a22 * self.a33 - self.a23 * self.a32, self.a23 * self.a31 - self.a21 * self.a33, self.a21 * self.a32 - self.a22 * self.a31, @@ -193,11 +192,11 @@ impl PerspectiveTransform { self.a12 * self.a23 - self.a13 * self.a22, self.a13 * self.a21 - self.a11 * self.a23, self.a11 * self.a22 - self.a12 * self.a21, - ); + ) } fn times(&self, other: &Self) -> Self { - return PerspectiveTransform::new( + PerspectiveTransform::new( self.a11 * other.a11 + self.a21 * other.a12 + self.a31 * other.a13, self.a11 * other.a21 + self.a21 * other.a22 + self.a31 * other.a23, self.a11 * other.a31 + self.a21 * other.a32 + self.a31 * other.a33, @@ -207,6 +206,6 @@ impl PerspectiveTransform { self.a13 * other.a11 + self.a23 * other.a12 + self.a33 * other.a13, self.a13 * other.a21 + self.a23 * other.a22 + self.a33 * other.a23, self.a13 * other.a31 + self.a23 * other.a32 + self.a33 * other.a33, - ); + ) } } diff --git a/src/common/reedsolomon/ReedSolomonTestCase.rs b/src/common/reedsolomon/ReedSolomonTestCase.rs index 6f90798..4de6b2d 100644 --- a/src/common/reedsolomon/ReedSolomonTestCase.rs +++ b/src/common/reedsolomon/ReedSolomonTestCase.rs @@ -38,9 +38,9 @@ const DECODER_TEST_ITERATIONS: i32 = 10; fn test_data_matrix() { let dm256 = super::get_predefined_genericgf(super::PredefinedGenericGF::DataMatrixField256); // real life test cases - test_encode_decode(&dm256, &vec![142, 164, 186], &vec![114, 25, 5, 88, 102]); + test_encode_decode(dm256, &vec![142, 164, 186], &vec![114, 25, 5, 88, 102]); test_encode_decode( - &dm256, + dm256, &vec![ 0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64, 0x70, 0x65, 0x66, 0x2F, 0x68, 0x70, 0x70, 0x68, 0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71, 0x30, 0x7B, 0x79, 0x6A, @@ -62,7 +62,7 @@ fn test_qr_code() { let qrcf256 = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); // Test case from example given in ISO 18004, Annex I test_encode_decode( - &qrcf256, + qrcf256, &vec![ 0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, @@ -70,7 +70,7 @@ fn test_qr_code() { &vec![0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87, 0x2C, 0x55], ); test_encode_decode( - &qrcf256, + qrcf256, &vec![ 0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F, 0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50, 0x61, 0x67, 0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, @@ -92,28 +92,28 @@ fn test_qr_code() { fn test_aztec() { // real life test cases test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), &vec![0x5, 0x6], &vec![0x3, 0x2, 0xB, 0xB, 0x7], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), &vec![0x0, 0x0, 0x0, 0x9], &vec![0xA, 0xD, 0x8, 0x6, 0x5, 0x6], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), &vec![0x2, 0x8, 0x8, 0x7], &vec![0xE, 0xC, 0xA, 0x9, 0x6, 0x8], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData6), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData6), &vec![0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B], &vec![0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData8), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData8), &vec![ 0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6, 0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA, 0xF8, 0xCE, 0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9, 0x6C, 0x6B, 0x9F, 0x08, @@ -129,7 +129,7 @@ fn test_aztec() { ], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData10), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData10), &vec![ 0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD, 0x02E, 0x056, 0x26A, 0x281, 0x1C2, 0x1A6, 0x296, 0x045, 0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2, @@ -176,7 +176,7 @@ fn test_aztec() { ], ); test_encode_decode( - &super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData12), + super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData12), &vec![ 0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85, 0x69A, 0xA81, 0x709, 0xA6A, 0x584, 0x510, 0x4AA, 0x256, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C, @@ -432,7 +432,7 @@ fn test_encode_decode_random(field: GenericGFRef, dataSize: usize, ecSize: usize ecWords[0..ecSize].clone_from_slice(&message[dataSize..dataSize + ecSize]); //System.arraycopy(message, dataSize, ecWords, 0, ecSize); // check to see if Decoder can fix up to ecWords/2 random errors - test_decoder(&field, &dataWords, &ecWords); + test_decoder(field, &dataWords, &ecWords); } } @@ -536,7 +536,7 @@ fn test_decoder(field: GenericGFRef, dataWords: &Vec, ecWords: &Vec) { ecWords.len(), i ), - &dataWords, + dataWords, &message, ); } @@ -545,7 +545,7 @@ fn test_decoder(field: GenericGFRef, dataWords: &Vec, ecWords: &Vec) { } } -fn assert_data_equals(message: String, expected: &Vec, received: &Vec) { +fn assert_data_equals(message: String, expected: &Vec, received: &[i32]) { for i in 0..expected.len() { //for (int i = 0; i < expected.length; i++) { if expected[i] != received[i] { @@ -553,7 +553,7 @@ fn assert_data_equals(message: String, expected: &Vec, received: &Vec) "{}. Mismatch at {}. Expected {}, got {}", message, i, - array_to_string(&expected), + array_to_string(expected), array_to_string(&received[0..expected.len()]) ); //fail(); @@ -563,12 +563,12 @@ fn assert_data_equals(message: String, expected: &Vec, received: &Vec) fn array_to_string(data: &[i32]) -> String { let mut sb = String::from("{"); - for i in 0..data.len() { + for dtm in data.iter() { //for (int i = 0; i < data.length; i++) { //sb.append(String.format(i > 0 ? ",%X" : "%X", data[i])); - sb.push_str(&format!("{}", data[i])); + sb.push_str(&format!("{}", *dtm)); } - sb.push_str("}"); + sb.push('}'); sb } diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index 8d859ef..48852ec 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -42,10 +42,11 @@ impl GenericGF { let mut expTable = vec![0; size]; let mut logTable = vec![0; size]; let mut x = 1; - for i in 0..size { + for expTableEntry in expTable.iter_mut().take(size) { + // for i in 0..size { //for (int i = 0; i < size; i++) { //expTable.push(x); - expTable[i] = x; + *expTableEntry = x; x *= 2; // we're assuming the generator alpha is 2 if x >= size as i32 { x ^= primitive; @@ -53,10 +54,11 @@ impl GenericGF { x &= sz_m_1; } } - for i in 0..size - 1 { + for (i, loc) in expTable.iter().enumerate().take(size - 1) { + // for i in 0..size - 1 { //for (int i = 0; i < size - 1; i++) { - let loc: usize = expTable[i] as usize; - logTable[loc] = i as i32; + // let loc: usize = expTable[i] as usize; + logTable[*loc as usize] = i as i32; } logTable[0] = 0; @@ -106,7 +108,7 @@ impl GenericGF { } let mut coefficients = vec![0; degree + 1]; coefficients[0] = coefficient; - return GenericGFPoly::new(source, &coefficients).unwrap(); + GenericGFPoly::new(source, &coefficients).unwrap() } /** @@ -115,7 +117,7 @@ impl GenericGF { * @return sum/difference of a and b */ pub fn addOrSubtract(a: i32, b: i32) -> i32 { - return a ^ b; + a ^ b } /** @@ -123,7 +125,7 @@ impl GenericGF { */ pub fn exp(&self, a: i32) -> i32 { // let pos: usize = a.try_into().unwrap(); - return self.expTable[a as usize]; + self.expTable[a as usize] } /** @@ -131,10 +133,10 @@ impl GenericGF { */ pub fn log(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::IllegalArgumentException("".to_owned())); + return Err(Exceptions::IllegalArgumentException(None)); } // let pos: usize = a.try_into().unwrap(); - return Ok(self.logTable[a as usize]); + Ok(self.logTable[a as usize]) } /** @@ -142,11 +144,11 @@ impl GenericGF { */ pub fn inverse(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::ArithmeticException("".to_owned())); + return Err(Exceptions::ArithmeticException(None)); } let log_t_loc: usize = a as usize; let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize; - return Ok(self.expTable[loc]); + Ok(self.expTable[loc]) } /** @@ -159,15 +161,15 @@ impl GenericGF { let a_loc: usize = a as usize; //.try_into().unwrap(); let b_loc: usize = b as usize; //.try_into().unwrap(); let comb_loc: usize = (self.logTable[a_loc] + self.logTable[b_loc]) as usize; - return self.expTable[comb_loc % (self.size - 1)]; + self.expTable[comb_loc % (self.size - 1)] } pub fn getSize(&self) -> usize { - return self.size; + self.size } pub fn getGeneratorBase(&self) -> i32 { - return self.generatorBase; + self.generatorBase } } diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index de63ff0..ab64f54 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -48,13 +48,13 @@ impl GenericGFPoly { * constant polynomial (that is, it is not the monomial "0") */ pub fn new(field: GenericGFRef, coefficients: &Vec) -> Result { - if coefficients.len() == 0 { - return Err(Exceptions::IllegalArgumentException( + if coefficients.is_empty() { + return Err(Exceptions::IllegalArgumentException(Some( "coefficients.len()".to_owned(), - )); + ))); } Ok(Self { - field: field, + field, coefficients: { let coefficients_length = coefficients.len(); if coefficients_length > 1 && coefficients[0] == 0 { @@ -85,28 +85,28 @@ impl GenericGFPoly { } pub fn getCoefficients(&self) -> &Vec { - return &self.coefficients; + &self.coefficients } /** * @return degree of this polynomial */ pub fn getDegree(&self) -> usize { - return self.coefficients.len() - 1; + self.coefficients.len() - 1 } /** * @return true iff this polynomial is the monomial "0" */ pub fn isZero(&self) -> bool { - return self.coefficients[0] == 0; + self.coefficients[0] == 0 } /** * @return coefficient of x^degree term in this polynomial */ pub fn getCoefficient(&self, degree: usize) -> i32 { - return self.coefficients[self.coefficients.len() - 1 - degree]; + self.coefficients[self.coefficients.len() - 1 - degree] } /** @@ -131,18 +131,18 @@ impl GenericGFPoly { for i in 1..size { //for (int i = 1; i < size; i++) { result = GenericGF::addOrSubtract( - self.field.multiply(a as i32, result as i32), + self.field.multiply(a as i32, result), self.coefficients[i], ); } - return result; + result } pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "GenericGFPolys do not have same GenericGF field".to_owned(), - )); + ))); } if self.isZero() { return Ok(other.clone()); @@ -171,15 +171,15 @@ impl GenericGFPoly { ); } - return Ok(GenericGFPoly::new(self.field, &sumDiff)?); + GenericGFPoly::new(self.field, &sumDiff) } pub fn multiply(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "GenericGFPolys do not have same GenericGF field".to_owned(), - )); + ))); } if self.isZero() || other.isZero() { return Ok(self.getZero()); @@ -200,7 +200,7 @@ impl GenericGFPoly { ); } } - return Ok(GenericGFPoly::new(self.field, &product)?); + GenericGFPoly::new(self.field, &product) } pub fn multiply_with_scalar(&self, scalar: i32) -> GenericGFPoly { @@ -213,11 +213,12 @@ impl GenericGFPoly { let size = self.coefficients.len(); let mut product = vec![0; size]; - for i in 0..size { + for (i, prod) in product.iter_mut().enumerate().take(size) { + // for i in 0..size { //for (int i = 0; i < size; i++) { - product[i] = self.field.multiply(self.coefficients[i], scalar); + *prod = self.field.multiply(self.coefficients[i], scalar); } - return GenericGFPoly::new(self.field, &product).unwrap(); + GenericGFPoly::new(self.field, &product).unwrap() } pub fn getZero(&self) -> Self { @@ -238,11 +239,12 @@ impl GenericGFPoly { } let size = self.coefficients.len(); let mut product = vec![0; size + degree]; - for i in 0..size { + for (i, prod) in product.iter_mut().enumerate().take(size) { + // for i in 0..size { //for (int i = 0; i < size; i++) { - product[i] = self.field.multiply(self.coefficients[i], coefficient); + *prod = self.field.multiply(self.coefficients[i], coefficient); } - return Ok(GenericGFPoly::new(self.field, &product)?); + GenericGFPoly::new(self.field, &product) } pub fn divide( @@ -250,14 +252,14 @@ impl GenericGFPoly { other: &GenericGFPoly, ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "GenericGFPolys do not have same GenericGF field".to_owned(), - )); + ))); } if other.isZero() { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Divide by 0".to_owned(), - )); + ))); } let mut quotient = self.getZero(); @@ -267,9 +269,9 @@ impl GenericGFPoly { let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) { Ok(val) => val, Err(_issue) => { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "arithmetic issue".to_owned(), - )) + ))) } }; @@ -285,7 +287,7 @@ impl GenericGFPoly { remainder = remainder.addOrSubtract(&term)?; } - return Ok((quotient, remainder)); + Ok((quotient, remainder)) } } @@ -301,22 +303,20 @@ impl fmt::Display for GenericGFPoly { if coefficient != 0 { if coefficient < 0 { if degree == self.getDegree() { - result.push_str("-"); + result.push('-'); } else { result.push_str(" - "); } coefficient = -coefficient; - } else { - if result.len() > 0 { - result.push_str(" + "); - } + } else if !result.is_empty() { + result.push_str(" + "); } if degree == 0 || coefficient != 1 { if let Ok(alpha_power) = self.field.log(coefficient) { if alpha_power == 0 { - result.push_str("1"); + result.push('1'); } else if alpha_power == 1 { - result.push_str("a"); + result.push('a'); } else { result.push_str("a^"); result.push_str(&format!("{}", alpha_power)); @@ -325,7 +325,7 @@ impl fmt::Display for GenericGFPoly { } if degree != 0 { if degree == 1 { - result.push_str("x"); + result.push('x'); } else { result.push_str("x^"); result.push_str(&format!("{}", degree)); diff --git a/src/common/reedsolomon/reedsolomon_decoder.rs b/src/common/reedsolomon/reedsolomon_decoder.rs index 690c591..e5178bd 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -48,7 +48,7 @@ pub struct ReedSolomonDecoder { impl ReedSolomonDecoder { pub fn new(field: GenericGFRef) -> Self { - Self { field: field } + Self { field } } /** @@ -78,11 +78,7 @@ impl ReedSolomonDecoder { } let syndrome = match GenericGFPoly::new(self.field, &syndromeCoefficients) { Ok(res) => res, - Err(_fail) => { - return Err(Exceptions::ReedSolomonException( - "IllegalArgumentException".to_owned(), - )) - } + Err(_fail) => return Err(Exceptions::ReedSolomonException(None)), }; let sigmaOmega = self.runEuclideanAlgorithm( &GenericGF::buildMonomial(self.field, twoS as usize, 1), @@ -91,21 +87,21 @@ impl ReedSolomonDecoder { )?; let sigma = &sigmaOmega[0]; let omega = &sigmaOmega[1]; - let errorLocations = self.findErrorLocations(&sigma)?; - let errorMagnitudes = self.findErrorMagnitudes(&omega, &errorLocations); + let errorLocations = self.findErrorLocations(sigma)?; + let errorMagnitudes = self.findErrorMagnitudes(omega, &errorLocations); for i in 0..errorLocations.len() { //for (int i = 0; i < errorLocations.length; i++) { let log_value = self.field.log(errorLocations[i] as i32)?; if log_value > received.len() as i32 - 1 { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "Bad error location".to_owned(), - )); + ))); } let position: isize = received.len() as isize - 1 - log_value as isize; if position < 0 { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "Bad error location".to_owned(), - )); + ))); } received[position as usize] = GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); @@ -143,9 +139,9 @@ impl ReedSolomonDecoder { // Divide rLastLast by rLast, with quotient in q and remainder in r if rLast.isZero() { // Oops, Euclidean algorithm already terminated? - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "r_{i-1} was zero".to_owned(), - )); + ))); } r = rLastLast; let mut q = r.getZero(); @@ -153,9 +149,9 @@ impl ReedSolomonDecoder { let dltInverse = match self.field.inverse(denominatorLeadingTerm) { Ok(inv) => inv, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "ArithmetricException".to_owned(), - )) + ))) } }; while r.getDegree() >= rLast.getDegree() && !r.isZero() { @@ -167,24 +163,24 @@ impl ReedSolomonDecoder { { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "IllegalArgumentException".to_owned(), - )) + ))) } }; r = match r.addOrSubtract(&match rLast.multiply_by_monomial(degreeDiff, scale) { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "IllegalArgumentException".to_owned(), - )) + ))) } }) { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "IllegalArgumentException".to_owned(), - )) + ))) } }; } @@ -192,47 +188,47 @@ impl ReedSolomonDecoder { t = match (match q.multiply(&tLast) { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "IllegalArgumentException".to_owned(), - )) + ))) } }) .addOrSubtract(&tLastLast) { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "IllegalArgumentException".to_owned(), - )) + ))) } }; if r.getDegree() >= rLast.getDegree() { - return Err(Exceptions::ReedSolomonException(format!( + return Err(Exceptions::ReedSolomonException(Some(format!( "Division algorithm failed to reduce polynomial? r: {}, rLast: {}", r, rLast - ))); + )))); } } let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "sigmaTilde(0) was zero".to_owned(), - )); + ))); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "ArithmetricException".to_owned(), - )) + ))) } }; let sigma = t.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse); - return Ok(vec![sigma, omega]); + Ok(vec![sigma, omega]) } fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result, Exceptions> { @@ -254,20 +250,20 @@ impl ReedSolomonDecoder { result[e] = match self.field.inverse(i as i32) { Ok(res) => res as usize, Err(_err) => { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "ArithmetricException".to_owned(), - )) + ))) } }; e += 1; } } if e != numErrors { - return Err(Exceptions::ReedSolomonException( + return Err(Exceptions::ReedSolomonException(Some( "Error locator degree does not match number of roots".to_owned(), - )); + ))); } - return Ok(result); + Ok(result) } fn findErrorMagnitudes( @@ -282,14 +278,15 @@ impl ReedSolomonDecoder { //for (int i = 0; i < s; i++) { let xiInverse = self.field.inverse(errorLocations[i] as i32).unwrap(); let mut denominator = 1; - for j in 0..s { + for (j, loc) in errorLocations.iter().enumerate().take(s) { + // for j in 0..s { //for (int j = 0; j < s; j++) { if i != j { //denominator = field.multiply(denominator, // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug. // Below is a funny-looking workaround from Steven Parkes - let term = self.field.multiply(errorLocations[j] as i32, xiInverse); + let term = self.field.multiply(*loc as i32, xiInverse); let termPlus1 = if (term & 0x1) == 0 { term | 1 } else { @@ -306,6 +303,6 @@ impl ReedSolomonDecoder { result[i] = self.field.multiply(result[i], xiInverse); } } - return result; + result } } diff --git a/src/common/reedsolomon/reedsolomon_encoder.rs b/src/common/reedsolomon/reedsolomon_encoder.rs index 6b7c5c6..7fa47a1 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -45,10 +45,7 @@ impl ReedSolomonEncoder { fn buildGenerator(&mut self, degree: usize) -> &GenericGFPoly { if degree >= self.cachedGenerators.len() { - let mut lastGenerator = self - .cachedGenerators - .get(self.cachedGenerators.len() - 1) - .unwrap(); + let mut lastGenerator = self.cachedGenerators.last().unwrap(); let cg_len = self.cachedGenerators.len(); let mut nextGenerator; for d in cg_len..=degree { @@ -71,20 +68,20 @@ impl ReedSolomonEncoder { } } let rv = self.cachedGenerators.get(degree).unwrap(); - return rv; + rv } pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<(), Exceptions> { if ec_bytes == 0 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "No error correction bytes".to_owned(), - )); + ))); } let data_bytes = to_encode.len() - ec_bytes; if data_bytes == 0 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "No data bytes provided".to_owned(), - )); + ))); } let fld = self.field; let generator = self.buildGenerator(ec_bytes); @@ -93,7 +90,7 @@ impl ReedSolomonEncoder { //System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); let mut info = GenericGFPoly::new(fld, &info_coefficients)?; info = info.multiply_by_monomial(ec_bytes, 1)?; - let remainder = &info.divide(&generator)?.1; + let remainder = &info.divide(generator)?.1; let coefficients = remainder.getCoefficients(); let num_zero_coefficients = ec_bytes - coefficients.len(); for i in 0..num_zero_coefficients { diff --git a/src/common/string_utils.rs b/src/common/string_utils.rs index 7320f79..ee1eb8a 100644 --- a/src/common/string_utils.rs +++ b/src/common/string_utils.rs @@ -98,14 +98,13 @@ impl StringUtils { * none of these can possibly be correct */ pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> EncodingRef { - match hints.get(&DecodeHintType::CHARACTER_SET) { - Some(hint) => { - if let DecodeHintValue::CharacterSet(cs_name) = hint { - return encoding::label::encoding_from_whatwg_label(cs_name).unwrap(); - } - } - _ => {} - }; + if let Some(DecodeHintValue::CharacterSet(cs_name)) = + hints.get(&DecodeHintType::CHARACTER_SET) + { + // if let DecodeHintValue::CharacterSet(cs_name) = hint { + return encoding::label::encoding_from_whatwg_label(cs_name).unwrap(); + // } + } // if hints.contains_key(&DecodeHintType::CHARACTER_SET) { // return Charset.forName(hints.get(DecodeHintType.CHARACTER_SET).toString()); // } @@ -141,7 +140,8 @@ impl StringUtils { let utf8bom = bytes.len() > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; - for i in 0..length { + // for i in 0..length { + for value in bytes.iter().take(length).copied() { // for (int i = 0; // i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); // i++) { @@ -149,7 +149,7 @@ impl StringUtils { break; } - let value = bytes[i]; + // let value = bytes[i]; // UTF-8 stuff if can_be_utf8 { @@ -270,6 +270,6 @@ impl StringUtils { return encoding::all::UTF_8; } // Otherwise, we take a wild guess with platform encoding - return encoding::all::UTF_8; + encoding::all::UTF_8 } } diff --git a/src/datamatrix/data_matrix_reader.rs b/src/datamatrix/data_matrix_reader.rs index 5d5f057..d970336 100644 --- a/src/datamatrix/data_matrix_reader.rs +++ b/src/datamatrix/data_matrix_reader.rs @@ -83,7 +83,7 @@ impl Reader for DataMatrixReader { points = detectorRXingResult.getPoints().clone(); } let mut result = RXingResult::new( - decoderRXingResult.getText().clone(), + decoderRXingResult.getText(), decoderRXingResult.getRawBytes().clone(), points.clone(), BarcodeFormat::DATA_MATRIX, @@ -127,10 +127,10 @@ impl DataMatrixReader { */ fn extractPureBits(&self, image: &BitMatrix) -> Result { let Some(leftTopBlack) = image.getTopLeftOnBit() else { - return Err(Exceptions::NotFoundException("".to_owned())) + return Err(Exceptions::NotFoundException(None)) }; let Some(rightBottomBlack) = image.getBottomRightOnBit()else { - return Err(Exceptions::NotFoundException("".to_owned())) + return Err(Exceptions::NotFoundException(None)) }; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -143,7 +143,7 @@ impl DataMatrixReader { let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32; let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32; if matrixWidth <= 0 || matrixHeight <= 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); // throw NotFoundException.getNotFoundInstance(); } @@ -180,12 +180,12 @@ impl DataMatrixReader { x += 1; } if x == width { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let moduleSize = x - leftTopBlack[0]; if moduleSize == 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(moduleSize) diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index 58bae0c..e0b3152 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -60,23 +60,23 @@ impl Writer for DataMatrixWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Found empty contents".to_owned(), - )); + ))); } if format != &BarcodeFormat::DATA_MATRIX { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode DATA_MATRIX, but got {:?}", format - ))); + )))); } if width < 0 || height < 0 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested dimensions can't be negative: {}x{}", width, height - ))); + )))); } // Try to get force shape & min / max size @@ -125,7 +125,7 @@ impl Writer for DataMatrixWriter { if hasEncodingHint { let Some(EncodeHintValue::CharacterSet(char_set_name)) = hints.get(&EncodeHintType::CHARACTER_SET) else { - return Err(Exceptions::IllegalArgumentException("charset does not exist".to_owned())) + return Err(Exceptions::IllegalArgumentException(Some("charset does not exist".to_owned()))) }; charset = encoding::label::encoding_from_whatwg_label(char_set_name); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); @@ -159,7 +159,7 @@ impl Writer for DataMatrixWriter { let symbol_lookup = SymbolInfoLookup::new(); let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else { - return Err(Exceptions::NotFoundException("symbol info is bad".to_owned())) + return Err(Exceptions::NotFoundException(Some("symbol info is bad".to_owned()))) }; //2. step: ECC generation diff --git a/src/datamatrix/decoder/bit_matrix_parser.rs b/src/datamatrix/decoder/bit_matrix_parser.rs index 930f87c..278a04f 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -33,8 +33,8 @@ impl BitMatrixParser { */ pub fn new(bitMatrix: &BitMatrix) -> Result { let dimension = bitMatrix.getHeight(); - if dimension < 8 || dimension > 144 || (dimension & 0x01) != 0 { - return Err(Exceptions::FormatException("".to_owned())); + if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { + return Err(Exceptions::FormatException(None)); } let version = Self::readVersion(bitMatrix)?; @@ -50,7 +50,7 @@ impl BitMatrixParser { } pub fn getVersion(&self) -> &Version { - &self.version + self.version } /** @@ -178,7 +178,7 @@ impl BitMatrixParser { } if resultOffset != self.version.getTotalCodewords() as usize { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } Ok(result) @@ -257,7 +257,7 @@ impl BitMatrixParser { if self.readModule(row, column, numRows, numColumns) { currentByte |= 1; } - return currentByte; + currentByte } /** @@ -302,7 +302,7 @@ impl BitMatrixParser { if self.readModule(3, numColumns - 1, numRows, numColumns) { currentByte |= 1; } - return currentByte; + currentByte } /** @@ -347,7 +347,7 @@ impl BitMatrixParser { if self.readModule(1, numColumns - 1, numRows, numColumns) { currentByte |= 1; } - return currentByte; + currentByte } /** @@ -392,7 +392,7 @@ impl BitMatrixParser { if self.readModule(1, numColumns - 1, numRows, numColumns) { currentByte |= 1; } - return currentByte; + currentByte } /** @@ -437,7 +437,7 @@ impl BitMatrixParser { if self.readModule(3, numColumns - 1, numRows, numColumns) { currentByte |= 1; } - return currentByte; + currentByte } /** @@ -455,9 +455,9 @@ impl BitMatrixParser { let symbolSizeColumns = version.getSymbolSizeColumns(); if bitMatrix.getHeight() != symbolSizeRows { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Dimension of bitMatrix must match the version size".to_owned(), - )); + ))); } let dataRegionSizeRows = version.getDataRegionSizeRows(); diff --git a/src/datamatrix/decoder/data_block.rs b/src/datamatrix/decoder/data_block.rs index 1bc57d7..df208f5 100644 --- a/src/datamatrix/decoder/data_block.rs +++ b/src/datamatrix/decoder/data_block.rs @@ -93,9 +93,11 @@ impl DataBlock { let mut rawCodewordsOffset = 0; for i in 0..shorterBlocksNumDataCodewords { // for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { - for j in 0..numRXingResultBlocks { + + for res in result.iter_mut().take(numRXingResultBlocks) { + // for j in 0..numRXingResultBlocks { // for (int j = 0; j < numRXingResultBlocks; j++) { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset]; + res.codewords[i] = rawCodewords[rawCodewordsOffset]; rawCodewordsOffset += 1; } } @@ -107,10 +109,10 @@ impl DataBlock { } else { numRXingResultBlocks }; - for j in 0..numLongerBlocks { + for res in result.iter_mut().take(numLongerBlocks) { + // for j in 0..numLongerBlocks { // for (int j = 0; j < numLongerBlocks; j++) { - result[j].codewords[longerBlocksNumDataCodewords - 1] = - rawCodewords[rawCodewordsOffset]; + res.codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset]; rawCodewordsOffset += 1; } @@ -136,7 +138,7 @@ impl DataBlock { } if rawCodewordsOffset != rawCodewords.len() { - return Err(Exceptions::IllegalArgumentException("".to_owned())); + return Err(Exceptions::IllegalArgumentException(None)); } Ok(result) diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index 190bc65..02793a3 100644 --- a/src/datamatrix/decoder/decoded_bit_stream_parser.rs +++ b/src/datamatrix/decoder/decoded_bit_stream_parser.rs @@ -137,7 +137,7 @@ pub fn decode(bytes: &[u8]) -> Result { decodeECISegment(&mut bits, &mut result)?; isECIencoded = true; // ECI detection only, atm continue decoding as ASCII } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), }; mode = Mode::ASCII_ENCODE; } @@ -145,7 +145,7 @@ pub fn decode(bytes: &[u8]) -> Result { break; } } //while (mode != Mode.PAD_ENCODE && bits.available() > 0); - if resultTrailer.len() > 0 { + if !resultTrailer.is_empty() { result.appendCharacters(&resultTrailer); } if isECIencoded { @@ -158,14 +158,12 @@ pub fn decode(bytes: &[u8]) -> Result { } else { symbologyModifier = 4; } + } else if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) { + symbologyModifier = 2; + } else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) { + symbologyModifier = 3; } else { - if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) { - symbologyModifier = 2; - } else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) { - symbologyModifier = 3; - } else { - symbologyModifier = 1; - } + symbologyModifier = 1; } Ok(DecoderRXingResult::with_symbology( @@ -196,7 +194,7 @@ fn decodeAsciiSegment( loop { let mut oneByte = bits.readBits(8)?; if oneByte == 0 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } else if oneByte <= 128 { // ASCII data (ASCII value + 1) if upperShift { @@ -256,11 +254,11 @@ fn decodeAsciiSegment( // Not to be used in ASCII encodation // but work around encoders that end with 254, latch back to ASCII if oneByte != 254 || bits.available() != 0 { - return Err(Exceptions::FormatException("".to_owned())) + return Err(Exceptions::FormatException(None)) }}, } } - if !(bits.available() > 0) { + if bits.available() == 0 { break; } } //while (bits.available() > 0); @@ -296,9 +294,10 @@ fn decodeC40Segment( parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues); - for i in 0..3 { + for cValue in cValues { + // for i in 0..3 { // for (int i = 0; i < 3; i++) { - let cValue = cValues[i]; + // let cValue = cValues[i]; match shift { 0 => { if cValue < 3 { @@ -312,15 +311,15 @@ fn decodeC40Segment( result.append_char(c40char); } } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } 1 => { if upperShift { - result.append_char(char::from_u32((cValue + 128) as u32).unwrap()); + result.append_char(char::from_u32(cValue + 128).unwrap()); upperShift = false; } else { - result.append_char(char::from_u32(cValue as u32).unwrap()); + result.append_char(char::from_u32(cValue).unwrap()); } shift = 0; } @@ -346,25 +345,25 @@ fn decodeC40Segment( upperShift = true } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } shift = 0; } 3 => { if upperShift { - result.append_char(char::from_u32(cValue as u32 + 224).unwrap()); + result.append_char(char::from_u32(cValue + 224).unwrap()); upperShift = false; } else { - result.append_char(char::from_u32(cValue as u32 + 96).unwrap()); + result.append_char(char::from_u32(cValue + 96).unwrap()); } shift = 0; } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } - if !(bits.available() > 0) { + if bits.available() == 0 { break; } } //while (bits.available() > 0); @@ -409,14 +408,13 @@ fn decodeTextSegment( } else if cValue < TEXT_BASIC_SET_CHARS.len() as u32 { let textChar = TEXT_BASIC_SET_CHARS[cValue as usize]; if upperShift { - result - .append_char(char::from_u32(textChar as u32 + 128 as u32).unwrap()); + result.append_char(char::from_u32(textChar as u32 + 128_u32).unwrap()); upperShift = false; } else { result.append_char(textChar); } } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } 1 => { @@ -452,7 +450,7 @@ fn decodeTextSegment( upperShift = true } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } shift = 0; @@ -468,14 +466,14 @@ fn decodeTextSegment( } shift = 0; } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } - if !(bits.available() > 0) { + if bits.available() == 0 { break; } } //while (bits.available() > 0); @@ -543,12 +541,12 @@ fn decodeAnsiX12Segment( // A - Z result.append_char(char::from_u32(cValue + 51).unwrap()); } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } } } - if !(bits.available() > 0) { + if bits.available() == 0 { break; } } //while (bits.available() > 0); @@ -601,7 +599,7 @@ fn decodeEdifactSegment( result.append_char(char::from_u32(edifactValue).unwrap()); } - if !(bits.available() > 0) { + if bits.available() == 0 { break; } } @@ -635,18 +633,19 @@ fn decodeBase256Segment( // We're seeing NegativeArraySizeException errors from users. // but we shouldn't in rust because it's unsigned // if count < 0 { - // return Err(Exceptions::FormatException("".to_owned())); + // return Err(Exceptions::FormatException(None)); // } let mut bytes = vec![0u8; count as usize]; - for i in 0..count as usize { + for byte in bytes.iter_mut().take(count as usize) { + // for i in 0..count as usize { // for (int i = 0; i < count; i++) { // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if bits.available() < 8 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } - bytes[i] = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; + *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; codewordPosition += 1; } result.append_string( @@ -665,7 +664,7 @@ fn decodeBase256Segment( */ fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<(), Exceptions> { if bits.available() < 8 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } let c1 = bits.readBits(8)?; if c1 <= 127 { diff --git a/src/datamatrix/decoder/decoder.rs b/src/datamatrix/decoder/decoder.rs index 8856aec..92e89f6 100644 --- a/src/datamatrix/decoder/decoder.rs +++ b/src/datamatrix/decoder/decoder.rs @@ -50,7 +50,7 @@ impl Decoder { * @throws ChecksumException if error correction fails */ pub fn decode_bools(&self, image: &Vec>) -> Result { - self.decode(&BitMatrix::parse_bools(&image)) + self.decode(&BitMatrix::parse_bools(image)) } /** @@ -72,7 +72,7 @@ impl Decoder { let version = parser.getVersion(); // Separate into data blocks - let dataBlocks = DataBlock::getDataBlocks(&codewords, &version)?; + let dataBlocks = DataBlock::getDataBlocks(&codewords, version)?; // Count total number of data bytes let mut totalBytes = 0; @@ -140,3 +140,9 @@ impl Decoder { Ok(()) } } + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/datamatrix/decoder/version.rs b/src/datamatrix/decoder/version.rs index 7940f8a..255cc43 100644 --- a/src/datamatrix/decoder/version.rs +++ b/src/datamatrix/decoder/version.rs @@ -111,7 +111,7 @@ impl Version { numColumns: u32, ) -> Result<&'static Version, Exceptions> { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } for version in VERSIONS.iter() { @@ -120,7 +120,7 @@ impl Version { } } - Err(Exceptions::FormatException("".to_owned())) + Err(Exceptions::FormatException(None)) } /** diff --git a/src/datamatrix/detector/detector.rs b/src/datamatrix/detector/detector.rs index ed9d285..6f4f946 100644 --- a/src/datamatrix/detector/detector.rs +++ b/src/datamatrix/detector/detector.rs @@ -53,7 +53,9 @@ impl<'a> Detector<'_> { if let Some(point) = self.correctTopRight(&points) { points[3] = point; } else { - return Err(Exceptions::NotFoundException("point 4 unfound".to_owned())); + return Err(Exceptions::NotFoundException(Some( + "point 4 unfound".to_owned(), + ))); } // points[3] = self.correctTopRight(&points); // if points[3] == null { @@ -82,7 +84,7 @@ impl<'a> Detector<'_> { } let bits = Self::sampleGrid( - &self.image, + self.image, &topLeft, &bottomLeft, &bottomRight, @@ -253,9 +255,9 @@ impl<'a> Detector<'_> { + self.transitionsBetween(&pointCs, &candidate2); if sumc1 > sumc2 { - return Some(candidate1); + Some(candidate1) } else { - return Some(candidate2); + Some(candidate2) } } @@ -315,10 +317,10 @@ impl<'a> Detector<'_> { } fn isValid(&self, p: &RXingResultPoint) -> bool { - return p.getX() >= 0.0 + p.getX() >= 0.0 && p.getX() <= self.image.getWidth() as f32 - 1.0 && p.getY() > 0.0 - && p.getY() <= self.image.getHeight() as f32 - 1.0; + && p.getY() <= self.image.getHeight() as f32 - 1.0 } fn sampleGrid( @@ -332,7 +334,7 @@ impl<'a> Detector<'_> { ) -> Result { let sampler = DefaultGridSampler {}; - return sampler.sample_grid_detailed( + sampler.sample_grid_detailed( image, dimensionX, dimensionY, @@ -352,7 +354,7 @@ impl<'a> Detector<'_> { bottomRight.getY(), bottomLeft.getX(), bottomLeft.getY(), - ); + ) } /** @@ -404,6 +406,6 @@ impl<'a> Detector<'_> { x += xstep; } - return transitions; + transitions } } diff --git a/src/datamatrix/encoder/ascii_encoder.rs b/src/datamatrix/encoder/ascii_encoder.rs index adc8001..ea9a87b 100644 --- a/src/datamatrix/encoder/ascii_encoder.rs +++ b/src/datamatrix/encoder/ascii_encoder.rs @@ -73,10 +73,10 @@ impl Encoder for ASCIIEncoder { } _ => { - return Err(Exceptions::IllegalStateException(format!( + return Err(Exceptions::IllegalStateException(Some(format!( "Illegal mode: {}", newMode - ))); + )))); } } } else if high_level_encoder::isExtendedASCII(c) { @@ -105,10 +105,15 @@ impl ASCIIEncoder { let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); Ok((num + 130) as char) } else { - Err(Exceptions::IllegalArgumentException(format!( + Err(Exceptions::IllegalArgumentException(Some(format!( "not digits: {}{}", digit1, digit2 - ))) + )))) } } } +impl Default for ASCIIEncoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/datamatrix/encoder/base256_encoder.rs b/src/datamatrix/encoder/base256_encoder.rs index 5106cf0..b266efc 100644 --- a/src/datamatrix/encoder/base256_encoder.rs +++ b/src/datamatrix/encoder/base256_encoder.rs @@ -65,10 +65,10 @@ impl Encoder for Base256Encoder { let (ci_pos, _) = buffer.char_indices().nth(1).unwrap(); buffer.insert(ci_pos, char::from_u32(dataCount as u32 % 250).unwrap()); } else { - return Err(Exceptions::IllegalStateException(format!( + return Err(Exceptions::IllegalStateException(Some(format!( "Message length not in valid ranges: {}", dataCount - ))); + )))); } } let c = buffer.chars().count(); @@ -96,3 +96,9 @@ impl Base256Encoder { } } } + +impl Default for Base256Encoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/datamatrix/encoder/c40_encoder.rs b/src/datamatrix/encoder/c40_encoder.rs index 5fe84ec..67acfa6 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -167,7 +167,7 @@ impl C40Encoder { let c = context.getCurrentChar(); let lastCharSize = encodeChar(c, removed); context.resetSymbolInfo(); //Deal with possible reduction in symbol size - return lastCharSize; + lastCharSize } pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) { @@ -219,9 +219,9 @@ impl C40Encoder { context.writeCodeword(C40_UNLATCH); } } else { - return Err(Exceptions::IllegalStateException( + return Err(Exceptions::IllegalStateException(Some( "Unexpected case. Please report!".to_owned(), - )); + ))); } context.signalEncoderChange(ASCII_ENCODATION); @@ -233,11 +233,11 @@ impl C40Encoder { sb.push('\u{3}'); return 1; } - if c >= '0' && c <= '9' { + if ('0'..='9').contains(&c) { sb.push((c as u8 - 48 + 4) as char); return 1; } - if c >= 'A' && c <= 'Z' { + if ('A'..='Z').contains(&c) { sb.push((c as u8 - 65 + 14) as char); return 1; } @@ -274,7 +274,7 @@ impl C40Encoder { } fn encodeToCodewords(sb: &str) -> String { - let v = (1600 * sb.chars().nth(0).unwrap() as u32) + let v = (1600 * sb.chars().next().unwrap() as u32) + (40 * sb.chars().nth(1).unwrap() as u32) + sb.chars().nth(2).unwrap() as u32 + 1; @@ -286,3 +286,9 @@ impl C40Encoder { // return new String(new char[] {cw1, cw2}); } } + +impl Default for C40Encoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/datamatrix/encoder/default_placement.rs b/src/datamatrix/encoder/default_placement.rs index 362ca14..b4b6a2c 100644 --- a/src/datamatrix/encoder/default_placement.rs +++ b/src/datamatrix/encoder/default_placement.rs @@ -64,7 +64,7 @@ impl DefaultPlacement { } pub fn setBit(&mut self, col: usize, row: usize, bit: bool) { - self.bits[row * self.numcols + col] = if bit { 1 } else { 0 }; + self.bits[row * self.numcols + col] = u8::from(bit); //if bit { 1 } else { 0 }; } pub fn noBit(&self, col: usize, row: usize) -> bool { @@ -281,7 +281,7 @@ mod test_placement { fn unvisualize(visualized: &str) -> String { let mut sb = String::new(); - for token in visualized.split(" ") { + for token in visualized.split(' ') { // for (String token : SPACE.split(visualized)) { let tkn: u32 = token.parse().unwrap(); sb.push(char::from_u32(tkn).unwrap()); diff --git a/src/datamatrix/encoder/edifact_encoder.rs b/src/datamatrix/encoder/edifact_encoder.rs index d49a070..47c839a 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -65,7 +65,7 @@ impl EdifactEncoder { * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ - fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> { + fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { let mut runner = || -> Result<(), Exceptions> { let count = buffer.chars().count(); if count == 0 { @@ -89,9 +89,9 @@ impl EdifactEncoder { } if count > 4 { - return Err(Exceptions::IllegalStateException( + return Err(Exceptions::IllegalStateException(Some( "Count must not exceed 4".to_owned(), - )); + ))); } let restChars = count - 1; let encoded = Self::encodeToCodewords(buffer)?; @@ -127,9 +127,9 @@ impl EdifactEncoder { } fn encodeChar(c: char, sb: &mut String) { - if c >= ' ' && c <= '?' { + if (' '..='?').contains(&c) { sb.push(c); - } else if c >= '@' && c <= '^' { + } else if ('@'..='^').contains(&c) { sb.push((c as u8 - 64) as char); } else { high_level_encoder::illegalCharacter(c).expect(""); @@ -139,11 +139,11 @@ impl EdifactEncoder { fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { - return Err(Exceptions::IllegalStateException( + return Err(Exceptions::IllegalStateException(Some( "StringBuilder must not be empty".to_owned(), - )); + ))); } - let c1 = sb.chars().nth(0).unwrap(); + let c1 = sb.chars().next().unwrap(); let c2 = if len >= 2 { sb.chars().nth(1).unwrap() } else { @@ -161,9 +161,9 @@ impl EdifactEncoder { }; let v: u32 = ((c1 as u32) << 18) + ((c2 as u32) << 12) + ((c3 as u32) << 6) + c4 as u32; - let cw1 = (v as u32 >> 16) & 255; - let cw2 = (v as u32 >> 8) & 255; - let cw3 = v as u32 & 255; + let cw1 = (v >> 16) & 255; + let cw2 = (v >> 8) & 255; + let cw3 = v & 255; let mut res = String::with_capacity(3); res.push(char::from_u32(cw1).unwrap()); if len >= 2 { @@ -176,3 +176,9 @@ impl EdifactEncoder { Ok(res) } } + +impl Default for EdifactEncoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index c101b39..b8981cf 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -64,9 +64,9 @@ impl<'a> EncoderContext<'_> { .decode(&encoded_bytes, encoding::DecoderTrap::Strict) .expect("round trip decode should always work") } else { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Message contains characters outside ISO-8859-1 encoding.".to_owned(), - )); + ))); }; Ok(Self { symbol_lookup: Rc::new(SymbolInfoLookup::new()), diff --git a/src/datamatrix/encoder/error_correction.rs b/src/datamatrix/encoder/error_correction.rs index 75c9c98..c0c05d6 100644 --- a/src/datamatrix/encoder/error_correction.rs +++ b/src/datamatrix/encoder/error_correction.rs @@ -152,9 +152,9 @@ const ALOG: [u32; 255] = { */ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "The number of codewords does not match the selected symbol".to_owned(), - )); + ))); } let mut sb = String::with_capacity( (symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()) as usize, @@ -171,7 +171,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result Result Result Result { let mut table = -1_isize; - for i in 0..FACTOR_SETS.len() { + for (i, set) in FACTOR_SETS.iter().enumerate() { + // for i in 0..FACTOR_SETS.len() { // for (int i = 0; i < FACTOR_SETS.length; i++) { - if FACTOR_SETS[i] as usize == numECWords { + if set == &(numECWords as u32) { table = i as isize; break; } } if table < 0 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Illegal number of error correction codewords specified: {}", numECWords - ))); + )))); } let poly = &FACTORS[table as usize]; let mut ecc = vec![0 as char; numECWords]; diff --git a/src/datamatrix/encoder/high_level_encode_test_case.rs b/src/datamatrix/encoder/high_level_encode_test_case.rs index 7f7c172..e90cad0 100644 --- a/src/datamatrix/encoder/high_level_encode_test_case.rs +++ b/src/datamatrix/encoder/high_level_encode_test_case.rs @@ -119,7 +119,7 @@ fn testC40EncodationSpecialCases1() { let substitute_symbols = SymbolInfoLookup::new(); let substitute_symbols = useTestSymbols(substitute_symbols); - let sil = Rc::new(substitute_symbols.clone()); + let sil = Rc::new(substitute_symbols); let visualized = encodeHighLevelCompareSIL("AIMAIMAIMAIMAIMAIM", false, Some(sil.clone())); assert_eq!("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized); diff --git a/src/datamatrix/encoder/high_level_encoder.rs b/src/datamatrix/encoder/high_level_encoder.rs index 7b26406..625e9b1 100644 --- a/src/datamatrix/encoder/high_level_encoder.rs +++ b/src/datamatrix/encoder/high_level_encoder.rs @@ -284,7 +284,7 @@ pub fn encodeHighLevelWithDimensionForceC40( pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize { let newMode = lookAheadTestIntern(msg, startpos, currentMode); - if currentMode as usize == X12_ENCODATION && newMode as usize == X12_ENCODATION { + if currentMode as usize == X12_ENCODATION && newMode == X12_ENCODATION { // let msg_graphemes = msg.graphemes(true); let endpos = (startpos + 3).min(msg.chars().count() as u32); for i in startpos..endpos { @@ -540,20 +540,15 @@ fn findMinimums( mins[i] += 1; } } - return min; + min } fn getMinimumCount(mins: &[u8]) -> u32 { - let mut minCount = 0; - for i in 0..6 { - // for (int i = 0; i < 6; i++) { - minCount += mins[i] as u32; - } - minCount + mins.iter().take(6).sum::() as u32 } pub fn isDigit(ch: char) -> bool { - ch >= '0' && ch <= '9' + ('0'..='9').contains(&ch) } pub fn isExtendedASCII(ch: char) -> bool { @@ -561,15 +556,15 @@ pub fn isExtendedASCII(ch: char) -> bool { } pub fn isNativeC40(ch: char) -> bool { - (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') + (ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch) } pub fn isNativeText(ch: char) -> bool { - (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') + (ch == ' ') || ('0'..='9').contains(&ch) || ('a'..='z').contains(&ch) } pub fn isNativeX12(ch: char) -> bool { - return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); + isX12TermSep(ch) || (ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch) } fn isX12TermSep(ch: char) -> bool { @@ -579,7 +574,7 @@ fn isX12TermSep(ch: char) -> bool { } pub fn isNativeEDIFACT(ch: char) -> bool { - ch >= ' ' && ch <= '^' + (' '..='^').contains(&ch) } fn isSpecialB256(_ch: char) -> bool { @@ -607,8 +602,8 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 { pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { // let hex = Integer.toHexString(c); // hex = "0000".substring(0, 4 - hex.length()) + hex; - Err(Exceptions::IllegalArgumentException(format!( + Err(Exceptions::IllegalArgumentException(Some(format!( "Illegal character: {} (0x{})", c, c - ))) + )))) } diff --git a/src/datamatrix/encoder/minimal_encoder.rs b/src/datamatrix/encoder/minimal_encoder.rs index d4e8715..8533e8b 100755 --- a/src/datamatrix/encoder/minimal_encoder.rs +++ b/src/datamatrix/encoder/minimal_encoder.rs @@ -65,22 +65,22 @@ const ISO_8859_1_ENCODER: EncodingRef = encoding::all::ISO_8859_1; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Mode { - ASCII, + Ascii, C40, - TEXT, + Text, X12, - EDF, + Edf, B256, } impl Mode { pub fn ordinal(&self) -> usize { match self { - Mode::ASCII => 0, + Mode::Ascii => 0, Mode::C40 => 1, - Mode::TEXT => 2, + Mode::Text => 2, Mode::X12 => 3, - Mode::EDF => 4, + Mode::Edf => 4, Mode::B256 => 5, } } @@ -177,8 +177,7 @@ pub fn encodeHighLevelWithDetails( &encode(msg, priorityCharset, fnc1, shape, macroId)?, encoding::DecoderTrap::Strict, ) - .expect("should decode") - .to_owned()) + .expect("should decode")) // return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1); } @@ -214,7 +213,7 @@ fn encode( .to_vec()) } -fn addEdge(edges: &mut Vec>>>, edge: Rc) -> Result<(), Exceptions> { +fn addEdge(edges: &mut [Vec>>], edge: Rc) -> Result<(), Exceptions> { let vertexIndex = (edge.fromPosition + edge.characterLength) as usize; if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() || edges[vertexIndex][edge.getEndMode()?.ordinal()] @@ -256,7 +255,7 @@ fn getNumberOfC40Words( } else if !isExtendedASCII(ci, input.getFNC1Character()) { thirdsCount += 2; //shift } else { - let asciiValue = ci as u8 & 0xff; + let asciiValue = ci as u8; if asciiValue >= 128 && (c40 && high_level_encoder::isNativeC40((asciiValue - 128) as char) || !c40 && high_level_encoder::isNativeText((asciiValue - 128) as char)) @@ -280,20 +279,20 @@ fn getNumberOfC40Words( fn addEdges( input: Rc, - edges: &mut Vec>>>, + edges: &mut [Vec>>], from: u32, previous: Option>, ) -> Result<(), Exceptions> { if input.isECI(from)? { addEdge( edges, - Rc::new(Edge::new(input, Mode::ASCII, from, 1, previous.clone())?), + Rc::new(Edge::new(input, Mode::Ascii, from, 1, previous)?), )?; return Ok(()); } let ch = input.charAt(from as usize)?; - if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::EDF { + if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::Edf { //not possible to unlatch a full EDF edge to something //else if high_level_encoder::isDigit(ch) @@ -305,7 +304,7 @@ fn addEdges( edges, Rc::new(Edge::new( input.clone(), - Mode::ASCII, + Mode::Ascii, from, 2, previous.clone(), @@ -317,7 +316,7 @@ fn addEdges( edges, Rc::new(Edge::new( input.clone(), - Mode::ASCII, + Mode::Ascii, from, 1, previous.clone(), @@ -325,7 +324,7 @@ fn addEdges( )?; } - let modes = [Mode::C40, Mode::TEXT]; + let modes = [Mode::C40, Mode::Text]; for mode in modes { // for (Mode mode : modes) { let mut characterLength = [0u32; 1]; @@ -387,7 +386,7 @@ fn addEdges( edges, Rc::new(Edge::new( input.clone(), - Mode::EDF, + Mode::Edf, from, i + 1, previous.clone(), @@ -404,7 +403,7 @@ fn addEdges( { addEdge( edges, - Rc::new(Edge::new(input, Mode::EDF, from, 4, previous.clone())?), + Rc::new(Edge::new(input, Mode::Edf, from, 4, previous)?), )?; } Ok(()) @@ -626,7 +625,7 @@ fn encodeMinimally(input: Rc) -> Result { // for (int j = 0; j < 6; j++) { if edges[inputLength][j].is_some() { let edge = edges[inputLength][j].as_ref().unwrap(); - let size = if j >= 1 && j <= 3 { + let size = if (1..=3).contains(&j) { edge.cachedTotalSize + 1 } else { edge.cachedTotalSize @@ -640,10 +639,10 @@ fn encodeMinimally(input: Rc) -> Result { } if minimalJ < 0 { - return Err(Exceptions::RuntimeException(format!( + return Err(Exceptions::RuntimeException(Some(format!( "Internal error: failed to encode \"{}\"", input - ))); + )))); } RXingResult::new(edges[inputLength][minimalJ as usize].clone()) } @@ -704,7 +703,7 @@ impl Edge { * B256 -> ASCII: without latch after n bytes */ match mode { - Mode::ASCII => { + Mode::Ascii => { size += 1; if input.isECI(fromPosition).expect("bool") || isExtendedASCII( @@ -717,7 +716,7 @@ impl Edge { size += 1; } if previousMode == Mode::C40 - || previousMode == Mode::TEXT + || previousMode == Mode::Text || previousMode == Mode::X12 { size += 1; // unlatch 254 to ASCII @@ -725,21 +724,22 @@ impl Edge { } Mode::B256 => { size += 1; - if previousMode != Mode::B256 { + if previousMode != Mode::B256 || Self::getB256Size(mode, previous.clone()) == 250 { size += 1; //byte count - } else if Self::getB256Size(mode, previous.clone()) == 250 { - size += 1; //extra byte count } - if previousMode == Mode::ASCII { + // } else if Self::getB256Size(mode, previous.clone()) == 250 { + // size += 1; //extra byte count + // } + if previousMode == Mode::Ascii { size += 1; //latch to B256 } else if previousMode == Mode::C40 - || previousMode == Mode::TEXT + || previousMode == Mode::Text || previousMode == Mode::X12 { size += 2; //unlatch to ASCII, latch to B256 } } - Mode::C40 | Mode::TEXT | Mode::X12 => { + Mode::C40 | Mode::Text | Mode::X12 => { if mode == Mode::X12 { size += 2; } else { @@ -754,22 +754,22 @@ impl Edge { * 2; } - if previousMode == Mode::ASCII || previousMode == Mode::B256 { + if previousMode == Mode::Ascii || previousMode == Mode::B256 { size += 1; //additional byte for latch from ASCII to this mode } else if previousMode != mode && (previousMode == Mode::C40 - || previousMode == Mode::TEXT + || previousMode == Mode::Text || previousMode == Mode::X12) { size += 2; //unlatch 254 to ASCII followed by latch to this mode } } - Mode::EDF => { + Mode::Edf => { size += 3; - if previousMode == Mode::ASCII || previousMode == Mode::B256 { + if previousMode == Mode::Ascii || previousMode == Mode::B256 { size += 1; //additional byte for latch from ASCII to this mode } else if previousMode == Mode::C40 - || previousMode == Mode::TEXT + || previousMode == Mode::Text || previousMode == Mode::X12 { size += 2; //unlatch 254 to ASCII followed by latch to this mode @@ -811,7 +811,7 @@ impl Edge { if let Some(prev) = previous { prev.mode } else { - Mode::ASCII + Mode::Ascii } // if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode} } @@ -820,7 +820,7 @@ impl Edge { if let Some(prev) = previous { prev.getEndMode() } else { - Ok(Mode::ASCII) + Ok(Mode::Ascii) } // return previous == null ? Mode::ASCII : previous.getEndMode(); } @@ -833,27 +833,27 @@ impl Edge { * */ pub fn getEndMode(&self) -> Result { let mode = self.mode; - if mode == Mode::EDF { + if mode == Mode::Edf { if self.characterLength < 4 { - return Ok(Mode::ASCII); + return Ok(Mode::Ascii); } - let lastASCII = Self::getLastASCII(&self)?; // see 5.2.8.2 EDIFACT encodation Rules + let lastASCII = Self::getLastASCII(self)?; // see 5.2.8.2 EDIFACT encodation Rules if lastASCII > 0 && self.getCodewordsRemaining(self.cachedTotalSize + lastASCII) <= 2 - lastASCII { - return Ok(Mode::ASCII); + return Ok(Mode::Ascii); } } - if mode == Mode::C40 || mode == Mode::TEXT || mode == Mode::X12 { + if mode == Mode::C40 || mode == Mode::Text || mode == Mode::X12 { // see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules if self.fromPosition + self.characterLength >= self.input.length() as u32 && self.getCodewordsRemaining(self.cachedTotalSize) == 0 { - return Ok(Mode::ASCII); + return Ok(Mode::Ascii); } - let lastASCII = Self::getLastASCII(&self)?; + let lastASCII = Self::getLastASCII(self)?; if lastASCII == 1 && self.getCodewordsRemaining(self.cachedTotalSize + 1) == 0 { - return Ok(Mode::ASCII); + return Ok(Mode::Ascii); } } @@ -969,7 +969,7 @@ impl Edge { * minimal number of codewords. **/ pub fn getCodewordsRemaining(&self, minimum: u32) -> u32 { - Self::getMinSymbolSize(&self, minimum) - minimum + Self::getMinSymbolSize(self, minimum) - minimum } pub fn getBytes1(c: u32) -> Vec { @@ -1003,9 +1003,9 @@ impl Edge { 2 } else if c == 32 { 3 - } else if c >= 48 && c <= 57 { + } else if (48..=57).contains(&c) { c - 44 - } else if c >= 65 && c <= 90 { + } else if (65..=90).contains(&c) { c - 51 } else { c @@ -1033,7 +1033,7 @@ impl Edge { ); i += 2; } - return Ok(result); + Ok(result) } pub fn getShiftValue(c: char, c40: bool, fnc1: Option) -> u32 { @@ -1055,7 +1055,7 @@ impl Edge { } if c40 { let c = c as u32; - return if c <= 31 { + if c <= 31 { c } else if c == 32 { 3 @@ -1073,10 +1073,10 @@ impl Edge { c - 96 } else { c - }; + } } else { let c = c as u32; - return if c == 0 { + if c == 0 { 0 } else if setIndex == 0 && c <= 3 { c - 1 @@ -1086,25 +1086,25 @@ impl Edge { c } else if c == 32 { 3 - } else if c >= 33 && c <= 47 { + } else if (33..=47).contains(&c) { c - 33 - } else if c >= 48 && c <= 57 { + } else if (48..=57).contains(&c) { c - 44 - } else if c >= 58 && c <= 64 { + } else if (58..=64).contains(&c) { c - 43 - } else if c >= 65 && c <= 90 { + } else if (65..=90).contains(&c) { c - 64 - } else if c >= 91 && c <= 95 { + } else if (91..=95).contains(&c) { c - 69 } else if c == 96 { 0 - } else if c >= 97 && c <= 122 { + } else if (97..=122).contains(&c) { c - 83 - } else if c >= 123 && c <= 127 { + } else if (123..=127).contains(&c) { c - 96 } else { c - }; + } } } @@ -1123,7 +1123,7 @@ impl Edge { c40Values.push(shiftValue as u8); //Shift[123] c40Values.push(Self::getC40Value(c40, shiftValue, ci, fnc1) as u8); } else { - let asciiValue = ((ci as u8 & 0xff) - 128) as char; + let asciiValue = (ci as u8 - 128) as char; if c40 && high_level_encoder::isNativeC40(asciiValue) || !c40 && high_level_encoder::isNativeText(asciiValue) { @@ -1178,13 +1178,14 @@ impl Edge { while i < numberOfThirds { // for (int i = 0; i < numberOfThirds; i += 3) { let mut edfValues = [0u32; 4]; - for j in 0..4 { + for edfValue in &mut edfValues { + // for j in 0..4 { // for (int j = 0; j < 4; j++) { if pos <= endPos { - edfValues[j] = self.input.charAt(pos)? as u32 & 0x3f; + *edfValue = self.input.charAt(pos)? as u32 & 0x3f; pos += 1; } else { - edfValues[j] = if pos == endPos + 1 { 0x1f } else { 0 }; + *edfValue = if pos == endPos + 1 { 0x1f } else { 0 }; } } let mut val24 = edfValues[0] << 18; @@ -1203,32 +1204,32 @@ impl Edge { pub fn getLatchBytes(&self) -> Result, Exceptions> { match Self::getPreviousMode(self.previous.clone())? { - Mode::ASCII | Mode::B256 => + Mode::Ascii | Mode::B256 => //after B256 ends (via length) we are back to ASCII { match self.mode { Mode::B256 => return Ok(Self::getBytes1(231)), Mode::C40 => return Ok(Self::getBytes1(230)), - Mode::TEXT => return Ok(Self::getBytes1(239)), + Mode::Text => return Ok(Self::getBytes1(239)), Mode::X12 => return Ok(Self::getBytes1(238)), - Mode::EDF => return Ok(Self::getBytes1(240)), + Mode::Edf => return Ok(Self::getBytes1(240)), _ => {} } } - Mode::C40 | Mode::TEXT | Mode::X12 + Mode::C40 | Mode::Text | Mode::X12 if self.mode != Self::getPreviousMode(self.previous.clone())? => { match self.mode { - Mode::ASCII => return Ok(Self::getBytes1(254)), + Mode::Ascii => return Ok(Self::getBytes1(254)), Mode::B256 => return Ok(Self::getBytes2(254, 231)), Mode::C40 => return Ok(Self::getBytes2(254, 230)), - Mode::TEXT => return Ok(Self::getBytes2(254, 239)), + Mode::Text => return Ok(Self::getBytes2(254, 239)), Mode::X12 => return Ok(Self::getBytes2(254, 238)), - Mode::EDF => return Ok(Self::getBytes2(254, 240)), + Mode::Edf => return Ok(Self::getBytes2(254, 240)), } } - Mode::C40 | Mode::TEXT | Mode::X12 => {} - Mode::EDF => assert!(self.mode == Mode::EDF), //The rightmost EDIFACT edge always contains an unlatch character + Mode::C40 | Mode::Text | Mode::X12 => {} + Mode::Edf => assert!(self.mode == Mode::Edf), //The rightmost EDIFACT edge always contains an unlatch character } Ok(Vec::new()) @@ -1237,12 +1238,12 @@ impl Edge { // Important: The function does not return the length bytes (one or two) in case of B256 encoding pub fn getDataBytes(&self) -> Result, Exceptions> { match self.mode { - Mode::ASCII => { + Mode::Ascii => { if self.input.isECI(self.fromPosition)? { - return Ok(Self::getBytes2( + Ok(Self::getBytes2( 241, self.input.getECIValue(self.fromPosition as usize)? as u32 + 1, - )); + )) } else if isExtendedASCII( self.input.charAt(self.fromPosition as usize)?, self.input.getFNC1Character(), @@ -1266,15 +1267,13 @@ impl Edge { )); } } - Mode::B256 => { - return Ok(Self::getBytes1( - self.input.charAt(self.fromPosition as usize)? as u32, - )) - } - Mode::C40 => return self.getC40Words(true, self.input.getFNC1Character()), - Mode::TEXT => return self.getC40Words(false, self.input.getFNC1Character()), - Mode::X12 => return self.getX12Words(), - Mode::EDF => return self.getEDFBytes(), + Mode::B256 => Ok(Self::getBytes1( + self.input.charAt(self.fromPosition as usize)? as u32, + )), + Mode::C40 => self.getC40Words(true, self.input.getFNC1Character()), + Mode::Text => self.getC40Words(false, self.input.getFNC1Character()), + Mode::X12 => self.getX12Words(), + Mode::Edf => self.getEDFBytes(), } // assert!( false); // Ok(vec![0]) @@ -1289,15 +1288,15 @@ impl RXingResult { let solution = if let Some(edge) = solution { edge } else { - return Err(Exceptions::IllegalArgumentException("()".to_string())); + return Err(Exceptions::IllegalArgumentException(None)); }; let input = solution.input.clone(); let mut size = 0; let mut bytesAL = Vec::new(); //new ArrayList<>(); let mut randomizePostfixLength = Vec::new(); //new ArrayList<>(); let mut randomizeLengths = Vec::new(); //new ArrayList<>(); - if (solution.mode == Mode::C40 || solution.mode == Mode::TEXT || solution.mode == Mode::X12) - && solution.getEndMode()? != Mode::ASCII + if (solution.mode == Mode::C40 || solution.mode == Mode::Text || solution.mode == Mode::X12) + && solution.getEndMode()? != Mode::Ascii { size += Self::prepend(&Edge::getBytes1(254), &mut bytesAL); } @@ -1355,10 +1354,11 @@ impl RXingResult { } let mut bytes = vec![0u8; bytesAL.len()]; - for i in 0..bytes.len() { - // for (int i = 0; i < bytes.length; i++) { - bytes[i] = *bytesAL.get(i).unwrap(); - } + // for (i, byte) in bytes.iter_mut().enumerate() { + // // for (int i = 0; i < bytes.length; i++) { + // *byte = *bytesAL.get(i).unwrap(); + // } + bytes[..].copy_from_slice(&bytesAL[..]); Ok(Self { bytes }) } diff --git a/src/datamatrix/encoder/symbol_info.rs b/src/datamatrix/encoder/symbol_info.rs index af760fd..ac97d09 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -127,9 +127,9 @@ impl SymbolInfo { 2 | 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::IllegalStateException( + _ => Err(Exceptions::IllegalStateException(Some( "Cannot handle this number of data regions".to_owned(), - )), + ))), } // switch (dataRegions) { // case 1: @@ -152,9 +152,9 @@ impl SymbolInfo { 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::IllegalStateException( + _ => Err(Exceptions::IllegalStateException(Some( "Cannot handle this number of data regions".to_owned(), - )), + ))), } // switch (dataRegions) { // case 1: @@ -344,10 +344,10 @@ impl<'a> SymbolInfoLookup<'a> { } } if fail { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can't find a symbol arrangement that matches the message. Data codewords: {}", dataCodewords - ))); + )))); } Ok(None) } diff --git a/src/datamatrix/encoder/text_encoder.rs b/src/datamatrix/encoder/text_encoder.rs index 4de6992..a375560 100644 --- a/src/datamatrix/encoder/text_encoder.rs +++ b/src/datamatrix/encoder/text_encoder.rs @@ -40,11 +40,11 @@ impl TextEncoder { sb.push('\u{3}'); return 1; } - if c >= '0' && c <= '9' { + if ('0'..='9').contains(&c) { sb.push((c as u8 - 48 + 4) as char); return 1; } - if c >= 'a' && c <= 'z' { + if ('a'..='z').contains(&c) { sb.push((c as u8 - 97 + 14) as char); return 1; } @@ -63,7 +63,7 @@ impl TextEncoder { sb.push((c as u8 - 58 + 15) as char); return 2; } - if c >= '[' && c <= '_' { + if ('['..='_').contains(&c) { sb.push('\u{1}'); //Shift 2 Set sb.push((c as u8 - 91 + 22) as char); return 2; @@ -86,6 +86,12 @@ impl TextEncoder { sb.push_str("\u{1}\u{001e}"); //Shift 2, Upper Shift let mut len = 2; len += Self::encodeChar((c as u8 - 128) as char, sb); - return len; + len + } +} + +impl Default for TextEncoder { + fn default() -> Self { + Self::new() } } diff --git a/src/datamatrix/encoder/x12_encoder.rs b/src/datamatrix/encoder/x12_encoder.rs index 8914982..ddd2548 100644 --- a/src/datamatrix/encoder/x12_encoder.rs +++ b/src/datamatrix/encoder/x12_encoder.rs @@ -65,19 +65,19 @@ impl X12Encoder { '>' => sb.push('\u{2}'), ' ' => sb.push('\u{3}'), _ => { - if c >= '0' && c <= '9' { + if ('0'..='9').contains(&c) { sb.push((c as u8 - 48 + 4) as char); - } else if c >= 'A' && c <= 'Z' { + } else if ('A'..='Z').contains(&c) { sb.push((c as u8 - 65 + 14) as char); } else { high_level_encoder::illegalCharacter(c).expect("detect_illegal_character"); } } } - return 1; + 1 } - fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> { + fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { context.updateSymbolInfo(); let available = context.getSymbolInfo().unwrap().getDataCapacity() - context.getCodewordCount() as u32; @@ -95,3 +95,9 @@ impl X12Encoder { Ok(()) } } + +impl Default for X12Encoder { + fn default() -> Self { + Self::new() + } +} diff --git a/src/dimension.rs b/src/dimension.rs index b0de16c..2a21c50 100644 --- a/src/dimension.rs +++ b/src/dimension.rs @@ -32,11 +32,11 @@ impl Dimension { } pub fn getWidth(&self) -> usize { - return self.0; + self.0 } pub fn getHeight(&self) -> usize { - return self.1; + self.1 } } diff --git a/src/exceptions.rs b/src/exceptions.rs index 463555b..7f9a45e 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -2,44 +2,68 @@ use std::{error::Error, fmt}; #[derive(Debug, PartialEq, Eq)] pub enum Exceptions { - IllegalArgumentException(String), - UnsupportedOperationException(String), - IllegalStateException(String), - ArithmeticException(String), - NotFoundException(String), - FormatException(String), - ChecksumException(String), - ReaderException(String), - WriterException(String), - ReedSolomonException(String), - IndexOutOfBoundsException(String), - RuntimeException(String), - ParseException(String), + IllegalArgumentException(Option), + UnsupportedOperationException(Option), + IllegalStateException(Option), + ArithmeticException(Option), + NotFoundException(Option), + FormatException(Option), + ChecksumException(Option), + ReaderException(Option), + WriterException(Option), + ReedSolomonException(Option), + IndexOutOfBoundsException(Option), + RuntimeException(Option), + ParseException(Option), ReaderDecodeException(), } impl fmt::Display for Exceptions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Exceptions::IllegalArgumentException(a) => { + Exceptions::IllegalArgumentException(Some(a)) => { write!(f, "IllegalArgumentException - {}", a) } - Exceptions::UnsupportedOperationException(a) => { + + Exceptions::UnsupportedOperationException(Some(a)) => { write!(f, "UnsupportedOperationException - {}", a) } - Exceptions::IllegalStateException(a) => write!(f, "IllegalStateException - {}", a), - Exceptions::ArithmeticException(a) => write!(f, "ArithmeticException - {}", a), - Exceptions::NotFoundException(a) => write!(f, "NotFoundException - {}", a), - Exceptions::FormatException(a) => write!(f, "FormatException - {}", a), - Exceptions::ChecksumException(a) => write!(f, "ChecksumException - {}", a), - Exceptions::ReaderException(a) => write!(f, "ReaderException - {}", a), - Exceptions::WriterException(a) => write!(f, "WriterException - {}", a), - Exceptions::ReedSolomonException(a) => write!(f, "ReedSolomonException - {}", a), - Exceptions::IndexOutOfBoundsException(a) => { + + Exceptions::IllegalStateException(Some(a)) => { + write!(f, "IllegalStateException - {}", a) + } + Exceptions::ArithmeticException(Some(a)) => write!(f, "ArithmeticException - {}", a), + Exceptions::NotFoundException(Some(a)) => write!(f, "NotFoundException - {}", a), + Exceptions::FormatException(Some(a)) => write!(f, "FormatException - {}", a), + Exceptions::ChecksumException(Some(a)) => write!(f, "ChecksumException - {}", a), + Exceptions::ReaderException(Some(a)) => write!(f, "ReaderException - {}", a), + Exceptions::WriterException(Some(a)) => write!(f, "WriterException - {}", a), + Exceptions::ReedSolomonException(Some(a)) => write!(f, "ReedSolomonException - {}", a), + Exceptions::IndexOutOfBoundsException(Some(a)) => { write!(f, "IndexOutOfBoundsException - {}", a) } - Exceptions::RuntimeException(a) => write!(f, "RuntimeException - {}", a), - Exceptions::ParseException(a) => write!(f, "ParseException - {}", a), + + Exceptions::RuntimeException(Some(a)) => write!(f, "RuntimeException - {}", a), + Exceptions::ParseException(Some(a)) => write!(f, "ParseException - {}", a), + + Exceptions::IllegalArgumentException(None) => write!(f, "IllegalArgumentException"), + + Exceptions::UnsupportedOperationException(None) => { + write!(f, "UnsupportedOperationException") + } + Exceptions::IllegalStateException(None) => write!(f, "IllegalStateException"), + Exceptions::ArithmeticException(None) => write!(f, "ArithmeticException"), + Exceptions::NotFoundException(None) => write!(f, "NotFoundException"), + Exceptions::FormatException(None) => write!(f, "FormatException"), + Exceptions::ChecksumException(None) => write!(f, "ChecksumException"), + Exceptions::ReaderException(None) => write!(f, "ReaderException"), + Exceptions::WriterException(None) => write!(f, "WriterException"), + Exceptions::ReedSolomonException(None) => write!(f, "ReedSolomonException"), + Exceptions::IndexOutOfBoundsException(None) => write!(f, "IndexOutOfBoundsException"), + + Exceptions::RuntimeException(None) => write!(f, "RuntimeException"), + Exceptions::ParseException(None) => write!(f, "ParseException"), + Exceptions::ReaderDecodeException() => write!(f, "ReaderDecodeException - -"), } } diff --git a/src/luminance_source.rs b/src/luminance_source.rs index 2ca9d60..a416312 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -71,7 +71,7 @@ pub trait LuminanceSource { * @return Whether this subclass supports cropping. */ fn isCropSupported(&self) -> bool { - return false; + false } /** @@ -91,16 +91,16 @@ pub trait LuminanceSource { _width: usize, _height: usize, ) -> Result, Exceptions> { - return Err(Exceptions::UnsupportedOperationException( + Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support cropping.".to_owned(), - )); + ))) } /** * @return Whether this subclass supports counter-clockwise rotation. */ fn isRotateSupported(&self) -> bool { - return false; + false } /** @@ -118,9 +118,9 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise(&self) -> Result, Exceptions> { - return Err(Exceptions::UnsupportedOperationException( + Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support rotation by 90 degrees.".to_owned(), - )); + ))) } /** @@ -130,16 +130,16 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise45(&self) -> Result, Exceptions> { - return Err(Exceptions::UnsupportedOperationException( + Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support rotation by 45 degrees.".to_owned(), - )); + ))) } fn invert_block_of_bytes(&self, vec_to_invert: Vec) -> Vec { - let mut iv = vec_to_invert.clone(); + let mut iv = vec_to_invert; for itm in iv.iter_mut() { let z = *itm; - *itm = 255 - (z & 0xFF); + *itm = 255 - z; } iv } diff --git a/src/maxicode/decoder/bit_matrix_parser.rs b/src/maxicode/decoder/bit_matrix_parser.rs index 1133daf..ee5d4ea 100644 --- a/src/maxicode/decoder/bit_matrix_parser.rs +++ b/src/maxicode/decoder/bit_matrix_parser.rs @@ -169,14 +169,16 @@ impl BitMatrixParser { let mut result = [0u8; 144]; let height = self.0.getHeight() as usize; let width = self.0.getWidth() as usize; - for y in 0..height { + for (y, bitnrRow) in BITNR.iter().enumerate().take(height) { + // for y in 0..height { // for (int y = 0; y < height; y++) { - let bitnrRow = BITNR[y]; - for x in 0..width { + // let bitnrRow = BITNR[y]; + for (x, bit) in bitnrRow.iter().enumerate().take(width) { + // for x in 0..width { // for (int x = 0; x < width; x++) { - let bit = bitnrRow[x]; - if bit >= 0 && self.0.get(x as u32, y as u32) { - result[bit as usize / 6] |= 1 << (5 - (bit % 6)); + // let bit = bitnrRow[x]; + if *bit >= 0 && self.0.get(x as u32, y as u32) { + result[*bit as usize / 6] |= 1 << (5 - (bit % 6)); } } } diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index 2cdb6ec..738a9c9 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -85,19 +85,18 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result let mut result = String::with_capacity(144); match mode { 2 | 3 => { - let postcode; - if mode == 2 { + let postcode = if mode == 2 { let pc = getPostCode2(bytes); let ps2Length = getPostCode2Length(bytes) as usize; if ps2Length > 10 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } // NumberFormat df = new DecimalFormat("0000000000".substring(0, ps2Length)); // postcode = df.format(pc); - postcode = format!("{:0>ps2Length$}", pc) + format!("{:0>ps2Length$}", pc) } else { - postcode = getPostCode3(bytes); - } + getPostCode3(bytes) + }; // NumberFormat threeDigits = new DecimalFormat("000"); // let country = threeDigits.format(getCountry(bytes)); // let service = threeDigits.format(getServiceClass(bytes)); @@ -134,11 +133,12 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result fn getBit(bit: u8, bytes: &[u8]) -> u8 { let bit = bit - 1; - if (bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) == 0 { - 0 - } else { - 1 - } + u8::from((bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) != 0) + // if (bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) == 0 { + // 0 + // } else { + // 1 + // } } fn getInt(bytes: &[u8], x: &[u8]) -> u32 { @@ -259,5 +259,5 @@ fn subtract_two_single_char_strings(str1: &str, str2: &str) -> usize { let str2_u16 = ((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize; - (str1_u16 - str2_u16) as usize + str1_u16 - str2_u16 } diff --git a/src/maxicode/decoder/decoder.rs b/src/maxicode/decoder/decoder.rs index f92b063..94528e0 100644 --- a/src/maxicode/decoder/decoder.rs +++ b/src/maxicode/decoder/decoder.rs @@ -70,7 +70,7 @@ pub fn decode_with_hints( correctErrors(&mut codewords, 20, 68, 56, ODD)?; datawords = vec![0u8; 78]; } - _ => return Err(Exceptions::NotFoundException("".to_owned())), + _ => return Err(Exceptions::NotFoundException(None)), } datawords[0..10].clone_from_slice(&codewords[0..10]); @@ -79,7 +79,7 @@ pub fn decode_with_hints( datawords[10..datawords_len].clone_from_slice(&codewords[20..datawords_len + 10]); // System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10); - return decoded_bit_stream_parser::decode(&datawords, mode); + decoded_bit_stream_parser::decode(&datawords, mode) } fn correctErrors( diff --git a/src/maxicode/maxi_code_reader.rs b/src/maxicode/maxi_code_reader.rs index 5b27afc..78bd1d5 100644 --- a/src/maxicode/maxi_code_reader.rs +++ b/src/maxicode/maxi_code_reader.rs @@ -62,7 +62,7 @@ impl Reader for MaxiCodeReader { // Note that MaxiCode reader effectively always assumes PURE_BARCODE mode // and can't detect it in an image let bits = Self::extractPureBits(image.getBlackMatrix())?; - let decoderRXingResult = decoder::decode_with_hints(bits, &hints)?; + let decoderRXingResult = decoder::decode_with_hints(bits, hints)?; let mut result = RXingResult::new( decoderRXingResult.getText(), decoderRXingResult.getRawBytes().clone(), @@ -97,7 +97,7 @@ impl MaxiCodeReader { fn extractPureBits(image: &BitMatrix) -> Result { let enclosingRectangleOption = image.getEnclosingRectangle(); if enclosingRectangleOption.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let enclosingRectangle = enclosingRectangleOption.unwrap(); diff --git a/src/multi/generic_multiple_barcode_reader.rs b/src/multi/generic_multiple_barcode_reader.rs index 080ca22..ba70973 100644 --- a/src/multi/generic_multiple_barcode_reader.rs +++ b/src/multi/generic_multiple_barcode_reader.rs @@ -56,7 +56,7 @@ impl MultipleBarcodeReader for GenericMultipleBarcodeReader { let mut results = Vec::new(); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); if results.is_empty() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(results) } diff --git a/src/multi/qrcode/detector/multi_detector.rs b/src/multi/qrcode/detector/multi_detector.rs index 00b840b..b126e6f 100644 --- a/src/multi/qrcode/detector/multi_detector.rs +++ b/src/multi/qrcode/detector/multi_detector.rs @@ -52,8 +52,8 @@ impl<'a> MultiDetector<'_> { let mut finder = MultiFinderPatternFinder::new(image, resultPointCallback); let infos = finder.findMulti(hints)?; - if infos.len() == 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + if infos.is_empty() { + return Err(Exceptions::NotFoundException(None)); } let mut result = Vec::new(); diff --git a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs index 9d52b1c..9384cf1 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -90,9 +90,9 @@ impl MultiFinderPatternFinder { if size < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::NotFoundException( + return Err(Exceptions::NotFoundException(Some( "Couldn't find enough finder patterns".to_owned(), - )); + ))); } /* @@ -179,8 +179,8 @@ impl MultiFinderPatternFinder { // Check the sizes let estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0); - if estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE - || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE + if !(MIN_MODULE_COUNT_PER_EDGE..=MAX_MODULE_COUNT_PER_EDGE) + .contains(&estimatedModuleCount) { continue; } @@ -210,7 +210,7 @@ impl MultiFinderPatternFinder { if !results.is_empty() { Ok(results) } else { - Err(Exceptions::NotFoundException("no result".to_owned())) + Err(Exceptions::NotFoundException(None)) } } diff --git a/src/multi/qrcode/qr_code_multi_reader.rs b/src/multi/qrcode/qr_code_multi_reader.rs index cb900e3..e07d54c 100644 --- a/src/multi/qrcode/qr_code_multi_reader.rs +++ b/src/multi/qrcode/qr_code_multi_reader.rs @@ -171,7 +171,7 @@ impl QRCodeMultiReader { let mut newRXingResult = RXingResult::new(&newText, newRawBytes, Vec::new(), BarcodeFormat::QR_CODE); - if newByteSegment.len() > 0 { + if !newByteSegment.is_empty() { newRXingResult.putMetadata( RXingResultMetadataType::BYTE_SEGMENTS, RXingResultMetadataValue::ByteSegments(vec![newByteSegment]), diff --git a/src/multi_format_reader.rs b/src/multi_format_reader.rs index 6922bc3..892d840 100644 --- a/src/multi_format_reader.rs +++ b/src/multi_format_reader.rs @@ -31,6 +31,7 @@ use crate::{ * @author Sean Owen * @author dswitkin@google.com (Daniel Switkin) */ +#[derive(Default)] pub struct MultiFormatReader { hints: DecodingHintDictionary, readers: Vec>, @@ -205,15 +206,6 @@ impl MultiFormatReader { } } } - return Err(Exceptions::NotFoundException("".to_owned())); - } -} - -impl Default for MultiFormatReader { - fn default() -> Self { - Self { - hints: HashMap::new(), - readers: Vec::new(), - } + Err(Exceptions::NotFoundException(None)) } } diff --git a/src/multi_format_writer.rs b/src/multi_format_writer.rs index 9c6114e..770e3ea 100644 --- a/src/multi_format_writer.rs +++ b/src/multi_format_writer.rs @@ -70,10 +70,10 @@ impl Writer for MultiFormatWriter { BarcodeFormat::DATA_MATRIX => Box::::default(), BarcodeFormat::AZTEC => Box::::default(), _ => { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "No encoder available for format {:?}", format - ))) + )))) } }; diff --git a/src/oned/coda_bar_reader.rs b/src/oned/coda_bar_reader.rs index ab67764..04ce1e7 100644 --- a/src/oned/coda_bar_reader.rs +++ b/src/oned/coda_bar_reader.rs @@ -64,7 +64,7 @@ impl OneDReader for CodaBarReader { loop { let charOffset = self.toNarrowWidePattern(nextStart); if charOffset == -1 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // Hack: We store the position in the alphabet table into a // StringBuilder, so that we can access the decoded patterns in @@ -81,7 +81,7 @@ impl OneDReader for CodaBarReader { { break; } - if !(nextStart < self.counterLength) { + if nextStart >= self.counterLength { break; } // no fixed end pattern so keep on reading while data is available } //while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available @@ -98,7 +98,7 @@ impl OneDReader for CodaBarReader { // otherwise this is probably a false positive. The exception is if we are // at the end of the row. (I.e. the barcode barely fits.) if nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } self.validatePattern(startOffset)?; @@ -114,9 +114,9 @@ impl OneDReader for CodaBarReader { // self.decodeRowRXingResult.setCharAt(i, Self::ALPHABET[self.decodeRowRXingResult.chars().nth(i).unwrap() as usize]); } // Ensure a valid start and end character - let startchar = self.decodeRowRXingResult.chars().nth(0).unwrap(); + let startchar = self.decodeRowRXingResult.chars().next().unwrap(); if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let endchar = self .decodeRowRXingResult @@ -124,13 +124,13 @@ impl OneDReader for CodaBarReader { .nth(self.decodeRowRXingResult.chars().count() - 1) .unwrap(); if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // remove stop/start characters character and check if a long enough string is contained if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize { // Almost surely a false positive ( start + stop + at least 1 character) - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } if !hints.contains_key(&DecodeHintType::RETURN_CODABAR_START_END) { @@ -231,7 +231,7 @@ impl CodaBarReader { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for // long stripes, while 0 and 1 are for short stripes. let category = (j & 1) + ((pattern as usize) & 1) * 2; - sizes[category] += self.counters[(pos + j) as usize]; + sizes[category] += self.counters[(pos + j)]; counts[category] += 1; pattern >>= 1; } @@ -269,7 +269,7 @@ impl CodaBarReader { let category = (j & 1) + ((pattern as usize) & 1) * 2; let size = self.counters[(pos + j)]; if (size as f32) < mins[category] || (size as f32) > maxes[category] { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } pattern >>= 1; } @@ -290,7 +290,7 @@ impl CodaBarReader { let mut i = row.getNextUnset(0); let end = row.getSize(); if i >= end { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let mut isWhite = true; let mut count = 0; @@ -344,7 +344,7 @@ impl CodaBarReader { i += 2; } - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } pub fn arrayContains(array: &[char], key: char) -> bool { @@ -355,7 +355,7 @@ impl CodaBarReader { } } // } - return false; + false } // Assumes that counters[position] is a bar. @@ -422,6 +422,6 @@ impl CodaBarReader { return i as i32; } } - return -1; + -1 } } diff --git a/src/oned/coda_bar_writer.rs b/src/oned/coda_bar_writer.rs index a8ca5df..5b30f13 100644 --- a/src/oned/coda_bar_writer.rs +++ b/src/oned/coda_bar_writer.rs @@ -30,7 +30,7 @@ const DEFAULT_GUARD: char = START_END_CHARS[0]; * * @author dsbnatut@gmail.com (Kazuki Nishiura) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct CodaBarWriter; impl OneDimensionalCodeWriter for CodaBarWriter { @@ -40,7 +40,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD) } else { // Verify input and calculate decoded length. - let firstChar = contents.chars().nth(0).unwrap().to_ascii_uppercase(); + let firstChar = contents.chars().next().unwrap().to_ascii_uppercase(); let lastChar = contents .chars() .nth(contents.chars().count() - 1) @@ -52,29 +52,29 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar); if startsNormal { if !endsNormal { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Invalid start/end guards: {}", contents - ))); + )))); } // else already has valid start/end contents.to_owned() } else if startsAlt { if !endsAlt { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Invalid start/end guards: {}", contents - ))); + )))); } // else already has valid start/end contents.to_owned() } else { // Doesn't start with a guard if endsNormal || endsAlt { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Invalid start/end guards: {}", contents - ))); + )))); } // else doesn't end with guard either, so add a default format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD) @@ -86,7 +86,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { //for i in 1..contents.chars().count() { for ch in contents[1..contents.chars().count() - 1].chars() { // for (int i = 1; i < contents.length() - 1; i++) { - if ch.is_digit(10) || ch == '-' || ch == '$' { + if ch.is_ascii_digit() || ch == '-' || ch == '$' { resultLength += 9; } else if CodaBarReader::arrayContains( &CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED, @@ -94,10 +94,10 @@ impl OneDimensionalCodeWriter for CodaBarWriter { ) { resultLength += 10; } else { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Cannot encode : '{}'", ch - ))); + )))); } } // A blank is placed between each character. @@ -155,12 +155,6 @@ impl OneDimensionalCodeWriter for CodaBarWriter { } } -impl Default for CodaBarWriter { - fn default() -> Self { - Self {} - } -} - /** * @author dsbnatut@gmail.com (Kazuki Nishiura) * @author Sean Owen diff --git a/src/oned/code_128_reader.rs b/src/oned/code_128_reader.rs index c4450a7..bdd3c25 100644 --- a/src/oned/code_128_reader.rs +++ b/src/oned/code_128_reader.rs @@ -25,7 +25,7 @@ use super::{one_d_reader, OneDReader}; * * @author Sean Owen */ -#[derive(OneDReader)] +#[derive(OneDReader, Default)] pub struct Code128Reader; impl OneDReader for Code128Reader { @@ -50,7 +50,7 @@ impl OneDReader for Code128Reader { CODE_START_A => CODE_CODE_A, CODE_START_B => CODE_CODE_B, CODE_START_C => CODE_CODE_C, - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), }; let mut done = false; @@ -106,7 +106,7 @@ impl OneDReader for Code128Reader { // Take care of illegal start codes match code { CODE_START_A | CODE_START_B | CODE_START_C => { - return Err(Exceptions::FormatException("".to_owned())) + return Err(Exceptions::FormatException(None)) } _ => {} } @@ -301,21 +301,21 @@ impl OneDReader for Code128Reader { row.getSize().min(nextStart + (nextStart - lastStart) / 2), false, )? { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier as usize * lastCode as usize; // lastCode is the checksum then: if (checksumTotal % 103) as u8 != lastCode { - return Err(Exceptions::ChecksumException("".to_owned())); + return Err(Exceptions::ChecksumException(None)); } // Need to pull out the check digits from string let resultLength = result.chars().count(); if resultLength == 0 { // false positive - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // Only bother if the result had at least one character, and if the checksum digit happened to @@ -340,9 +340,9 @@ impl OneDReader for Code128Reader { let rawCodesSize = rawCodes.len(); let mut rawBytes = vec![0u8; rawCodesSize]; - for i in 0..rawCodesSize { + for (i, rawByte) in rawBytes.iter_mut().enumerate().take(rawCodesSize) { // for (int i = 0; i < rawCodesSize; i++) { - rawBytes[i] = *rawCodes.get(i).unwrap(); + *rawByte = *rawCodes.get(i).unwrap(); } let mut resultObject = RXingResult::new( &result, @@ -419,7 +419,7 @@ impl Code128Reader { } } - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } fn decodeCode( @@ -435,7 +435,7 @@ impl Code128Reader { // for (int d = 0; d < CODE_PATTERNS.len(); d++) { let pattern = &CODE_PATTERNS[d]; let variance = - one_d_reader::patternMatchVariance(counters, &pattern, MAX_INDIVIDUAL_VARIANCE); + one_d_reader::patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if variance < bestVariance { bestVariance = variance; bestMatch = d as isize; @@ -445,17 +445,11 @@ impl Code128Reader { if bestMatch >= 0 { Ok(bestMatch as u8) } else { - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } } } -impl Default for Code128Reader { - fn default() -> Self { - Self {} - } -} - use lazy_static::lazy_static; lazy_static! { diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index 5db54ce..aa5f314 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -43,10 +43,10 @@ const CODE_FNC_4_B: usize = 100; // Code B // RXingResults of minimal lookahead for code C #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CType { - UNCODABLE, - ONE_DIGIT, - TWO_DIGITS, - FNC_1, + Uncodable, + OneDigit, + TwoDigits, + Fnc1, } /** @@ -54,13 +54,9 @@ enum CType { * * @author erik.barbara@gmail.com (Erik Barbara) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct Code128Writer; -impl Default for Code128Writer { - fn default() -> Self { - Self {} - } -} + impl OneDimensionalCodeWriter for Code128Writer { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { self.encode_oned_with_hints(contents, &HashMap::new()) @@ -98,11 +94,11 @@ impl OneDimensionalCodeWriter for Code128Writer { fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { let length = contents.chars().count(); // Check length - if length < 1 || length > 80 { - return Err(Exceptions::IllegalArgumentException(format!( + if !(1..=80).contains(&length) { + return Err(Exceptions::IllegalArgumentException(Some(format!( "Contents length should be between 1 and 80 characters, but got {}", length - ))); + )))); } // Check for forced code set hint. @@ -114,10 +110,10 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result forcedCodeSet = CODE_CODE_B as i32, "C" => forcedCodeSet = CODE_CODE_C as i32, _ => { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Unsupported code set hint: {}", codeSetHint - ))) + )))) } } } @@ -136,10 +132,10 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 127 { // no full Latin-1 character set available at the moment // shift and manual code change are not supported - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Bad character in input: ASCII value={}", c - ))); + )))); } } } @@ -152,20 +148,20 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 95 && c <= 127 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Bad character in input for forced code set A: ASCII value={}", c - ))); + )))); } } CODE_CODE_B_I32 => // allows no ascii below 32 (terminal symbols) { if c <= 32 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Bad character in input for forced code set B: ASCII value={}", c - ))); + )))); } } CODE_CODE_C_I32 => @@ -177,10 +173,10 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result {} @@ -225,7 +221,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception _ => // Then handle normal characters otherwise { - match codeSet as usize { + match codeSet { CODE_CODE_A => { patternIndex = contents.chars().nth(position).unwrap() as isize - ' ' as isize; @@ -242,9 +238,9 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception // CODE_CODE_C if position + 1 == length { // this is the last character, but the encoding is C, which always encodes two characers - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Bad number of characters for digit only encoding.".to_owned(), - )); + ))); } let s: String = contents .char_indices() @@ -266,7 +262,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception // Do we have a code set? if codeSet == 0 { // No, we don't have a code set - match newCodeSet as usize { + match newCodeSet { CODE_CODE_A => patternIndex = CODE_START_A as isize, CODE_CODE_B => patternIndex = CODE_START_B as isize, _ => patternIndex = CODE_START_C as isize, @@ -321,7 +317,7 @@ fn produceRXingResult(patterns: &mut Vec>, checkSum: usize) -> Vec>, checkSum: usize) -> Vec CType { let last = value.chars().count(); if start >= last { - return CType::UNCODABLE; + return CType::Uncodable; } let c = value.chars().nth(start).unwrap(); if c == ESCAPE_FNC_1 { - return CType::FNC_1; + return CType::Fnc1; } - if c < '0' || c > '9' { - return CType::UNCODABLE; + if !('0'..='9').contains(&c) { + return CType::Uncodable; } if start + 1 >= last { - return CType::ONE_DIGIT; + return CType::OneDigit; } let c = value.chars().nth(start + 1).unwrap(); - if c < '0' || c > '9' { - return CType::ONE_DIGIT; + if !('0'..='9').contains(&c) { + return CType::OneDigit; } - return CType::TWO_DIGITS; + CType::TwoDigits } fn chooseCode(value: &str, start: usize, oldCode: usize) -> usize { let mut lookahead = findCType(value, start); - if lookahead == CType::ONE_DIGIT { + if lookahead == CType::OneDigit { if oldCode == CODE_CODE_A { return CODE_CODE_A; } return CODE_CODE_B; } - if lookahead == CType::UNCODABLE { + if lookahead == CType::Uncodable { if start < value.chars().count() { let c = value.chars().nth(start).unwrap(); if c < ' ' @@ -378,7 +374,7 @@ fn chooseCode(value: &str, start: usize, oldCode: usize) -> usize { } return CODE_CODE_B; // no choice } - if oldCode == CODE_CODE_A && lookahead == CType::FNC_1 { + if oldCode == CODE_CODE_A && lookahead == CType::Fnc1 { return CODE_CODE_A; } if oldCode == CODE_CODE_C { @@ -386,18 +382,18 @@ fn chooseCode(value: &str, start: usize, oldCode: usize) -> usize { return CODE_CODE_C; } if oldCode == CODE_CODE_B { - if lookahead == CType::FNC_1 { + if lookahead == CType::Fnc1 { return CODE_CODE_B; // can continue in code B } // Seen two consecutive digits, see what follows lookahead = findCType(value, start + 2); - if lookahead == CType::UNCODABLE || lookahead == CType::ONE_DIGIT { + if lookahead == CType::Uncodable || lookahead == CType::OneDigit { return CODE_CODE_B; // not worth switching now } - if lookahead == CType::FNC_1 { + if lookahead == CType::Fnc1 { // two digits, then FNC_1... lookahead = findCType(value, start + 3); - if lookahead == CType::TWO_DIGITS { + if lookahead == CType::TwoDigits { // then two more digits, switch return CODE_CODE_C; } else { @@ -408,27 +404,27 @@ fn chooseCode(value: &str, start: usize, oldCode: usize) -> usize { // Look ahead to choose whether to switch now or on the next round. let mut index = start + 4; let mut lookahead = findCType(value, index); - while lookahead == CType::TWO_DIGITS { + while lookahead == CType::TwoDigits { // while (lookahead = findCType(value, index)) == CType::TWO_DIGITS { index += 2; lookahead = findCType(value, index); } - if lookahead == CType::ONE_DIGIT { + if lookahead == CType::OneDigit { // odd number of digits, switch later return CODE_CODE_B; } return CODE_CODE_C; // even number of digits, switch now } // Here oldCode == 0, which means we are choosing the initial code - if lookahead == CType::FNC_1 { + if lookahead == CType::Fnc1 { // ignore FNC_1 lookahead = findCType(value, start + 1); } - if lookahead == CType::TWO_DIGITS { + if lookahead == CType::TwoDigits { // at least two digits, start in code C return CODE_CODE_C; } - return CODE_CODE_B; + CODE_CODE_B } /** @@ -452,15 +448,15 @@ mod MinimalEncoder { A, B, C, - NONE, + None, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Latch { A, B, C, - SHIFT, - NONE, + Shift, + None, } const A : &str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\u{0000}\u{0001}\u{0002}/ @@ -476,14 +472,14 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; pub fn encode(contents: &str) -> Result, Exceptions> { let length = contents.chars().count(); let mut memoizedCost = vec![vec![0_u32; length]; 4]; //new int[4][contents.length()]; - let mut minPath = vec![vec![Latch::NONE; length]; 4]; //new Latch[4][contents.length()]; + let mut minPath = vec![vec![Latch::None; length]; 4]; //new Latch[4][contents.length()]; - encode_with_start_position(contents, Charset::NONE, 0, &mut memoizedCost, &mut minPath)?; + encode_with_start_position(contents, Charset::None, 0, &mut memoizedCost, &mut minPath)?; let mut patterns: Vec> = Vec::new(); //new ArrayList<>(); let mut checkSum = vec![0_usize]; //new int[] {0}; let mut checkWeight = vec![1]; //new int[] {1}; - let mut charset = Charset::NONE; + let mut charset = Charset::None; let mut i = 0; while i < length { // for i in 0..length { @@ -520,14 +516,14 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; i, ); } - Latch::SHIFT => addPattern( + Latch::Shift => addPattern( &mut patterns, CODE_SHIFT, &mut checkSum, &mut checkWeight, i, ), - Latch::NONE => { /* skip */ } + Latch::None => { /* skip */ } } if charset == Charset::C { if contents.chars().nth(i).unwrap() == ESCAPE_FNC_1 { @@ -564,8 +560,8 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; ESCAPE_FNC_2 => CODE_FNC_2 as isize, ESCAPE_FNC_3 => CODE_FNC_3 as isize, ESCAPE_FNC_4 => { - if (charset == Charset::A && latch != Latch::SHIFT) - || (charset == Charset::B && latch == Latch::SHIFT) + if (charset == Charset::A && latch != Latch::Shift) + || (charset == Charset::B && latch == Latch::Shift) { CODE_FNC_4_A as isize } else { @@ -574,12 +570,11 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } _ => contents.chars().nth(i).unwrap() as isize - ' ' as isize, }; - if (charset == Charset::A && latch != Latch::SHIFT) - || (charset == Charset::B && latch == Latch::SHIFT) + if ((charset == Charset::A && latch != Latch::Shift) + || (charset == Charset::B && latch == Latch::Shift)) + && patternIndex < 0 { - if patternIndex < 0 { - patternIndex += '`' as isize; - } + patternIndex += '`' as isize; } addPattern( &mut patterns, @@ -618,7 +613,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } fn isDigit(c: char) -> bool { - return c >= '0' && c <= '9'; + ('0'..='9').contains(&c) } fn canEncode(contents: &str, charset: Charset, position: usize) -> bool { @@ -665,7 +660,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } let mut minCost = u32::MAX; - let mut minLatch = Latch::NONE; + let mut minLatch = Latch::None; let atEnd = position + 1 >= contents.chars().count(); let sets = [Charset::A, Charset::B]; @@ -673,7 +668,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; // for (int i = 0; i <= 1; i++) { if canEncode(contents, sets[i], position) { let mut cost = 1; - let mut latch = Latch::NONE; + let mut latch = Latch::None; if charset != sets[i] { cost += 1; latch = sets[i].into(); //Latch::valueOf(sets[i].toString()); @@ -694,7 +689,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; cost = 1; if charset == sets[(i + 1) % 2] { cost += 1; - latch = Latch::SHIFT; + latch = Latch::Shift; if !atEnd { cost += encode_with_start_position( contents, @@ -713,7 +708,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } if canEncode(contents, Charset::C, position) { let mut cost = 1; - let mut latch = Latch::NONE; + let mut latch = Latch::None; if charset != Charset::C { cost += 1; latch = Latch::C; @@ -738,10 +733,10 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } } if minCost == u32::MAX { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Bad character in input: ASCII value={}", contents.chars().nth(position).unwrap_or('x') - ))); + )))); // throw new IllegalArgumentException("Bad character in input: ASCII value=" + (int) contents.charAt(position)); } memoizedCost[charset.ordinal()][position] = minCost; @@ -759,7 +754,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; Charset::A => 0, Charset::B => 1, Charset::C => 2, - Charset::NONE => 3, + Charset::None => 3, } } } @@ -769,8 +764,8 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; Latch::A => 0, Latch::B => 1, Latch::C => 2, - Latch::SHIFT => 3, - Latch::NONE => 4, + Latch::Shift => 3, + Latch::None => 4, } } } @@ -780,7 +775,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; Charset::A => Latch::A, Charset::B => Latch::B, Charset::C => Latch::C, - Charset::NONE => Latch::NONE, + Charset::None => Latch::None, } } } diff --git a/src/oned/code_39_reader.rs b/src/oned/code_39_reader.rs index aa8b0c6..198edc8 100644 --- a/src/oned/code_39_reader.rs +++ b/src/oned/code_39_reader.rs @@ -64,7 +64,7 @@ impl OneDReader for Code39Reader { one_d_reader::recordPattern(row, nextStart, &mut counters)?; let pattern = Self::toNarrowWidePattern(&counters); if pattern < 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -76,7 +76,7 @@ impl OneDReader for Code39Reader { // Read off white space nextStart = row.getNextSet(nextStart); - if !(decodedChar != '*') { + if decodedChar == '*' { break; } } //(decodedChar != '*'); @@ -93,7 +93,7 @@ impl OneDReader for Code39Reader { // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if nextStart != end && (whiteSpaceAfterEnd * 2) < lastPatternSize as usize { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } if self.usingCheckDigit { @@ -111,22 +111,21 @@ impl OneDReader for Code39Reader { if self.decodeRowRXingResult.chars().nth(max).unwrap() != Self::ALPHABET_STRING.chars().nth(total % 43).unwrap() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } self.decodeRowRXingResult.truncate(max); } if self.decodeRowRXingResult.chars().count() == 0 { // false positive - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } - let resultString; - if self.extendedMode { - resultString = Self::decodeExtended(&self.decodeRowRXingResult)?; + let resultString = if self.extendedMode { + Self::decodeExtended(&self.decodeRowRXingResult)? } else { - resultString = self.decodeRowRXingResult.clone(); - } + self.decodeRowRXingResult.clone() + }; let left = (start[1] + start[0]) as f32 / 2.0; let right = (lastStart + lastPatternSize as usize) as f32 / 2.0; @@ -247,7 +246,7 @@ impl Code39Reader { isWhite = !isWhite; } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions @@ -268,13 +267,12 @@ impl Code39Reader { wideCounters = 0; let mut totalWideCountersWidth = 0; let mut pattern = 0; - for i in 0..numCounters { + for (i, counter) in counters.iter().enumerate().take(numCounters) { // for (int i = 0; i < numCounters; i++) { - let counter = counters[i]; - if counter > maxNarrowCounter { + if *counter > maxNarrowCounter { pattern |= 1 << (numCounters - 1 - i); wideCounters += 1; - totalWideCountersWidth += counter; + totalWideCountersWidth += *counter; } } if wideCounters == 3 { @@ -298,11 +296,11 @@ impl Code39Reader { return pattern; } - if !(wideCounters > 3) { + if wideCounters <= 3 { break; } } //while ; - return -1; + -1 } fn patternToChar(pattern: u32) -> Result { @@ -315,7 +313,7 @@ impl Code39Reader { if pattern == Self::ASTERISK_ENCODING { return Ok('*'); } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn decodeExtended(encoded: &str) -> Result { @@ -332,29 +330,29 @@ impl Code39Reader { match c { '+' => { // +A to +Z map to a to z - if next >= 'A' && next <= 'Z' { + if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 + 32).unwrap(); } else { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } } '$' => { // $A to $Z map to control codes SH to SB - if next >= 'A' && next <= 'Z' { + if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 - 64).unwrap(); } else { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } } '%' => { // %A to %E map to control codes ESC to US - if next >= 'A' && next <= 'E' { + if ('A'..='E').contains(&next) { decodedChar = char::from_u32(next as u32 - 38).unwrap(); - } else if next >= 'F' && next <= 'J' { + } else if ('F'..='J').contains(&next) { decodedChar = char::from_u32(next as u32 - 11).unwrap(); - } else if next >= 'K' && next <= 'O' { + } else if ('K'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 + 16).unwrap(); - } else if next >= 'P' && next <= 'T' { + } else if ('P'..='T').contains(&next) { decodedChar = char::from_u32(next as u32 + 43).unwrap(); } else if next == 'U' { decodedChar = 0 as char; @@ -365,17 +363,17 @@ impl Code39Reader { } else if next == 'X' || next == 'Y' || next == 'Z' { decodedChar = 127 as char; } else { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } } '/' => { // /A to /O map to ! to , and /Z maps to : - if next >= 'A' && next <= 'O' { + if ('A'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 - 32).unwrap(); } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } } _ => {} diff --git a/src/oned/code_39_writer.rs b/src/oned/code_39_writer.rs index bd4b735..87e8a67 100644 --- a/src/oned/code_39_writer.rs +++ b/src/oned/code_39_writer.rs @@ -25,33 +25,32 @@ use super::{Code39Reader, OneDimensionalCodeWriter}; * * @author erik.barbara@gmail.com (Erik Barbara) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct Code39Writer; -impl Default for Code39Writer { - fn default() -> Self { - Self {} - } -} - impl OneDimensionalCodeWriter for Code39Writer { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { let mut contents = contents.to_owned(); let mut length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested contents should be less than 80 digits long, but got {}", length - ))); + )))); } - for i in 0..length { + let mut i = 0; + while i < length { + // for i in 0..length { // for (int i = 0; i < length; i++) { - if let None = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).unwrap()) { + if Code39Reader::ALPHABET_STRING + .find(contents.chars().nth(i).unwrap()) + .is_none() + { contents = Self::tryToConvertToExtendedMode(&contents)?; length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(format!("Requested contents should be less than 80 digits long, but got {} (extended full ASCII mode)",length))); + return Err(Exceptions::IllegalArgumentException(Some(format!("Requested contents should be less than 80 digits long, but got {} (extended full ASCII mode)",length)))); } break; } @@ -64,6 +63,7 @@ impl OneDimensionalCodeWriter for Code39Writer { // } // break; // } + i += 1; } let mut widths = [0_usize; 9]; //new int[9]; @@ -99,10 +99,10 @@ impl OneDimensionalCodeWriter for Code39Writer { } impl Code39Writer { fn toIntArray(a: u32, toReturn: &mut [usize; 9]) { - for i in 0..9 { + for (i, val) in toReturn.iter_mut().enumerate().take(9) { // for (int i = 0; i < 9; i++) { let temp = a & (1 << (8 - i)); - toReturn[i] = if temp == 0 { 1 } else { 2 }; + *val = if temp == 0 { 1 } else { 2 }; } } @@ -155,10 +155,10 @@ impl Code39Writer { extendedContent .push(char::from_u32('P' as u32 + (character as u32 - 123)).unwrap()); } else { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested content contains a non-encodable character: '{}'", character - ))); + )))); } } } diff --git a/src/oned/code_93_reader.rs b/src/oned/code_93_reader.rs index 62f7ac5..68b784d 100644 --- a/src/oned/code_93_reader.rs +++ b/src/oned/code_93_reader.rs @@ -63,7 +63,7 @@ impl OneDReader for Code93Reader { one_d_reader::recordPattern(row, nextStart, &mut theCounters)?; let pattern = Self::toPattern(&theCounters); if pattern < 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -75,7 +75,7 @@ impl OneDReader for Code93Reader { // Read off white space nextStart = row.getNextSet(nextStart); - if !(decodedChar != '*') { + if decodedChar == '*' { break; } } //while (decodedChar != '*'); @@ -92,12 +92,12 @@ impl OneDReader for Code93Reader { // Should be at least one more black module if nextStart == end || !row.get(nextStart) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } if self.decodeRowRXingResult.chars().count() < 2 { // false positive -- need at least 2 checksum digits - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Self::checkChecksums(&self.decodeRowRXingResult)?; @@ -193,7 +193,7 @@ impl Code93Reader { isWhite = !isWhite; } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn toPattern(counters: &[u32; 6]) -> i32 { @@ -204,11 +204,11 @@ impl Code93Reader { } let mut pattern = 0; let max = counters.len(); - for i in 0..max { + for (i, counter) in counters.iter().enumerate().take(max) { // for (int i = 0; i < max; i++) { - let scaled = (counters[i] as f32 * 9.0 / sum as f32).round() as u32; + let scaled = (*counter as f32 * 9.0 / sum as f32).round() as u32; // let scaled = Math.round(counters[i] * 9.0 / sum); - if scaled < 1 || scaled > 4 { + if !(1..=4).contains(&scaled) { return -1; } if (i & 0x01) == 0 { @@ -220,7 +220,7 @@ impl Code93Reader { pattern <<= scaled; } } - return pattern; + pattern } fn patternToChar(pattern: u32) -> Result { @@ -230,7 +230,7 @@ impl Code93Reader { return Ok(Self::ALPHABET[i]); } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn decodeExtended(encoded: &str) -> Result { @@ -241,40 +241,40 @@ impl Code93Reader { // for i in 0..length { // for (int i = 0; i < length; i++) { let c = encoded.chars().nth(i).unwrap(); - if c >= 'a' && c <= 'd' { + if ('a'..='d').contains(&c) { if i >= length - 1 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } let next = encoded.chars().nth(i + 1).unwrap(); let mut decodedChar = '\0'; match c { 'd' => { // +A to +Z map to a to z - if next >= 'A' && next <= 'Z' { + if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 + 32).unwrap(); } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } 'a' => { // $A to $Z map to control codes SH to SB - if next >= 'A' && next <= 'Z' { + if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 - 64).unwrap(); } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } 'b' => { - if next >= 'A' && next <= 'E' { + if ('A'..='E').contains(&next) { // %A to %E map to control codes ESC to USep decodedChar = char::from_u32(next as u32 - 38).unwrap(); - } else if next >= 'F' && next <= 'J' { + } else if ('F'..='J').contains(&next) { // %F to %J map to ; < = > ? decodedChar = char::from_u32(next as u32 - 11).unwrap(); - } else if next >= 'K' && next <= 'O' { + } else if ('K'..='O').contains(&next) { // %K to %O map to [ \ ] ^ _ decodedChar = char::from_u32(next as u32 + 16).unwrap(); - } else if next >= 'P' && next <= 'T' { + } else if ('P'..='T').contains(&next) { // %P to %T map to { | } ~ DEL decodedChar = char::from_u32(next as u32 + 43).unwrap(); } else if next == 'U' { @@ -286,21 +286,21 @@ impl Code93Reader { } else if next == 'W' { // %W map to ` decodedChar = '`'; - } else if next >= 'X' && next <= 'Z' { + } else if ('X'..='Z').contains(&next) { // %X to %Z all map to DEL (127) decodedChar = 127 as char; } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } 'c' => { // /A to /O map to ! to , and /Z maps to : - if next >= 'A' && next <= 'O' { + if ('A'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 - 32).unwrap(); } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } _ => {} @@ -345,7 +345,7 @@ impl Code93Reader { } } if result.chars().nth(checkPosition).unwrap() != Self::ALPHABET[(total as usize) % 47] { - Err(Exceptions::ChecksumException("".to_owned())) + Err(Exceptions::ChecksumException(None)) } else { Ok(()) } diff --git a/src/oned/code_93_writer.rs b/src/oned/code_93_writer.rs index 7a8c34c..46ed4af 100644 --- a/src/oned/code_93_writer.rs +++ b/src/oned/code_93_writer.rs @@ -23,15 +23,9 @@ use super::{Code93Reader, OneDimensionalCodeWriter}; /** * This object renders a CODE93 code as a BitMatrix */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct Code93Writer; -impl Default for Code93Writer { - fn default() -> Self { - Self {} - } -} - impl OneDimensionalCodeWriter for Code93Writer { /** * @param contents barcode contents to encode. It should not be encoded for extended characters. @@ -41,7 +35,7 @@ impl OneDimensionalCodeWriter for Code93Writer { let mut contents = Self::convertToExtended(contents)?; let length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {}" , length))); + return Err(Exceptions::IllegalArgumentException(Some(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {}" , length)))); } //length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar @@ -202,10 +196,10 @@ impl Code93Writer { extendedContent .push(char::from_u32('P' as u32 + character as u32 - '{' as u32).unwrap()); } else { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested content contains a non-encodable character: '{}'", character - ))); + )))); } } diff --git a/src/oned/ean_13_reader.rs b/src/oned/ean_13_reader.rs index 695cab8..a0c53d7 100644 --- a/src/oned/ean_13_reader.rs +++ b/src/oned/ean_13_reader.rs @@ -31,7 +31,7 @@ use crate::Exceptions; * @author Sean Owen * @author alasdair@google.com (Alasdair Mackintosh) */ -#[derive(OneDReader, EANReader)] +#[derive(OneDReader, EANReader, Default)] pub struct EAN13Reader; impl UPCEANReader for EAN13Reader { fn getBarcodeFormat(&self) -> crate::BarcodeFormat { @@ -154,12 +154,6 @@ impl EAN13Reader { return Ok(()); } } - return Err(Exceptions::NotFoundException("".to_owned())); - } -} - -impl Default for EAN13Reader { - fn default() -> Self { - Self {} + Err(Exceptions::NotFoundException(None)) } } diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index 1f566d3..70943f4 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -28,7 +28,7 @@ use super::{OneDimensionalCodeWriter, UPCEANReader, UPCEANWriter}; * * @author aripollak@gmail.com (Ari Pollak) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct EAN13Writer; impl UPCEANWriter for EAN13Writer {} @@ -40,9 +40,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { match length { 12 => { // No check digit present, calculate it and add it - let check; + // try { - check = reader.getStandardUPCEANChecksum(&contents)?; + let check = reader.getStandardUPCEANChecksum(&contents)?; // } catch (FormatException fe) { // throw new IllegalArgumentException(fe); // } @@ -51,25 +51,25 @@ impl OneDimensionalCodeWriter for EAN13Writer { 13 => { //try { if !reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Contents do not pass checksum".to_owned(), - )); + ))); } //} catch (FormatException ignored) { //return Err( Exceptions::IllegalArgumentException("Illegal contents".to_owned())); //} } _ => { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested contents should be 12 or 13 digits long, but got {}", length - ))) + )))) } } EAN13Writer::checkNumeric(&contents)?; - let firstDigit = contents.chars().nth(0).unwrap().to_digit(10).unwrap() as usize; //, 10); + let firstDigit = contents.chars().next().unwrap().to_digit(10).unwrap() as usize; //, 10); let parities = EAN13Reader::FIRST_DIGIT_ENCODINGS[firstDigit]; let mut result = [false; CODE_WIDTH]; let mut pos = 0; @@ -123,11 +123,6 @@ impl OneDimensionalCodeWriter for EAN13Writer { Self::DEFAULT_MARGIN } } -impl Default for EAN13Writer { - fn default() -> Self { - Self {} - } -} const CODE_WIDTH: usize = 3 + // start guard (7 * 6) + // left bars diff --git a/src/oned/ean_8_reader.rs b/src/oned/ean_8_reader.rs index 046c816..72b7049 100644 --- a/src/oned/ean_8_reader.rs +++ b/src/oned/ean_8_reader.rs @@ -26,7 +26,7 @@ use super::UPCEANReader; * * @author Sean Owen */ -#[derive(OneDReader, EANReader)] +#[derive(OneDReader, EANReader, Default)] pub struct EAN8Reader; impl UPCEANReader for EAN8Reader { @@ -83,9 +83,3 @@ impl UPCEANReader for EAN8Reader { Ok(rowOffset) } } - -impl Default for EAN8Reader { - fn default() -> Self { - Self {} - } -} diff --git a/src/oned/ean_8_writer.rs b/src/oned/ean_8_writer.rs index 87c3caa..70e1462 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -28,7 +28,7 @@ use super::{upc_ean_reader, OneDimensionalCodeWriter, UPCEANWriter}; * * @author aripollak@gmail.com (Ari Pollak) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct EAN8Writer; const CODE_WIDTH: usize = 3 + // start guard @@ -37,11 +37,6 @@ const CODE_WIDTH: usize = 3 + // start guard (7 * 4) + // right bars 3; // end guard -impl Default for EAN8Writer { - fn default() -> Self { - Self {} - } -} impl UPCEANWriter for EAN8Writer {} impl OneDimensionalCodeWriter for EAN8Writer { /** @@ -66,19 +61,19 @@ impl OneDimensionalCodeWriter for EAN8Writer { // try { { if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Contents do not pass checksum".to_owned(), - )); + ))); } } // } catch (FormatException ignored) { // throw new IllegalArgumentException("Illegal contents"); // }}, _ => { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested contents should be 7 or 8 digits long, but got {}", length - ))) + )))) } } diff --git a/src/oned/itf_reader.rs b/src/oned/itf_reader.rs index 6c9db8a..14310d0 100644 --- a/src/oned/itf_reader.rs +++ b/src/oned/itf_reader.rs @@ -151,7 +151,7 @@ impl OneDReader for ITFReader { lengthOK = true; } if !lengthOK { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } let mut resultObject = RXingResult::new( @@ -277,7 +277,7 @@ impl ITFReader { if quietCount != 0 { // Unable to find the necessary number of quiet zone pixels. - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } else { Ok(()) } @@ -294,7 +294,7 @@ impl ITFReader { let width = row.getSize(); let endStart = row.getNextSet(0); if endStart == width { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(endStart) @@ -397,7 +397,7 @@ impl ITFReader { isWhite = !isWhite; } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } /** @@ -412,9 +412,8 @@ impl ITFReader { let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestMatch = -1_isize; let max = PATTERNS.len(); - for i in 0..max { + for (i, pattern) in PATTERNS.iter().enumerate().take(max) { // for (int i = 0; i < max; i++) { - let pattern = &PATTERNS[i]; let variance = one_d_reader::patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if variance < bestVariance { @@ -428,7 +427,7 @@ impl ITFReader { if bestMatch >= 0 { Ok(bestMatch as u32 % 10) } else { - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } } } diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index da16523..5d131f7 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -25,28 +25,22 @@ use super::OneDimensionalCodeWriter; * * @author erik.barbara@gmail.com (Erik Barbara) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct ITFWriter; -impl Default for ITFWriter { - fn default() -> Self { - Self {} - } -} - impl OneDimensionalCodeWriter for ITFWriter { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { let length = contents.chars().count(); if length % 2 != 0 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "The length of the input should be even".to_owned(), - )); + ))); } if length > 80 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested contents should be less than 80 digits long, but got {}", length - ))); + )))); } Self::checkNumeric(contents)?; diff --git a/src/oned/multi_format_one_d_reader.rs b/src/oned/multi_format_one_d_reader.rs index 1b686d1..e5d4519 100644 --- a/src/oned/multi_format_one_d_reader.rs +++ b/src/oned/multi_format_one_d_reader.rs @@ -51,7 +51,7 @@ impl OneDReader for MultiFormatOneDReader { // } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } impl MultiFormatOneDReader { @@ -111,12 +111,10 @@ impl MultiFormatOneDReader { } } -use crate::result_point::ResultPoint; use crate::DecodeHintType; use crate::DecodingHintDictionary; use crate::RXingResultMetadataType; use crate::RXingResultMetadataValue; -use crate::RXingResultPoint; use crate::Reader; use std::collections::HashMap; @@ -167,18 +165,21 @@ impl Reader for MultiFormatOneDReader { // for point in result.getRXingResultPointsMut().iter_mut() { let total_points = result.getRXingResultPoints().len(); let points = result.getRXingResultPointsMut(); - for i in 0..total_points { + for point in points.iter_mut().take(total_points) { + // for i in 0..total_points { // for (int i = 0; i < points.length; i++) { - points[i] = RXingResultPoint::new( - height as f32 - points[i].getY() - 1.0, - points[i].getX(), - ); + std::mem::swap(&mut point.x, &mut point.y); + point.x = height as f32 - point.x - 1.0; + // points[i] = RXingResultPoint::new( + // height as f32 - points[i].getY() - 1.0, + // points[i].getX(), + // ); } // } Ok(result) } else { - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } } diff --git a/src/oned/multi_format_upc_ean_reader.rs b/src/oned/multi_format_upc_ean_reader.rs index 529689f..f7861ee 100644 --- a/src/oned/multi_format_upc_ean_reader.rs +++ b/src/oned/multi_format_upc_ean_reader.rs @@ -89,7 +89,7 @@ impl MultiFormatUPCEANReader { // // But, don't return UPC-A if UPC-A was not a requested format! let ean13MayBeUPCA = result.getBarcodeFormat() == &BarcodeFormat::EAN_13 - && result.getText().chars().nth(0).unwrap() == '0'; + && result.getText().starts_with('0'); let canReturnUPCA = if let Some(DecodeHintValue::PossibleFormats(possibleFormats)) = hints.get(&DecodeHintType::POSSIBLE_FORMATS) @@ -134,16 +134,14 @@ impl OneDReader for MultiFormatUPCEANReader { } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } -use crate::result_point::ResultPoint; use crate::DecodeHintType; use crate::DecodingHintDictionary; use crate::RXingResultMetadataType; use crate::RXingResultMetadataValue; -use crate::RXingResultPoint; use std::collections::HashMap; impl Reader for MultiFormatUPCEANReader { @@ -193,18 +191,21 @@ impl Reader for MultiFormatUPCEANReader { // for point in result.getRXingResultPointsMut().iter_mut() { let total_points = result.getRXingResultPoints().len(); let points = result.getRXingResultPointsMut(); - for i in 0..total_points { + for point in points.iter_mut().take(total_points) { + // for i in 0..total_points { // for (int i = 0; i < points.length; i++) { - points[i] = RXingResultPoint::new( - height as f32 - points[i].getY() - 1.0, - points[i].getX(), - ); + std::mem::swap(&mut point.x, &mut point.y); + point.x = height as f32 - point.x - 1.0; + // points[i] = RXingResultPoint::new( + // height as f32 - points[i].getY() - 1.0, + // points[i].getX(), + // ); } // } Ok(result) } else { - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } } diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 29b7240..9cf9fcc 100644 --- a/src/oned/one_d_code_writer.rs +++ b/src/oned/one_d_code_writer.rs @@ -103,9 +103,9 @@ pub trait OneDimensionalCodeWriter: Writer { */ fn checkNumeric(contents: &str) -> Result<(), Exceptions> { if !NUMERIC.is_match(contents) { - Err(Exceptions::IllegalArgumentException( + Err(Exceptions::IllegalArgumentException(Some( "Input should only contain digits 0-9".to_owned(), - )) + ))) } else { Ok(()) } @@ -168,23 +168,23 @@ impl Writer for L { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Found empty contents".to_owned(), - )); + ))); } if width < 0 || height < 0 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Negative size is not allowed. Input: {}x{}", width, height - ))); + )))); } if let Some(supportedFormats) = self.getSupportedWriteFormats() { if !supportedFormats.contains(format) { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode {:?}, but got {:?}", supportedFormats, format - ))); + )))); } } diff --git a/src/oned/one_d_reader.rs b/src/oned/one_d_reader.rs index b8939cc..a6b7418 100644 --- a/src/oned/one_d_reader.rs +++ b/src/oned/one_d_reader.rs @@ -54,12 +54,11 @@ pub trait OneDReader: Reader { let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER); let rowStep = 1.max(height >> (if tryHarder { 8 } else { 5 })); - let maxLines; - if tryHarder { - maxLines = height; // Look at the whole image, not just the center + let maxLines = if tryHarder { + height // Look at the whole image, not just the center } else { - maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image - } + 15 // 15 rows spaced 1/32 apart is roughly the middle half of the image + }; let middle = height / 2; for x in 0..maxLines { @@ -143,7 +142,7 @@ pub trait OneDReader: Reader { } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } /** @@ -193,7 +192,7 @@ pub fn patternMatchVariance(counters: &[u32], pattern: &[u32], maxIndividualVari } let unitBarWidth = total / patternLength as f32; - maxIndividualVariance *= unitBarWidth as f32; + maxIndividualVariance *= unitBarWidth; let mut totalVariance = 0.0; for x in 0..numCounters { @@ -210,7 +209,7 @@ pub fn patternMatchVariance(counters: &[u32], pattern: &[u32], maxIndividualVari } totalVariance += variance; } - return totalVariance / total; + totalVariance / total } /** @@ -232,7 +231,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu counters.fill(0); let end = row.getSize(); if start >= end { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let mut isWhite = !row.get(start); let mut counterPosition = 0; @@ -254,7 +253,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. if !(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end)) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(()) } @@ -276,7 +275,7 @@ pub fn recordPatternInReverse( } } if numTransitionsLeft >= 0 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } recordPattern(row, start + 1, counters)?; diff --git a/src/oned/rss/abstract_rss_reader.rs b/src/oned/rss/abstract_rss_reader.rs index c684c24..9a5e6c6 100644 --- a/src/oned/rss/abstract_rss_reader.rs +++ b/src/oned/rss/abstract_rss_reader.rs @@ -47,18 +47,16 @@ pub trait AbstractRSSReaderTrait: OneDReader { // } fn parseFinderValue(counters: &[u32], finderPatterns: &[[u32; 4]]) -> Result { - for value in 0..finderPatterns.len() { + for (value, pattern) in finderPatterns.iter().enumerate() { + // for value in 0..finderPatterns.len() { // for (int value = 0; value < finderPatterns.length; value++) { - if one_d_reader::patternMatchVariance( - counters, - &finderPatterns[value], - Self::MAX_INDIVIDUAL_VARIANCE, - ) < Self::MAX_AVG_VARIANCE + if one_d_reader::patternMatchVariance(counters, pattern, Self::MAX_INDIVIDUAL_VARIANCE) + < Self::MAX_AVG_VARIANCE { return Ok(value as u32); } } - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } /** @@ -74,10 +72,10 @@ pub trait AbstractRSSReaderTrait: OneDReader { fn increment(array: &mut [u32], errors: &[f32]) { let mut index = 0; let mut biggestError = errors[0]; - for i in 1..array.len() { + for (i, error) in errors.iter().enumerate().take(array.len()).skip(1) { // for (int i = 1; i < array.length; i++) { - if errors[i] > biggestError { - biggestError = errors[i]; + if *error > biggestError { + biggestError = *error; index = i; } } @@ -87,10 +85,11 @@ pub trait AbstractRSSReaderTrait: OneDReader { fn decrement(array: &mut [u32], errors: &[f32]) { let mut index = 0; let mut biggestError = errors[0]; - for i in 1..array.len() { + for (i, error) in errors.iter().enumerate().take(array.len()).skip(1) { + // for i in 1..array.len() { // for (int i = 1; i < array.length; i++) { - if errors[i] < biggestError { - biggestError = errors[i]; + if *error < biggestError { + biggestError = *error; index = i; } } @@ -116,6 +115,6 @@ pub trait AbstractRSSReaderTrait: OneDReader { } return maxCounter < 10 * minCounter; } - return false; + false } } diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index 22b49ff..6cb93a8 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -53,9 +53,9 @@ pub fn buildBitArrayFromString(data: &str) -> Result { if i % 9 == 0 { // spaces if dotsAndXs.chars().nth(i).unwrap() != ' ' { - return Err(Exceptions::IllegalStateException( + return Err(Exceptions::IllegalStateException(Some( "space expected".to_owned(), - )); + ))); } continue; } diff --git a/src/oned/rss/expanded/bit_array_builder.rs b/src/oned/rss/expanded/bit_array_builder.rs index b9a658a..4c1ec96 100644 --- a/src/oned/rss/expanded/bit_array_builder.rs +++ b/src/oned/rss/expanded/bit_array_builder.rs @@ -35,7 +35,7 @@ use super::ExpandedPair; pub fn buildBitArray(pairs: &Vec) -> BitArray { let mut charNumber = (pairs.len() * 2) - 1; - if pairs.get(pairs.len() - 1).unwrap().getRightChar().is_none() { + if pairs.last().unwrap().getRightChar().is_none() { charNumber -= 1; } @@ -88,7 +88,7 @@ pub fn buildBitArray(pairs: &Vec) -> BitArray { } } } - return binary; + binary } /** @@ -118,9 +118,8 @@ mod BitArrayBuilderTest { fn buildBitArray(pairValues: &Vec>) -> BitArray { let mut pairs = Vec::new(); //new ArrayList<>(); - for i in 0..pairValues.len() { + for (i, pair) in pairValues.iter().enumerate() { // for (int i = 0; i < pairValues.length; ++i) { - let pair = &pairValues[i]; let leftChar = if i == 0 { None diff --git a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs index 342f648..e7dbe58 100644 --- a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs +++ b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs @@ -149,8 +149,8 @@ pub fn createDecoder<'a>( _ => {} } - Err(Exceptions::IllegalStateException(format!( + Err(Exceptions::IllegalStateException(Some(format!( "unknown decoder: {}", information - ))) + )))) } diff --git a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs index d5b1cbe..4e487d4 100644 --- a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01392xDecoder<'_> {} impl AbstractExpandedDecoder for AI01392xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::NotFoundException("".to_owned())); + return Err(crate::Exceptions::NotFoundException(None)); } let mut buf = String::new(); @@ -58,7 +58,7 @@ impl AbstractExpandedDecoder for AI01392xDecoder<'_> { Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::LAST_DIGIT_SIZE, "", )?; - buf.push_str(&decodedInformation.getNewString()); + buf.push_str(decodedInformation.getNewString()); Ok(buf) } diff --git a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs index 31b0c99..d6dbd9b 100644 --- a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01393xDecoder<'_> {} impl AbstractExpandedDecoder for AI01393xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::NotFoundException("".to_owned())); + return Err(crate::Exceptions::NotFoundException(None)); } let mut buf = String::new(); @@ -74,7 +74,7 @@ impl AbstractExpandedDecoder for AI01393xDecoder<'_> { + Self::FIRST_THREE_DIGITS_SIZE, "", )?; - buf.push_str(&generalInformation.getNewString()); + buf.push_str(generalInformation.getNewString()); Ok(buf) } diff --git a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs index fb764de..6ee8153 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs @@ -57,7 +57,7 @@ impl AbstractExpandedDecoder for AI013x0x1xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE + Self::DATE_SIZE { - return Err(crate::Exceptions::NotFoundException("".to_owned())); + return Err(crate::Exceptions::NotFoundException(None)); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs index 22524d7..0c70233 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs @@ -53,7 +53,7 @@ impl AbstractExpandedDecoder for AI013x0xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE { - return Err(crate::Exceptions::NotFoundException("".to_owned())); + return Err(crate::Exceptions::NotFoundException(None)); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs b/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs index 0a24d32..1133974 100644 --- a/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs +++ b/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs @@ -33,7 +33,7 @@ use super::{AI01decoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ pub struct AI01AndOtherAIs<'a>(&'a BitArray, GeneralAppIdDecoder<'a>); -impl<'a> AI01decoder for AI01AndOtherAIs<'_> {} +impl AI01decoder for AI01AndOtherAIs<'_> {} impl AbstractExpandedDecoder for AI01AndOtherAIs<'_> { fn parseInformation(&mut self) -> Result { let mut buff = String::new(); //new StringBuilder(); diff --git a/src/oned/rss/expanded/decoders/block_parsed_result.rs b/src/oned/rss/expanded/decoders/block_parsed_result.rs index f0fd4b9..9781762 100644 --- a/src/oned/rss/expanded/decoders/block_parsed_result.rs +++ b/src/oned/rss/expanded/decoders/block_parsed_result.rs @@ -34,6 +34,13 @@ pub struct BlockParsedRXingResult { decodedInformation: Option, finished: bool, } + +impl Default for BlockParsedRXingResult { + fn default() -> Self { + Self::new() + } +} + impl BlockParsedRXingResult { pub fn new() -> Self { Self::with_information(None, false) diff --git a/src/oned/rss/expanded/decoders/current_parsing_state.rs b/src/oned/rss/expanded/decoders/current_parsing_state.rs index 9f0e236..32d8523 100644 --- a/src/oned/rss/expanded/decoders/current_parsing_state.rs +++ b/src/oned/rss/expanded/decoders/current_parsing_state.rs @@ -25,9 +25,9 @@ */ #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum State { - NUMERIC, - ALPHA, - ISO_IEC_646, + Numeric, + Alpha, + IsoIec646, } /** @@ -42,7 +42,7 @@ impl CurrentParsingState { pub fn new() -> Self { Self { position: 0, - encoding: State::NUMERIC, + encoding: State::Numeric, } } @@ -59,26 +59,32 @@ impl CurrentParsingState { } pub fn isAlpha(&self) -> bool { - self.encoding == State::ALPHA + self.encoding == State::Alpha } pub fn isNumeric(&self) -> bool { - self.encoding == State::NUMERIC + self.encoding == State::Numeric } pub fn isIsoIec646(&self) -> bool { - self.encoding == State::ISO_IEC_646 + self.encoding == State::IsoIec646 } pub fn setNumeric(&mut self) { - self.encoding = State::NUMERIC; + self.encoding = State::Numeric; } pub fn setAlpha(&mut self) { - self.encoding = State::ALPHA; + self.encoding = State::Alpha; } pub fn setIsoIec646(&mut self) { - self.encoding = State::ISO_IEC_646; + self.encoding = State::IsoIec646; + } +} + +impl Default for CurrentParsingState { + fn default() -> Self { + Self::new() } } diff --git a/src/oned/rss/expanded/decoders/decoded_numeric.rs b/src/oned/rss/expanded/decoders/decoded_numeric.rs index 291e4fd..ed32120 100644 --- a/src/oned/rss/expanded/decoders/decoded_numeric.rs +++ b/src/oned/rss/expanded/decoders/decoded_numeric.rs @@ -51,9 +51,7 @@ impl DecodedNumeric { if /*firstDigit < 0 ||*/ firstDigit > 10 || /*secondDigit < 0 ||*/ secondDigit > 10 { - return Err(Exceptions::FormatException( - ".getFormatInstance();".to_owned(), - )); + return Err(Exceptions::FormatException(None)); } Ok(Self { diff --git a/src/oned/rss/expanded/decoders/field_parser.rs b/src/oned/rss/expanded/decoders/field_parser.rs index 64d7e60..8e49f71 100644 --- a/src/oned/rss/expanded/decoders/field_parser.rs +++ b/src/oned/rss/expanded/decoders/field_parser.rs @@ -149,7 +149,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result Result Result Result Result { if rawInformation.chars().count() < aiSize { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let ai: String = rawInformation.chars().take(aiSize).collect(); if rawInformation.chars().count() < aiSize + fieldSize { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let field: String = rawInformation @@ -234,16 +234,12 @@ fn processVariableAI( variableFieldSize: usize, rawInformation: &str, ) -> Result { - let ai: String = rawInformation.chars().take(aiSize as usize).collect(); //rawInformation.substring(0, aiSize); + let ai: String = rawInformation.chars().take(aiSize).collect(); //rawInformation.substring(0, aiSize); let maxSize = rawInformation .chars() .count() .min(aiSize + variableFieldSize); - let field: String = rawInformation - .chars() - .skip(aiSize as usize) - .take(maxSize) - .collect(); // (aiSize, maxSize); + let field: String = rawInformation.chars().skip(aiSize).take(maxSize).collect(); // (aiSize, maxSize); let remaining: String = rawInformation.chars().skip(maxSize).collect(); let result = format!("({}){}", ai, field); //'(' + ai + ')' + field; let parsedAI = parseFieldsInGeneralPurpose(&remaining)?; @@ -287,7 +283,7 @@ impl DataLength { mod FieldParserTest { fn checkFields(expected: &str) { - let field = expected.replace("(", "").replace(")", ""); + let field = expected.replace(['(', ')'], ""); let actual = super::parseFieldsInGeneralPurpose(&field).expect("parse"); assert_eq!(expected, actual); } diff --git a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs index b601a93..d491008 100644 --- a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs +++ b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs @@ -122,7 +122,7 @@ impl<'a> GeneralAppIdDecoder<'_> { } pub fn extractNumericValueFromBitArray(&self, pos: usize, bits: u32) -> u32 { - Self::extractNumericValueFromBitArrayWithInformation(&self.information, pos, bits) + Self::extractNumericValueFromBitArrayWithInformation(self.information, pos, bits) } pub fn extractNumericValueFromBitArrayWithInformation( @@ -192,7 +192,7 @@ impl<'a> GeneralAppIdDecoder<'_> { break; } - if !(!isFinished) { + if isFinished { break; } } //while (!isFinished); @@ -200,7 +200,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if result.getDecodedInformation().is_some() { Ok(result.getDecodedInformation().as_ref().unwrap().clone()) } else { - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } } @@ -315,7 +315,7 @@ impl<'a> GeneralAppIdDecoder<'_> { } let fiveBitValue = self.extractNumericValueFromBitArray(pos, 5); - if fiveBitValue >= 5 && fiveBitValue < 16 { + if (5..16).contains(&fiveBitValue) { return true; } @@ -324,7 +324,7 @@ impl<'a> GeneralAppIdDecoder<'_> { } let sevenBitValue = self.extractNumericValueFromBitArray(pos, 7); - if sevenBitValue >= 64 && sevenBitValue < 116 { + if (64..116).contains(&sevenBitValue) { return true; } @@ -334,7 +334,7 @@ impl<'a> GeneralAppIdDecoder<'_> { let eightBitValue = self.extractNumericValueFromBitArray(pos, 8); - eightBitValue >= 232 && eightBitValue < 253 + (232..253).contains(&eightBitValue) } fn decodeIsoIec646(&self, pos: usize) -> Result { @@ -343,7 +343,7 @@ impl<'a> GeneralAppIdDecoder<'_> { return Ok(DecodedChar::new(pos + 5, DecodedChar::FNC1)); } - if fiveBitValue >= 5 && fiveBitValue < 15 { + if (5..15).contains(&fiveBitValue) { return Ok(DecodedChar::new( pos + 5, char::from_u32('0' as u32 + fiveBitValue - 5).unwrap(), @@ -352,14 +352,14 @@ impl<'a> GeneralAppIdDecoder<'_> { let sevenBitValue = self.extractNumericValueFromBitArray(pos, 7); - if sevenBitValue >= 64 && sevenBitValue < 90 { + if (64..90).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, char::from_u32(sevenBitValue + 1).unwrap(), )); } - if sevenBitValue >= 90 && sevenBitValue < 116 { + if (90..116).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, char::from_u32(sevenBitValue + 7).unwrap(), @@ -389,7 +389,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 250 => '?', 251 => '_', 252 => ' ', - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), }; Ok(DecodedChar::new(pos + 8, c)) @@ -402,7 +402,7 @@ impl<'a> GeneralAppIdDecoder<'_> { // We now check if it's a valid 5-bit value (0..9 and FNC1) let fiveBitValue = self.extractNumericValueFromBitArray(pos, 5); - if fiveBitValue >= 5 && fiveBitValue < 16 { + if (5..16).contains(&fiveBitValue) { return true; } @@ -412,7 +412,7 @@ impl<'a> GeneralAppIdDecoder<'_> { let sixBitValue = self.extractNumericValueFromBitArray(pos, 6); - sixBitValue >= 16 && sixBitValue < 63 // 63 not included + (16..63).contains(&sixBitValue) // 63 not included } fn decodeAlphanumeric(&self, pos: usize) -> Result { @@ -421,7 +421,7 @@ impl<'a> GeneralAppIdDecoder<'_> { return Ok(DecodedChar::new(pos + 5, DecodedChar::FNC1)); } - if fiveBitValue >= 5 && fiveBitValue < 15 { + if (5..15).contains(&fiveBitValue) { return Ok(DecodedChar::new( pos + 5, char::from_u32('0' as u32 + fiveBitValue - 5).unwrap(), @@ -430,7 +430,7 @@ impl<'a> GeneralAppIdDecoder<'_> { let sixBitValue = self.extractNumericValueFromBitArray(pos, 6); - if sixBitValue >= 32 && sixBitValue < 58 { + if (32..58).contains(&sixBitValue) { return Ok(DecodedChar::new( pos + 6, char::from_u32(sixBitValue + 33).unwrap(), @@ -444,10 +444,10 @@ impl<'a> GeneralAppIdDecoder<'_> { 61 => '.', 62 => '/', _ => { - return Err(Exceptions::IllegalStateException(format!( + return Err(Exceptions::IllegalStateException(Some(format!( "Decoding invalid alphanumeric value: {}", sixBitValue - ))) + )))) } }; diff --git a/src/oned/rss/expanded/expanded_row.rs b/src/oned/rss/expanded/expanded_row.rs index d38c35f..6388418 100644 --- a/src/oned/rss/expanded/expanded_row.rs +++ b/src/oned/rss/expanded/expanded_row.rs @@ -14,14 +14,14 @@ * limitations under the License. */ -use std::fmt::Display; +use std::{fmt::Display, hash::Hash}; use super::ExpandedPair; /** * One row of an RSS Expanded Stacked symbol, consisting of 1+ expanded pairs. */ -#[derive(Hash, Clone)] +#[derive(Clone)] pub struct ExpandedRow { pairs: Vec, rowNumber: u32, @@ -58,6 +58,12 @@ impl PartialEq for ExpandedRow { } } +impl Hash for ExpandedRow { + fn hash(&self, state: &mut H) { + self.pairs.hash(state); + } +} + impl Display for ExpandedRow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{{ ")?; diff --git a/src/oned/rss/expanded/rss_expanded_image_2_result_test_case.rs b/src/oned/rss/expanded/rss_expanded_image_2_result_test_case.rs index 0273f9f..0092e5d 100644 --- a/src/oned/rss/expanded/rss_expanded_image_2_result_test_case.rs +++ b/src/oned/rss/expanded/rss_expanded_image_2_result_test_case.rs @@ -74,7 +74,7 @@ fn assertCorrectImage2result(fileName: &str, expected: ExpandedProductParsedRXin let mut binaryMap = BinaryBitmap::new(Rc::new(RefCell::new(GlobalHistogramBinarizer::new( Box::new(BufferedImageLuminanceSource::new(image)), )))); - let rowNumber = binaryMap.getHeight() as usize / 2; + let rowNumber = binaryMap.getHeight() / 2; let row = binaryMap.getBlackRow(rowNumber).expect("get row"); let mut rssExpandedReader = RSSExpandedReader::new(); diff --git a/src/oned/rss/expanded/rss_expanded_reader.rs b/src/oned/rss/expanded/rss_expanded_reader.rs index 0379316..306753f 100644 --- a/src/oned/rss/expanded/rss_expanded_reader.rs +++ b/src/oned/rss/expanded/rss_expanded_reader.rs @@ -37,7 +37,7 @@ use crate::{ OneDReader, }, BarcodeFormat, DecodeHintType, DecodingHintDictionary, Exceptions, RXingResult, - RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, ResultPoint, + RXingResultMetadataType, RXingResultMetadataValue, Reader, }; use super::{bit_array_builder, decoders::abstract_expanded_decoder, ExpandedPair, ExpandedRow}; @@ -132,6 +132,7 @@ lazy_static! { * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ +#[derive(Default)] pub struct RSSExpandedReader { _possibleLeftPairs: Vec, _possibleRightPairs: Vec, @@ -225,18 +226,21 @@ impl Reader for RSSExpandedReader { // for point in result.getRXingResultPointsMut().iter_mut() { let total_points = result.getRXingResultPoints().len(); let points = result.getRXingResultPointsMut(); - for i in 0..total_points { + for point in points.iter_mut().take(total_points) { + // for i in 0..total_points { // for (int i = 0; i < points.length; i++) { - points[i] = RXingResultPoint::new( - height as f32 - points[i].getY() - 1.0, - points[i].getX(), - ); + std::mem::swap(&mut point.x, &mut point.y); + point.x = height as f32 - point.x - 1.0; + // points[i] = RXingResultPoint::new( + // height as f32 - points[i].getY() - 1.0, + // points[i].getX(), + // ); } // } Ok(result) } else { - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } } @@ -335,16 +339,16 @@ impl RSSExpandedReader { // When the image is 180-rotated, then rows are sorted in wrong direction. // Try twice with both the directions. let ps = self.checkRows(false); - if ps.is_some() { - return Ok(ps.unwrap()); + if let Some(ps) = ps { + return Ok(ps); } let ps = self.checkRows(true); - if ps.is_some() { - return Ok(ps.unwrap()); + if let Some(ps) = ps { + return Ok(ps); } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn checkRows(&mut self, reverse: bool) -> Option> { @@ -415,7 +419,7 @@ impl RSSExpandedReader { } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } // Whether the pairs form a valid find pattern sequence, @@ -427,7 +431,7 @@ impl RSSExpandedReader { // for (int[] sequence : FINDER_PATTERN_SEQUENCES) { if pairs.len() <= sequence.len() { let mut stop = true; - for j in 0..pairs.len() { + for (j, seq) in sequence.iter().enumerate().take(pairs.len()) { // for (int j = 0; j < pairs.size(); j++) { if pairs .get(j) @@ -436,7 +440,7 @@ impl RSSExpandedReader { .as_ref() .unwrap() .getValue() - != sequence[j] + != *seq { stop = false; break; @@ -448,7 +452,7 @@ impl RSSExpandedReader { } } - return false; + false } fn storeRow(&mut self, rowNumber: u32) { @@ -535,7 +539,7 @@ impl RSSExpandedReader { return true; } } - return false; + false } // Only used for unit testing @@ -564,7 +568,7 @@ impl RSSExpandedReader { .unwrap() .getRXingResultPoints(); let lastPoints = pairs - .get(pairs.len() - 1) + .last() .unwrap() .getFinderPattern() .as_ref() @@ -663,13 +667,8 @@ impl RSSExpandedReader { let leftChar = self.decodeDataCharacter(row, pattern.as_ref().unwrap(), isOddPattern, true)?; - if !previousPairs.is_empty() - && previousPairs - .get(previousPairs.len() - 1) - .unwrap() - .mustBeLast() - { - return Err(Exceptions::NotFoundException("".to_owned())); + if !previousPairs.is_empty() && previousPairs.last().unwrap().mustBeLast() { + return Err(Exceptions::NotFoundException(None)); } let rightChar = if let Ok(ch) = @@ -708,7 +707,7 @@ impl RSSExpandedReader { } else if previousPairs.is_empty() { rowOffset = 0; } else { - let lastPair = previousPairs.get(previousPairs.len() - 1).unwrap(); + let lastPair = previousPairs.last().unwrap(); rowOffset = lastPair.getFinderPattern().as_ref().unwrap().getStartEnd()[1] as i32; } let mut searchingEvenPair = previousPairs.len() % 2 != 0; @@ -760,16 +759,14 @@ impl RSSExpandedReader { isWhite = !isWhite; } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn reverseCounters(counters: &mut [u32]) { let length = counters.len(); for i in 0..length / 2 { // for (int i = 0; i < length / 2; ++i) { - let tmp = counters[i]; - counters[i] = counters[length - i - 1]; - counters[length - i - 1] = tmp; + counters.swap(i, length - i - 1); } } @@ -861,7 +858,7 @@ impl RSSExpandedReader { let expectedElementWidth: f32 = (pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) as f32 / 15.0; if (elementWidth - expectedElementWidth).abs() / expectedElementWidth > 0.3 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // let oddCounts = &mut self.oddCounts; @@ -869,18 +866,18 @@ impl RSSExpandedReader { // let oddRoundingErrors = &mut self.oddRoundingErrors; // let evenRoundingErrors = &mut self.evenRoundingErrors; - for i in 0..counters.len() { + for (i, counter) in counters.iter().enumerate() { // for (int i = 0; i < counters.length; i++) { - let value: f32 = 1.0 * counters[i] as f32 / elementWidth; + let value: f32 = 1.0 * (*counter as f32) / elementWidth; let mut count = (value + 0.5) as i32; // Round if count < 1 { if value < 0.3 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } count = 1; } else if count > 8 { if value > 8.7 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } count = 8; } @@ -898,7 +895,7 @@ impl RSSExpandedReader { let weightRowNumber = (4 * pattern.getValue() as isize + (if isOddPattern { 0 } else { 2 }) - + (if leftChar { 0 } else { 1 }) + + isize::from(!leftChar)//(if leftChar { 0 } else { 1 }) - 1) as usize; let mut oddSum = 0; @@ -921,8 +918,8 @@ impl RSSExpandedReader { } let checksumPortion = oddChecksumPortion + evenChecksumPortion; - if (oddSum & 0x01) != 0 || oddSum > 13 || oddSum < 4 { - return Err(Exceptions::NotFoundException("".to_owned())); + if (oddSum & 0x01) != 0 || !(4..=13).contains(&oddSum) { + return Err(Exceptions::NotFoundException(None)); } let group = ((13 - oddSum) / 2) as usize; @@ -971,12 +968,12 @@ impl RSSExpandedReader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decrementEven = true; } @@ -984,12 +981,12 @@ impl RSSExpandedReader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } incrementEven = true; } @@ -997,7 +994,7 @@ impl RSSExpandedReader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // Both bad if oddSum < evenSum { @@ -1007,20 +1004,17 @@ impl RSSExpandedReader { decrementOdd = true; incrementEven = true; } - } else { - if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); - } - // Nothing to do! + } else if evenParityBad { + return Err(Exceptions::NotFoundException(None)); } } - _ => return Err(Exceptions::NotFoundException("".to_owned())), + _ => return Err(Exceptions::NotFoundException(None)), } if incrementOdd { if decrementOdd { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -1029,7 +1023,7 @@ impl RSSExpandedReader { } if incrementEven { if decrementEven { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Self::increment(&mut self.evenCounts, &self.oddRoundingErrors); } @@ -1040,22 +1034,3 @@ impl RSSExpandedReader { Ok(()) } } - -impl Default for RSSExpandedReader { - fn default() -> Self { - Self { - _possibleLeftPairs: Default::default(), - _possibleRightPairs: Default::default(), - decodeFinderCounters: Default::default(), - dataCharacterCounters: Default::default(), - oddRoundingErrors: Default::default(), - evenRoundingErrors: Default::default(), - oddCounts: Default::default(), - evenCounts: Default::default(), - pairs: Default::default(), - rows: Default::default(), - startEnd: Default::default(), - startFromEven: Default::default(), - } - } -} diff --git a/src/oned/rss/expanded/test_case_util.rs b/src/oned/rss/expanded/test_case_util.rs index ad5a830..fcf617f 100644 --- a/src/oned/rss/expanded/test_case_util.rs +++ b/src/oned/rss/expanded/test_case_util.rs @@ -33,16 +33,13 @@ use crate::{common::GlobalHistogramBinarizer, BinaryBitmap, BufferedImageLuminan fn getBufferedImage(fileName: &str) -> DynamicImage { let path = format!("test_resources/blackbox/rssexpandedstacked-2/{}", fileName); - let image = image::open(path).expect("load image"); - - image + image::open(path).expect("load image") } pub(crate) fn getBinaryBitmap(fileName: &str) -> BinaryBitmap { let bufferedImage = getBufferedImage(fileName); - let binaryMap = BinaryBitmap::new(Rc::new(RefCell::new(GlobalHistogramBinarizer::new( - Box::new(BufferedImageLuminanceSource::new(bufferedImage)), - )))); - binaryMap + BinaryBitmap::new(Rc::new(RefCell::new(GlobalHistogramBinarizer::new( + Box::new(BufferedImageLuminanceSource::new(bufferedImage)), + )))) } diff --git a/src/oned/rss/rss_14_reader.rs b/src/oned/rss/rss_14_reader.rs index e179bd1..b55a492 100644 --- a/src/oned/rss/rss_14_reader.rs +++ b/src/oned/rss/rss_14_reader.rs @@ -20,7 +20,7 @@ use crate::{ common::BitArray, oned::{one_d_reader, OneDReader}, BarcodeFormat, DecodeHintType, DecodingHintDictionary, Exceptions, RXingResult, - RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, ResultPoint, + RXingResultMetadataType, RXingResultMetadataValue, Reader, }; use super::{ @@ -63,13 +63,13 @@ impl OneDReader for RSS14Reader { if left.getCount() > 1 { for right in &self.possibleRightPairs { // for (Pair right : possibleRightPairs) { - if right.getCount() > 1 && self.checkChecksum(&left, &right) { - return Ok(self.constructRXingResult(&left, &right)); + if right.getCount() > 1 && self.checkChecksum(left, right) { + return Ok(self.constructRXingResult(left, right)); } } } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } impl Reader for RSS14Reader { @@ -119,18 +119,21 @@ impl Reader for RSS14Reader { // for point in result.getRXingResultPointsMut().iter_mut() { let total_points = result.getRXingResultPoints().len(); let points = result.getRXingResultPointsMut(); - for i in 0..total_points { + // for i in 0..total_points { + for point in points.iter_mut().take(total_points) { // for (int i = 0; i < points.length; i++) { - points[i] = RXingResultPoint::new( - height as f32 - points[i].getY() - 1.0, - points[i].getX(), - ); + std::mem::swap(&mut point.x, &mut point.y); + point.x = height as f32 - point.x - 1.0 + // points[i] = RXingResultPoint::new( + // height as f32 - points[i].getY() - 1.0, + // points[i].getX(), + // ); } // } Ok(result) } else { - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } } @@ -284,10 +287,10 @@ impl RSS14Reader { pattern, )) }(); - if pos_pair.is_err() { - None + if let Ok(ppair) = pos_pair { + Some(ppair) } else { - Some(pos_pair.unwrap()) + None } } @@ -328,15 +331,16 @@ impl RSS14Reader { // let oddRoundingErrors = //&mut self.oddRoundingErrors;//[0f32; 4]; // self.getOddRoundingErrors(); // let evenRoundingErrors = &mut self.evenRoundingErrors;//[0f32; 4]; // self.getEvenRoundingErrors(); - for i in 0..counters.len() { + for (i, counter) in counters.iter().enumerate() { // for (int i = 0; i < counters.length; i++) { - let value: f32 = counters[i] as f32 / elementWidth; - let mut count = (value + 0.5) as u32; // Round - if count < 1 { - count = 1; - } else if count > 8 { - count = 8; - } + let value: f32 = *counter as f32 / elementWidth; + // let mut count = (value + 0.5) as u32; // Round + let count = ((value + 0.5) as u32).clamp(1, 8); + // if count < 1 { + // count = 1; + // } else if count > 8 { + // count = 8; + // } let offset = i / 2; if (i & 0x01) == 0 { self.oddCounts[offset] = count; @@ -368,8 +372,8 @@ impl RSS14Reader { let checksumPortion = oddChecksumPortion + 3 * evenChecksumPortion; if outsideChar { - if (oddSum & 0x01) != 0 || oddSum > 12 || oddSum < 4 { - return Err(Exceptions::NotFoundException("".to_owned())); + if (oddSum & 0x01) != 0 || !(4..=12).contains(&oddSum) { + return Err(Exceptions::NotFoundException(None)); } let group = ((12 - oddSum) / 2) as usize; let oddWidest = Self::OUTSIDE_ODD_WIDEST[group]; @@ -378,13 +382,13 @@ impl RSS14Reader { let vEven = rss_utils::getRSSvalue(&self.evenCounts, evenWidest, true); let tEven = Self::OUTSIDE_EVEN_TOTAL_SUBSET[group]; let gSum = Self::OUTSIDE_GSUM[group]; - return Ok(DataCharacter::new( + Ok(DataCharacter::new( vOdd * tEven + vEven + gSum, checksumPortion, - )); + )) } else { - if (evenSum & 0x01) != 0 || evenSum > 10 || evenSum < 4 { - return Err(Exceptions::NotFoundException("".to_owned())); + if (evenSum & 0x01) != 0 || !(4..=10).contains(&evenSum) { + return Err(Exceptions::NotFoundException(None)); } let group = ((10 - evenSum) / 2) as usize; let oddWidest = Self::INSIDE_ODD_WIDEST[group]; @@ -393,10 +397,10 @@ impl RSS14Reader { let vEven = rss_utils::getRSSvalue(&self.evenCounts, evenWidest, false); let tOdd = Self::INSIDE_ODD_TOTAL_SUBSET[group]; let gSum = Self::INSIDE_GSUM[group]; - return Ok(DataCharacter::new( + Ok(DataCharacter::new( vEven * tOdd + vOdd + gSum, checksumPortion, - )); + )) } } @@ -449,7 +453,7 @@ impl RSS14Reader { isWhite = !isWhite; } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } fn parseFoundFinderPattern( @@ -534,7 +538,7 @@ impl RSS14Reader { } let mismatch = oddSum as i32 + evenSum as i32 - numModules as i32; - let oddParityBad = (oddSum & 0x01) == (if outsideChar { 1 } else { 0 }); + let oddParityBad = (oddSum & 0x01) == u32::from(outsideChar); //(if outsideChar { 1 } else { 0 }); let evenParityBad = (evenSum & 0x01) == 1; /*if (mismatch == 2) { if (!(oddParityBad && evenParityBad)) { @@ -553,12 +557,12 @@ impl RSS14Reader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } decrementEven = true; } @@ -566,12 +570,12 @@ impl RSS14Reader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } incrementEven = true; } @@ -579,7 +583,7 @@ impl RSS14Reader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // Both bad if oddSum < evenSum { @@ -589,19 +593,16 @@ impl RSS14Reader { decrementOdd = true; incrementEven = true; } - } else { - if evenParityBad { - return Err(Exceptions::NotFoundException("".to_owned())); - } - // Nothing to do! + } else if evenParityBad { + return Err(Exceptions::NotFoundException(None)); } } - _ => return Err(Exceptions::NotFoundException("".to_owned())), + _ => return Err(Exceptions::NotFoundException(None)), } if incrementOdd { if decrementOdd { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -610,7 +611,7 @@ impl RSS14Reader { } if incrementEven { if decrementEven { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Self::increment(&mut self.evenCounts, &self.evenRoundingErrors); } diff --git a/src/oned/rss/rss_utils.rs b/src/oned/rss/rss_utils.rs index f271e36..75c5ec6 100644 --- a/src/oned/rss/rss_utils.rs +++ b/src/oned/rss/rss_utils.rs @@ -64,13 +64,15 @@ pub fn getRSSvalue(widths: &[u32], maxWidth: u32, noNarrow: bool) -> u32 { } n -= elmWidth; } - return val; + val } fn combins(n: u32, r: u32) -> u32 { let maxDenom; let minDenom; - if n - r > r { + + // if n - r > r { + if n.checked_sub(r).is_none() { minDenom = r; maxDenom = n - r; } else { diff --git a/src/oned/upc_a_reader.rs b/src/oned/upc_a_reader.rs index 49a9b26..178eee6 100644 --- a/src/oned/upc_a_reader.rs +++ b/src/oned/upc_a_reader.rs @@ -24,6 +24,7 @@ use super::{EAN13Reader, OneDReader, UPCEANReader}; * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ +#[derive(Default)] pub struct UPCAReader(EAN13Reader); impl Reader for UPCAReader { @@ -87,20 +88,15 @@ impl UPCEANReader for UPCAReader { } } -impl Default for UPCAReader { - fn default() -> Self { - Self(Default::default()) - } -} - impl UPCAReader { // private final UPCEANReader ean13Reader = new EAN13Reader(); fn maybeReturnRXingResult(result: RXingResult) -> Result { let text = result.getText(); - if text.chars().nth(0).unwrap() == '0' { + if let Some(stripped_text) = text.strip_prefix('0') { + // if text.starts_with('0') { let mut upcaRXingResult = RXingResult::new( - &text[1..], + stripped_text, Vec::new(), result.getRXingResultPoints().to_vec(), BarcodeFormat::UPC_A, @@ -110,7 +106,7 @@ impl UPCAReader { // } Ok(upcaRXingResult) } else { - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } } } diff --git a/src/oned/upc_a_writer.rs b/src/oned/upc_a_writer.rs index 3e50764..0efa359 100644 --- a/src/oned/upc_a_writer.rs +++ b/src/oned/upc_a_writer.rs @@ -25,14 +25,9 @@ use super::EAN13Writer; * * @author qwandor@google.com (Andrew Walbran) */ +#[derive(Default)] pub struct UPCAWriter(EAN13Writer); -impl Default for UPCAWriter { - fn default() -> Self { - Self(Default::default()) - } -} - impl Writer for UPCAWriter { fn encode( &self, @@ -53,10 +48,10 @@ impl Writer for UPCAWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::UPC_A { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode UPC-A, but got {:?}", format - ))); + )))); } // Transform a UPC-A code into the equivalent EAN-13 code and write it that way self.0.encode_with_hints( @@ -64,7 +59,7 @@ impl Writer for UPCAWriter { &BarcodeFormat::EAN_13, width, height, - &hints, + hints, ) } } diff --git a/src/oned/upc_e_reader.rs b/src/oned/upc_e_reader.rs index f311700..8480cf1 100644 --- a/src/oned/upc_e_reader.rs +++ b/src/oned/upc_e_reader.rs @@ -25,7 +25,7 @@ use rxing_one_d_proc_derive::{EANReader, OneDReader}; * * @author Sean Owen */ -#[derive(OneDReader, EANReader)] +#[derive(OneDReader, EANReader, Default)] pub struct UPCEReader; impl UPCEANReader for UPCEReader { @@ -84,12 +84,6 @@ impl UPCEANReader for UPCEReader { } } -impl Default for UPCEReader { - fn default() -> Self { - Self {} - } -} - impl UPCEReader { /** * The pattern that marks the middle, and end, of a UPC-E pattern. @@ -146,7 +140,7 @@ impl UPCEReader { } } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } } @@ -160,7 +154,7 @@ pub fn convertUPCEtoUPCA(upce: &str) -> String { let upceChars = &upce[1..7]; //['0';6];//new char[6]; //upce.getChars(1, 7, upceChars, 0); let mut result = String::with_capacity(12); //new StringBuilder(12); - result.push(upce.chars().nth(0).unwrap()); + result.push(upce.chars().next().unwrap()); let lastChar = upceChars.chars().nth(5).unwrap(); match lastChar { '0' | '1' | '2' => { diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index a19f69a..0bb677f 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -31,15 +31,11 @@ const CODE_WIDTH: usize = 3 + // start guard * * @author 0979097955s@gmail.com (RX) */ -#[derive(OneDWriter)] +#[derive(OneDWriter, Default)] pub struct UPCEWriter; impl UPCEANWriter for UPCEWriter {} -impl Default for UPCEWriter { - fn default() -> Self { - Self {} - } -} + impl OneDimensionalCodeWriter for UPCEWriter { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { let length = contents.chars().count(); @@ -63,29 +59,29 @@ impl OneDimensionalCodeWriter for UPCEWriter { if !reader .checkStandardUPCEANChecksum(&upc_e_reader::convertUPCEtoUPCA(&contents))? { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Contents do not pass checksum".to_owned(), - )); + ))); } } // } catch (FormatException ignored) { // throw new IllegalArgumentException("Illegal contents"); // }}, _ => { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Requested contents should be 7 or 8 digits long, but got {}", length - ))) + )))) } } Self::checkNumeric(&contents)?; - let firstDigit = contents.chars().nth(0).unwrap().to_digit(10).unwrap() as usize; //Character.digit(contents.charAt(0), 10); + let firstDigit = contents.chars().next().unwrap().to_digit(10).unwrap() as usize; //Character.digit(contents.charAt(0), 10); if firstDigit != 0 && firstDigit != 1 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Number system must be 0 or 1".to_owned(), - )); + ))); } let checkDigit = contents.chars().nth(7).unwrap().to_digit(10).unwrap() as usize; //Character.digit(contents.charAt(7), 10); @@ -109,7 +105,7 @@ impl OneDimensionalCodeWriter for UPCEWriter { ) as usize; } - Self::appendPattern(&mut result, pos, &upc_ean_reader::END_PATTERN, false) as usize; + Self::appendPattern(&mut result, pos, &upc_ean_reader::END_PATTERN, false); Ok(result.to_vec()) } diff --git a/src/oned/upc_ean_extension_2_support.rs b/src/oned/upc_ean_extension_2_support.rs index 9efab6e..89bc44f 100644 --- a/src/oned/upc_ean_extension_2_support.rs +++ b/src/oned/upc_ean_extension_2_support.rs @@ -26,16 +26,10 @@ use super::{upc_ean_reader, UPCEANReader, STAND_IN}; /** * @see UPCEANExtension5Support */ +#[derive(Default)] pub struct UPCEANExtension2Support { decodeMiddleCounters: [u32; 4], } -impl Default for UPCEANExtension2Support { - fn default() -> Self { - Self { - decodeMiddleCounters: Default::default(), - } - } -} impl UPCEANExtension2Support { pub fn decodeRow( @@ -114,12 +108,12 @@ impl UPCEANExtension2Support { } if resultString.chars().count() != 2 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } if resultString.parse::().unwrap() % 4 != checkParity { // if (Integer.parseInt(resultString.toString()) % 4 != checkParity) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(rowOffset as u32) diff --git a/src/oned/upc_ean_extension_5_support.rs b/src/oned/upc_ean_extension_5_support.rs index 1c13b48..e604c51 100644 --- a/src/oned/upc_ean_extension_5_support.rs +++ b/src/oned/upc_ean_extension_5_support.rs @@ -26,17 +26,12 @@ use super::{upc_ean_reader, UPCEANReader, STAND_IN}; /** * @see UPCEANExtension2Support */ +#[derive(Default)] pub struct UPCEANExtension5Support { //decodeMiddleCounters : [u32;4], // decodeRowStringBuffer : String, } -impl Default for UPCEANExtension5Support { - fn default() -> Self { - Self {} - } -} - impl UPCEANExtension5Support { const CHECK_DIGIT_ENCODINGS: [usize; 10] = [0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05]; @@ -83,7 +78,7 @@ impl UPCEANExtension5Support { // counters[2] = 0; // counters[3] = 0; let end = row.getSize(); - let mut rowOffset = startRange[1] as usize; + let mut rowOffset = startRange[1]; let mut lgPatternFound = 0; @@ -115,12 +110,12 @@ impl UPCEANExtension5Support { } if resultString.chars().count() != 5 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let checkDigit = Self::determineCheckDigit(lgPatternFound)?; if Self::extensionChecksum(resultString) != checkDigit as u32 { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(rowOffset as u32) @@ -146,7 +141,7 @@ impl UPCEANExtension5Support { i -= 2; } sum *= 3; - return sum % 10; + sum % 10 } fn determineCheckDigit(lgPatternFound: usize) -> Result { @@ -156,7 +151,7 @@ impl UPCEANExtension5Support { return Ok(d); } } - return Err(Exceptions::NotFoundException("".to_owned())); + Err(Exceptions::NotFoundException(None)) } /** @@ -184,7 +179,7 @@ impl UPCEANExtension5Support { } fn parseExtension5String(raw: &str) -> Option { - let currency = match raw.chars().nth(0).unwrap() { + let currency = match raw.chars().next().unwrap() { '0' => "£", '5' => "$", '9' => { diff --git a/src/oned/upc_ean_extension_support.rs b/src/oned/upc_ean_extension_support.rs index d32a9ff..a98f39e 100644 --- a/src/oned/upc_ean_extension_support.rs +++ b/src/oned/upc_ean_extension_support.rs @@ -18,19 +18,12 @@ use crate::{common::BitArray, Exceptions, RXingResult}; use super::{UPCEANExtension2Support, UPCEANExtension5Support, UPCEANReader, STAND_IN}; +#[derive(Default)] pub struct UPCEANExtensionSupport { twoSupport: UPCEANExtension2Support, fiveSupport: UPCEANExtension5Support, } -impl Default for UPCEANExtensionSupport { - fn default() -> Self { - Self { - twoSupport: Default::default(), - fiveSupport: Default::default(), - } - } -} impl UPCEANExtensionSupport { const EXTENSION_START_PATTERN: [u32; 3] = [1, 1, 2]; diff --git a/src/oned/upc_ean_reader.rs b/src/oned/upc_ean_reader.rs index 425b516..478f5ab 100644 --- a/src/oned/upc_ean_reader.rs +++ b/src/oned/upc_ean_reader.rs @@ -203,16 +203,16 @@ pub trait UPCEANReader: OneDReader { let end = endRange[1]; let quietEnd = end + (end - endRange[0]); if quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)? { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let resultString = result; // UPC/EAN should never be less than 8 chars anyway if resultString.chars().count() < 8 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } if !self.checkChecksum(&resultString)? { - return Err(Exceptions::ChecksumException("".to_owned())); + return Err(Exceptions::ChecksumException(None)); } let left = (startGuardRange[1] + startGuardRange[0]) as f32 / 2.0; @@ -273,7 +273,7 @@ pub trait UPCEANReader: OneDReader { } } if !valid { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } } // let allowedExtensions = @@ -287,7 +287,7 @@ pub trait UPCEANReader: OneDReader { // } // } // if (!valid) { - // return Err(Exceptions::NotFoundException("".to_owned())); + // return Err(Exceptions::NotFoundException(None)); // } // } @@ -335,7 +335,7 @@ pub trait UPCEANReader: OneDReader { return Ok(false); } let char_in_question = s.chars().nth(length - 1).unwrap(); - let check = char_in_question.is_digit(10); + let check = char_in_question.is_ascii_digit(); // let check = Character.digit(s.charAt(length - 1), 10); let check_against = &s[..length - 1]; //s.subSequence(0, length - 1); @@ -356,8 +356,8 @@ pub trait UPCEANReader: OneDReader { while i >= 0 { // for (int i = length - 1; i >= 0; i -= 2) { let digit = (s.chars().nth(i as usize).unwrap() as i32) - ('0' as i32); - if digit < 0 || digit > 9 { - return Err(Exceptions::FormatException("".to_owned())); + if !(0..=9).contains(&digit) { + return Err(Exceptions::FormatException(None)); } sum += digit; @@ -368,8 +368,8 @@ pub trait UPCEANReader: OneDReader { while i >= 0 { // for (int i = length - 2; i >= 0; i -= 2) { let digit = (s.chars().nth(i as usize).unwrap() as i32) - ('0' as i32); - if digit < 0 || digit > 9 { - return Err(Exceptions::FormatException("".to_owned())); + if !(0..=9).contains(&digit) { + return Err(Exceptions::FormatException(None)); } sum += digit; @@ -456,7 +456,7 @@ pub trait UPCEANReader: OneDReader { } } - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } /** @@ -482,9 +482,8 @@ pub trait UPCEANReader: OneDReader { let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestMatch = -1_isize; let max = patterns.len(); - for i in 0..max { + for (i, pattern) in patterns.iter().enumerate().take(max) { // for (int i = 0; i < max; i++) { - let pattern = &patterns[i]; let variance: f32 = one_d_reader::patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if variance < bestVariance { @@ -495,7 +494,7 @@ pub trait UPCEANReader: OneDReader { if bestMatch >= 0 { Ok(bestMatch as usize) } else { - Err(Exceptions::NotFoundException("".to_owned())) + Err(Exceptions::NotFoundException(None)) } } diff --git a/src/pdf417/decoder/barcode_value.rs b/src/pdf417/decoder/barcode_value.rs index b1724d3..ea63138 100644 --- a/src/pdf417/decoder/barcode_value.rs +++ b/src/pdf417/decoder/barcode_value.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; /** * @author Guenther Grau */ -#[derive(Clone)] +#[derive(Clone, Default)] pub struct BarcodeValue(HashMap); // private final Map values = new HashMap<>(); @@ -70,9 +70,3 @@ impl BarcodeValue { } } } - -impl Default for BarcodeValue { - fn default() -> Self { - Self(Default::default()) - } -} diff --git a/src/pdf417/decoder/bounding_box.rs b/src/pdf417/decoder/bounding_box.rs index 9ce71ba..0f974ac 100644 --- a/src/pdf417/decoder/bounding_box.rs +++ b/src/pdf417/decoder/bounding_box.rs @@ -44,7 +44,7 @@ impl BoundingBox { let leftUnspecified = topLeft.is_none() || bottomLeft.is_none(); let rightUnspecified = topRight.is_none() || bottomRight.is_none(); if leftUnspecified && rightUnspecified { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } let newTopLeft; diff --git a/src/pdf417/decoder/decoded_bit_stream_parser.rs b/src/pdf417/decoder/decoded_bit_stream_parser.rs index 35b929f..b64518d 100644 --- a/src/pdf417/decoder/decoded_bit_stream_parser.rs +++ b/src/pdf417/decoder/decoded_bit_stream_parser.rs @@ -33,12 +33,12 @@ use crate::{ #[derive(Clone, Copy, PartialEq, Eq)] enum Mode { - ALPHA, - LOWER, - MIXED, - PUNCT, - ALPHA_SHIFT, - PUNCT_SHIFT, + Alpha, + Lower, + Mixed, + Punct, + AlphaShift, + PunctShift, } const TEXT_COMPACTION_MODE_LATCH: u32 = 900; @@ -131,7 +131,7 @@ const NUMBER_OF_SEQUENCE_CODEWORDS: usize = 2; pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { let mut result = ECIStringBuilder::with_capacity(codewords.len() * 2); - let mut codeIndex = textCompaction(codewords, 1, &mut result)? as usize; + let mut codeIndex = textCompaction(codewords, 1, &mut result)?; let mut resultMetadata = PDF417RXingResultMetadata::default(); while codeIndex < codewords[0] as usize { let code = codewords[codeIndex]; @@ -170,7 +170,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result // Should not see these outside a macro block { - return Err(Exceptions::FormatException("".to_owned())) + return Err(Exceptions::FormatException(None)) } _ => { // Default to text compaction. During testing numerous barcodes @@ -185,7 +185,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result codewords[0] as usize { // we must have at least two bytes left for the segment index - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS]; - for i in 0..NUMBER_OF_SEQUENCE_CODEWORDS { + for seq in segmentIndexArray + .iter_mut() + .take(NUMBER_OF_SEQUENCE_CODEWORDS) + { // for (int i = 0; i < NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) { - segmentIndexArray[i] = codewords[codeIndex]; + *seq = codewords[codeIndex]; codeIndex += 1; } let segmentIndexString = decodeBase900toBase10(&segmentIndexArray, NUMBER_OF_SEQUENCE_CODEWORDS)?; if segmentIndexString.is_empty() { resultMetadata.setSegmentIndex(0); + } else if let Ok(parsed_int) = segmentIndexString.parse::() { + resultMetadata.setSegmentIndex(parsed_int); } else { - if let Ok(parsed_int) = segmentIndexString.parse::() { - resultMetadata.setSegmentIndex(parsed_int); - } else { - // too large; bad input? - return Err(Exceptions::FormatException("".to_owned())); - } + // too large; bad input? + return Err(Exceptions::FormatException(None)); } // Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec @@ -242,7 +243,7 @@ pub fn decodeMacroBlock( } if fileId.chars().count() == 0 { // at least one fileId codeword is required (Annex H.2) - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } resultMetadata.setFileId(fileId); @@ -298,14 +299,14 @@ pub fn decodeMacroBlock( fileSize = fileSize.build_result(); resultMetadata.setFileSize(fileSize.to_string().parse().unwrap()); } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } MACRO_PDF417_TERMINATOR => { codeIndex += 1; resultMetadata.setLastSegment(true); } - _ => return Err(Exceptions::FormatException("".to_owned())), + _ => return Err(Exceptions::FormatException(None)), } } @@ -345,13 +346,13 @@ fn textCompaction( ) -> Result { let mut codeIndex = codeIndex; // 2 character per codeword - let mut textCompactionData = vec![0; (codewords[0] as usize - codeIndex) as usize * 2]; + let mut textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; // Used to hold the byte compaction value if there is a mode shift - let mut byteCompactionData = vec![0; (codewords[0] as usize - codeIndex) as usize * 2]; + let mut byteCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; let mut index = 0; let mut end = false; - let mut subMode = Mode::ALPHA; + let mut subMode = Mode::Alpha; while (codeIndex < codewords[0] as usize) && !end { let mut code = codewords[codeIndex]; codeIndex += 1; @@ -454,7 +455,7 @@ fn decodeTextCompaction( let subModeCh = textCompactionData[i]; let mut ch = 0 as char; match subMode { - Mode::ALPHA => + Mode::Alpha => // Alpha (uppercase alphabetic) { if subModeCh < 26 { @@ -464,23 +465,23 @@ fn decodeTextCompaction( match subModeCh { 26 => ch = ' ', LL => { - subMode = Mode::LOWER; + subMode = Mode::Lower; latchedMode = subMode; } ML => { - subMode = Mode::MIXED; + subMode = Mode::Mixed; latchedMode = subMode; } PS => { // Shift to punctuation priorToShiftMode = subMode; - subMode = Mode::PUNCT_SHIFT; + subMode = Mode::PunctShift; } MODE_SHIFT_TO_BYTE_COMPACTION_MODE => { result.append_char(char::from_u32(byteCompactionData[i]).unwrap()) } TEXT_COMPACTION_MODE_LATCH => { - subMode = Mode::ALPHA; + subMode = Mode::Alpha; latchedMode = subMode; } _ => {} @@ -488,7 +489,7 @@ fn decodeTextCompaction( } } - Mode::LOWER => + Mode::Lower => // Lower (lowercase alphabetic) { if subModeCh < 26 { @@ -499,22 +500,22 @@ fn decodeTextCompaction( AS => { // Shift to alpha priorToShiftMode = subMode; - subMode = Mode::ALPHA_SHIFT; + subMode = Mode::AlphaShift; } ML => { - subMode = Mode::MIXED; + subMode = Mode::Mixed; latchedMode = subMode; } PS => { // Shift to punctuation priorToShiftMode = subMode; - subMode = Mode::PUNCT_SHIFT; + subMode = Mode::PunctShift; } MODE_SHIFT_TO_BYTE_COMPACTION_MODE => { result.append_char(char::from_u32(byteCompactionData[i]).unwrap()) } TEXT_COMPACTION_MODE_LATCH => { - subMode = Mode::ALPHA; + subMode = Mode::Alpha; latchedMode = subMode; } _ => {} @@ -522,7 +523,7 @@ fn decodeTextCompaction( } } - Mode::MIXED => + Mode::Mixed => // Mixed (numeric and some punctuation) { if subModeCh < PL { @@ -530,22 +531,22 @@ fn decodeTextCompaction( } else { match subModeCh { PL => { - subMode = Mode::PUNCT; + subMode = Mode::Punct; latchedMode = subMode; } 26 => ch = ' ', LL => { - subMode = Mode::LOWER; + subMode = Mode::Lower; latchedMode = subMode; } AL | TEXT_COMPACTION_MODE_LATCH => { - subMode = Mode::ALPHA; + subMode = Mode::Alpha; latchedMode = subMode; } PS => { // Shift to punctuation priorToShiftMode = subMode; - subMode = Mode::PUNCT_SHIFT; + subMode = Mode::PunctShift; } MODE_SHIFT_TO_BYTE_COMPACTION_MODE => { result.append_char(char::from_u32(byteCompactionData[i]).unwrap()) @@ -555,7 +556,7 @@ fn decodeTextCompaction( } } - Mode::PUNCT => + Mode::Punct => // Punctuation { if subModeCh < PAL { @@ -563,7 +564,7 @@ fn decodeTextCompaction( } else { match subModeCh { PAL | TEXT_COMPACTION_MODE_LATCH => { - subMode = Mode::ALPHA; + subMode = Mode::Alpha; latchedMode = subMode; } MODE_SHIFT_TO_BYTE_COMPACTION_MODE => { @@ -574,7 +575,7 @@ fn decodeTextCompaction( } } - Mode::ALPHA_SHIFT => { + Mode::AlphaShift => { // Restore sub-mode subMode = priorToShiftMode; if subModeCh < 26 { @@ -582,20 +583,20 @@ fn decodeTextCompaction( } else { match subModeCh { 26 => ch = ' ', - TEXT_COMPACTION_MODE_LATCH => subMode = Mode::ALPHA, + TEXT_COMPACTION_MODE_LATCH => subMode = Mode::Alpha, _ => {} } } } - Mode::PUNCT_SHIFT => { + Mode::PunctShift => { // Restore sub-mode subMode = priorToShiftMode; if subModeCh < PAL { ch = PUNCT_CHARS[subModeCh as usize]; } else { match subModeCh { - PAL | TEXT_COMPACTION_MODE_LATCH => subMode = Mode::ALPHA, + PAL | TEXT_COMPACTION_MODE_LATCH => subMode = Mode::Alpha, MODE_SHIFT_TO_BYTE_COMPACTION_MODE => // PS before Shift-to-Byte is used as a padding character, // see 5.4.2.4 of the specification @@ -613,7 +614,7 @@ fn decodeTextCompaction( } i += 1; } - return latchedMode; + latchedMode } /** @@ -802,8 +803,8 @@ fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result u32 { @@ -153,7 +153,7 @@ impl DetectionRXingResult { fn adjustRowNumbersFromBothRI(&mut self) { if self.detectionRXingResultColumns[0].is_none() - && self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1].is_none() + && self.detectionRXingResultColumns[self.barcodeColumnCount + 1].is_none() { return; } @@ -167,89 +167,85 @@ impl DetectionRXingResult { .len() { // for (int codewordsRow = 0; codewordsRow < LRIcodewords.length; codewordsRow++) { - if - //let (Some(lricw), Some(rricw)) = - self.detectionRXingResultColumns[0] + if self.detectionRXingResultColumns[0] .as_ref() .unwrap() .getCodewords()[codewordsRow] .is_some() - && self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] + && self.detectionRXingResultColumns[self.barcodeColumnCount + 1] .as_ref() .unwrap() .getCodewords()[codewordsRow] .is_some() - { - if self.detectionRXingResultColumns[0] + && self.detectionRXingResultColumns[0] .as_ref() .unwrap() .getCodewords()[codewordsRow] .as_ref() .unwrap() .getRowNumber() - == self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] + == self.detectionRXingResultColumns[self.barcodeColumnCount + 1] .as_ref() .unwrap() .getCodewords()[codewordsRow] .as_ref() .unwrap() .getRowNumber() - { - // if (LRIcodewords[codewordsRow] != null && - // RRIcodewords[codewordsRow] != null && - // LRIcodewords[codewordsRow].getRowNumber() == RRIcodewords[codewordsRow].getRowNumber()) { - for barcodeColumn in 1..=self.barcodeColumnCount { - // for (int barcodeColumn = 1; barcodeColumn <= barcodeColumnCount; barcodeColumn++) { - if self.detectionRXingResultColumns[barcodeColumn].is_some() - //let Some(dc_col) = - //&mut self.detectionRXingResultColumns[barcodeColumn] + { + // if (LRIcodewords[codewordsRow] != null && + // RRIcodewords[codewordsRow] != null && + // LRIcodewords[codewordsRow].getRowNumber() == RRIcodewords[codewordsRow].getRowNumber()) { + for barcodeColumn in 1..=self.barcodeColumnCount { + // for (int barcodeColumn = 1; barcodeColumn <= barcodeColumnCount; barcodeColumn++) { + if self.detectionRXingResultColumns[barcodeColumn].is_some() + //let Some(dc_col) = + //&mut self.detectionRXingResultColumns[barcodeColumn] + { + if self.detectionRXingResultColumns[barcodeColumn] + .as_mut() + .unwrap() + .getCodewordsMut()[codewordsRow] + .is_some() { - if self.detectionRXingResultColumns[barcodeColumn] + //let Some(codeword) = &mut self.detectionRXingResultColumns[barcodeColumn].as_mut().unwrap().getCodewordsMut()[codewordsRow] { + let new_row_number = self.detectionRXingResultColumns[0] + .as_ref() + .unwrap() + .getCodewords()[codewordsRow] + .as_ref() + .unwrap() + .getRowNumber(); + self.detectionRXingResultColumns[barcodeColumn] .as_mut() .unwrap() .getCodewordsMut()[codewordsRow] - .is_some() + .as_mut() + .unwrap() + .setRowNumber(new_row_number); + if !self.detectionRXingResultColumns[barcodeColumn] + .as_mut() + .unwrap() + .getCodewordsMut()[codewordsRow] + .as_ref() + .unwrap() + .hasValidRowNumber() { - //let Some(codeword) = &mut self.detectionRXingResultColumns[barcodeColumn].as_mut().unwrap().getCodewordsMut()[codewordsRow] { - let new_row_number = self.detectionRXingResultColumns[0] - .as_ref() - .unwrap() - .getCodewords()[codewordsRow] - .as_ref() - .unwrap() - .getRowNumber(); + // self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow] = None; self.detectionRXingResultColumns[barcodeColumn] .as_mut() .unwrap() - .getCodewordsMut()[codewordsRow] - .as_mut() - .unwrap() - .setRowNumber(new_row_number); - if !self.detectionRXingResultColumns[barcodeColumn] - .as_mut() - .unwrap() - .getCodewordsMut()[codewordsRow] - .as_ref() - .unwrap() - .hasValidRowNumber() - { - // self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow] = None; - self.detectionRXingResultColumns[barcodeColumn] - .as_mut() - .unwrap() - .getCodewordsMut()[codewordsRow] = None; - } - } else { - continue; + .getCodewordsMut()[codewordsRow] = None; } } else { continue; } - // let codeword = self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow]; - // if (codeword == null) { - // continue; - // } + } else { + continue; } + // let codeword = self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow]; + // if (codeword == null) { + // continue; + // } } } } @@ -260,12 +256,12 @@ impl DetectionRXingResult { } fn adjustRowNumbersFromRRI(&mut self) -> u32 { - if self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1].is_none() { + if self.detectionRXingResultColumns[self.barcodeColumnCount + 1].is_none() { return 0; } // if let Some(col) = &self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] { let mut unadjustedCount = 0; - let codewords_len = self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] + let codewords_len = self.detectionRXingResultColumns[self.barcodeColumnCount + 1] .as_ref() .unwrap() .getCodewords() @@ -273,7 +269,7 @@ impl DetectionRXingResult { for codewordsRow in 0..codewords_len { // for (int codewordsRow = 0; codewordsRow < codewords.length; codewordsRow++) { // if let Some(codeword_col) = codewords[codewordsRow] { - if self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] + if self.detectionRXingResultColumns[self.barcodeColumnCount + 1] .as_ref() .unwrap() .getCodewords()[codewordsRow] @@ -282,7 +278,7 @@ impl DetectionRXingResult { continue; } let rowIndicatorRowNumber = self.detectionRXingResultColumns - [self.barcodeColumnCount as usize + 1] + [self.barcodeColumnCount + 1] .as_ref() .unwrap() .getCodewords()[codewordsRow] @@ -290,7 +286,7 @@ impl DetectionRXingResult { .unwrap() .getRowNumber(); let mut invalidRowCounts = 0; - let mut barcodeColumn = self.barcodeColumnCount as usize + 1; + let mut barcodeColumn = self.barcodeColumnCount + 1; while barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP { // for (int barcodeColumn = barcodeColumnCount + 1; // barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; @@ -375,7 +371,7 @@ impl DetectionRXingResult { .getRowNumber(); let mut invalidRowCounts = 0; let mut barcodeColumn = 1_usize; - while barcodeColumn < self.barcodeColumnCount as usize + 1 + while barcodeColumn < self.barcodeColumnCount + 1 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP { // for (int barcodeColumn = 1; @@ -624,11 +620,12 @@ impl DetectionRXingResult { barcodeColumn: usize, detectionRXingResultColumn: Option, ) { - self.detectionRXingResultColumns[barcodeColumn] = if detectionRXingResultColumn.is_none() { - None - } else { - Some(Box::new(detectionRXingResultColumn.unwrap())) - }; + self.detectionRXingResultColumns[barcodeColumn] = + if let Some(detectionRXingResultColumn) = detectionRXingResultColumn { + Some(Box::new(detectionRXingResultColumn)) + } else { + None + }; } pub fn getDetectionRXingResultColumn( @@ -660,7 +657,7 @@ impl Display for DetectionRXingResult { for barcodeColumn in 0..self.barcodeColumnCount + 2 { // for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) { if self.detectionRXingResultColumns[barcodeColumn].is_none() { - write!(f, "{}", " | ")?; + write!(f, " | ")?; // formatter.format(" | "); continue; } @@ -669,7 +666,7 @@ impl Display for DetectionRXingResult { .unwrap() .getCodewords()[codewordsRow]; if codeword.is_none() { - write!(f, "{}", " | ")?; + write!(f, " | ")?; // formatter.format(" | "); continue; } @@ -682,7 +679,7 @@ impl Display for DetectionRXingResult { // formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue()); } // formatter.format("%n"); - write!(f, "{}", "\n")?; + writeln!(f)?; } // return formatter.toString(); write!(f, "") diff --git a/src/pdf417/decoder/detection_result_column.rs b/src/pdf417/decoder/detection_result_column.rs index 7faddc5..e134a39 100644 --- a/src/pdf417/decoder/detection_result_column.rs +++ b/src/pdf417/decoder/detection_result_column.rs @@ -127,19 +127,19 @@ impl DetectionRXingResultColumnTrait for DetectionRXingResultColumn { impl Display for DetectionRXingResultColumn { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.isLeft.is_some() { - write!(f, "IsLeft: {} \n", self.isLeft.as_ref().unwrap())?; + writeln!(f, "IsLeft: {} ", self.isLeft.as_ref().unwrap())?; } let mut row = 0; for codeword in &self.codewords { // for (Codeword codeword : codewords) { if codeword.is_none() { - write!(f, "{:3}: | \n", row)?; + writeln!(f, "{:3}: | ", row)?; row += 1; continue; } - write!( + writeln!( f, - "{:3}: {:3}|{:3}\n", + "{:3}: {:3}|{:3}", row, codeword.as_ref().unwrap().getRowNumber(), codeword.as_ref().unwrap().getValue() diff --git a/src/pdf417/decoder/detection_result_row_indicator_column.rs b/src/pdf417/decoder/detection_result_row_indicator_column.rs index eecb840..67de26f 100644 --- a/src/pdf417/decoder/detection_result_row_indicator_column.rs +++ b/src/pdf417/decoder/detection_result_row_indicator_column.rs @@ -90,12 +90,11 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn { { self.getCodewordsMut()[codewordsRow] = None; } else { - let checkedRows; - if maxRowHeight > 2 { - checkedRows = (maxRowHeight - 2) * rowDifference; + let checkedRows = if maxRowHeight > 2 { + (maxRowHeight - 2) * rowDifference } else { - checkedRows = rowDifference; - } + rowDifference + }; let mut closePreviousCodewordFound = checkedRows >= codewordsRow as i32; let mut i = 1; while i <= checkedRows && !closePreviousCodewordFound { @@ -103,7 +102,7 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn { // there must be (height * rowDifference) number of codewords missing. For now we assume height = 1. // This should hopefully get rid of most problems already. closePreviousCodewordFound = - self.getCodewords()[codewordsRow as usize - i as usize].is_some(); + self.getCodewords()[codewordsRow - i as usize].is_some(); i += 1; } @@ -176,10 +175,10 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn { } } // Maybe we should check if we have ambiguous values? - if (barcodeColumnCount.getValue().len() == 0) - || (barcodeRowCountUpperPart.getValue().len() == 0) - || (barcodeRowCountLowerPart.getValue().len() == 0) - || (barcodeECLevel.getValue().len() == 0) + if barcodeColumnCount.getValue().is_empty() + || barcodeRowCountUpperPart.getValue().is_empty() + || barcodeRowCountLowerPart.getValue().is_empty() + || barcodeECLevel.getValue().is_empty() || barcodeColumnCount.getValue()[0] < 1 || barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0] < pdf_417_common::MIN_ROWS_IN_BARCODE @@ -211,13 +210,13 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn { // } fn setRowNumbers(code_words: &mut [Option]) { - for codeword_opt in code_words { + for codeword in code_words.iter_mut().flatten() { //self.0.getCodewordsMut() { // for (Codeword codeword : getCodewords()) { - if let Some(codeword) = codeword_opt { - // if (codeword != null) { - codeword.setRowNumberAsRowIndicatorColumn(); - } + // if let Some(codeword) = codeword_opt { + // if (codeword != null) { + codeword.setRowNumberAsRowIndicatorColumn(); + // } } } @@ -228,13 +227,14 @@ fn removeIncorrectCodewords( ) { // Remove codewords which do not match the metadata // TODO Maybe we should keep the incorrect codewords for the start and end positions? - for codewordRow in 0..codewords.len() { + for codeword_row in codewords.iter_mut() { + // for codewordRow in 0..codewords.len() { // for (int codewordRow = 0; codewordRow < codewords.length; codewordRow++) { - if let Some(codeword) = codewords[codewordRow] { + if let Some(codeword) = codeword_row { let rowIndicatorValue = codeword.getValue() % 30; let mut codewordRowNumber = codeword.getRowNumber(); if codewordRowNumber > barcodeMetadata.getRowCount() as i32 { - codewords[codewordRow] = None; + *codeword_row = None; continue; } if !isLeft { @@ -243,19 +243,19 @@ fn removeIncorrectCodewords( match codewordRowNumber % 3 { 0 => { if rowIndicatorValue * 3 + 1 != barcodeMetadata.getRowCountUpperPart() { - codewords[codewordRow] = None; + *codeword_row = None; } } 1 => { if rowIndicatorValue / 3 != barcodeMetadata.getErrorCorrectionLevel() || rowIndicatorValue % 3 != barcodeMetadata.getRowCountLowerPart() { - codewords[codewordRow] = None; + *codeword_row = None; } } 2 => { if rowIndicatorValue + 1 != barcodeMetadata.getColumnCount() { - codewords[codewordRow] = None; + *codeword_row = None; } } _ => {} @@ -291,10 +291,10 @@ fn adjustIncompleteIndicatorColumnRowNumbers( let mut barcodeRow = -1; let mut maxRowHeight = 1; let mut currentRowHeight = 0; - for codewordsRow in firstRow..lastRow { + for codword_opt in codewords.iter_mut().take(lastRow).skip(firstRow) { // for (int codewordsRow = firstRow; codewordsRow < lastRow; codewordsRow++) { - if let Some(codeword) = &mut codewords[codewordsRow] { + if let Some(codeword) = codword_opt { codeword.setRowNumberAsRowIndicatorColumn(); let rowDifference = codeword.getRowNumber() - barcodeRow; @@ -308,7 +308,7 @@ fn adjustIncompleteIndicatorColumnRowNumbers( currentRowHeight = 1; barcodeRow = codeword.getRowNumber(); } else if codeword.getRowNumber() >= barcodeMetadata.getRowCount() as i32 { - codewords[codewordsRow] = None; + *codword_opt = None; } else { barcodeRow = codeword.getRowNumber(); currentRowHeight = 1; diff --git a/src/pdf417/decoder/ec/error_correction.rs b/src/pdf417/decoder/ec/error_correction.rs index ecef469..0e67071 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -47,13 +47,13 @@ lazy_static! { * @return number of errors * @throws ChecksumException if errors cannot be corrected, maybe because of too many errors */ -pub fn decode<'a>( +pub fn decode( received: &mut [u32], numECCodewords: u32, erasures: &mut [u32], ) -> Result { - let field: Rc<&'static ModulusGF> = Rc::new(&FLD_INTERIOR); - let poly = ModulusPoly::new(field.clone(), received.to_vec())?; + let field: &'static ModulusGF = &FLD_INTERIOR; + let poly = ModulusPoly::new(field, received.to_vec())?; let mut S = vec![0u32; numECCodewords as usize]; let mut error = false; for i in (1..=numECCodewords).rev() { @@ -69,7 +69,7 @@ pub fn decode<'a>( return Ok(0); } - let mut knownErrors: Rc = ModulusPoly::getOne(field.clone()); + let mut knownErrors: Rc = ModulusPoly::getOne(field); let mut b; let mut term; let mut kE: Rc; @@ -78,34 +78,34 @@ pub fn decode<'a>( // for (int erasure : erasures) { b = field.exp(received.len() as u32 - 1 - *erasure); // Add (1 - bx) term: - term = ModulusPoly::new(field.clone(), vec![field.subtract(0, b), 1])?; + term = ModulusPoly::new(field, vec![field.subtract(0, b), 1])?; kE = knownErrors.clone(); knownErrors = kE.multiply(Rc::new(term))?; } } - let syndrome = Rc::new(ModulusPoly::new(field.clone(), S)?); + let syndrome = Rc::new(ModulusPoly::new(field, S)?); //syndrome = syndrome.multiply(knownErrors); let sigmaOmega = runEuclideanAlgorithm( - ModulusPoly::buildMonomial(field.clone(), numECCodewords as usize, 1), + ModulusPoly::buildMonomial(field, numECCodewords as usize, 1), syndrome, numECCodewords, - field.clone(), + field, )?; let sigma = sigmaOmega[0].clone(); let omega = sigmaOmega[1].clone(); //sigma = sigma.multiply(knownErrors); - let mut errorLocations = findErrorLocations(sigma.clone(), field.clone())?; - let errorMagnitudes = findErrorMagnitudes(omega, sigma, &mut errorLocations, field.clone()); + let mut errorLocations = findErrorLocations(sigma.clone(), field)?; + let errorMagnitudes = findErrorMagnitudes(omega, sigma, &mut errorLocations, field); for i in 0..errorLocations.len() { // for (int i = 0; i < errorLocations.length; i++) { let position = received.len() as isize - 1 - field.log(errorLocations[i])? as isize; if position < 0 { - return Err(Exceptions::ChecksumException(format!("{}", file!()))); + return Err(Exceptions::ChecksumException(Some(file!().to_string()))); } received[position as usize] = field.subtract(received[position as usize], errorMagnitudes[i]); @@ -118,7 +118,7 @@ fn runEuclideanAlgorithm( a: Rc, b: Rc, R: u32, - field: Rc<&'static ModulusGF>, + field: &'static ModulusGF, ) -> Result<[Rc; 2], Exceptions> { // Assume a's degree is >= b's let mut a = a; @@ -129,8 +129,8 @@ fn runEuclideanAlgorithm( let mut rLast = a; let mut r = b; - let mut tLast = ModulusPoly::getZero(field.clone()); - let mut t = ModulusPoly::getOne(field.clone()); + let mut tLast = ModulusPoly::getZero(field); + let mut t = ModulusPoly::getOne(field); // Run Euclidean algorithm until r's degree is less than R/2 while r.getDegree() >= R / 2 { @@ -142,17 +142,17 @@ fn runEuclideanAlgorithm( // Divide rLastLast by rLast, with quotient in q and remainder in r if rLast.isZero() { // Oops, Euclidean algorithm already terminated? - return Err(Exceptions::ChecksumException(format!("{}", file!()))); + return Err(Exceptions::ChecksumException(Some(file!().to_string()))); } r = rLastLast; - let mut q = ModulusPoly::getZero(field.clone()); //field.getZero(); + let mut q = ModulusPoly::getZero(field); //field.getZero(); let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree() as usize); let dltInverse = field.inverse(denominatorLeadingTerm)?; while r.getDegree() >= rLast.getDegree() && !r.isZero() { let degreeDiff = r.getDegree() - rLast.getDegree(); let scale = field.multiply(r.getCoefficient(r.getDegree() as usize), dltInverse); q = q.add(ModulusPoly::buildMonomial( - field.clone(), + field, degreeDiff as usize, scale, ))?; @@ -164,7 +164,7 @@ fn runEuclideanAlgorithm( let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::ChecksumException(format!("{}", file!()))); + return Err(Exceptions::ChecksumException(Some(file!().to_string()))); } let inverse = field.inverse(sigmaTildeAtZero)?; @@ -176,7 +176,7 @@ fn runEuclideanAlgorithm( fn findErrorLocations( errorLocator: Rc, - field: Rc<&ModulusGF>, + field: &ModulusGF, ) -> Result, Exceptions> { // This is a direct application of Chien's search let numErrors = errorLocator.getDegree(); @@ -192,7 +192,7 @@ fn findErrorLocations( i += 1; } if e != numErrors { - return Err(Exceptions::ChecksumException(format!("{}", file!()))); + return Err(Exceptions::ChecksumException(Some(file!().to_string()))); } Ok(result) } @@ -201,7 +201,7 @@ fn findErrorMagnitudes( errorEvaluator: Rc, errorLocator: Rc, errorLocations: &mut [u32], - field: Rc<&'static ModulusGF>, + field: &'static ModulusGF, ) -> Vec { let errorLocatorDegree = errorLocator.getDegree(); if errorLocatorDegree < 1 { @@ -213,8 +213,8 @@ fn findErrorMagnitudes( formalDerivativeCoefficients[errorLocatorDegree as usize - i as usize] = field.multiply(i, errorLocator.getCoefficient(i as usize)); } - let formalDerivative = ModulusPoly::new(field.clone(), formalDerivativeCoefficients) - .expect("should generate good poly"); + let formalDerivative = + ModulusPoly::new(field, formalDerivativeCoefficients).expect("should generate good poly"); // This is directly applying Forney's Formula let s = errorLocations.len(); diff --git a/src/pdf417/decoder/ec/error_correction_test_case.rs b/src/pdf417/decoder/ec/error_correction_test_case.rs index 6903f7f..5267a65 100644 --- a/src/pdf417/decoder/ec/error_correction_test_case.rs +++ b/src/pdf417/decoder/ec/error_correction_test_case.rs @@ -49,7 +49,7 @@ const _MAX_ERASURES: usize = ERROR_LIMIT; #[test] fn testNoError() { - let mut received = PDF417_TEST_WITH_EC.clone(); + let mut received = PDF417_TEST_WITH_EC; // no errors checkDecode(&mut received).expect("ok"); } @@ -58,7 +58,7 @@ fn testNoError() { fn testExplicitError() { for i in 0..PDF417_TEST_WITH_EC.len() { // for (int i = 0; i < PDF417_TEST_WITH_EC.length; i++) { - let mut received = PDF417_TEST_WITH_EC.clone(); + let mut received = PDF417_TEST_WITH_EC; received[i] = 610; //random.gen_range(0..256);// random.nextInt(256); checkDecode(&mut received).expect("ok"); } @@ -69,7 +69,7 @@ fn testOneError() { let mut random = getRandom(); for i in 0..PDF417_TEST_WITH_EC.len() { // for (int i = 0; i < PDF417_TEST_WITH_EC.length; i++) { - let mut received = PDF417_TEST_WITH_EC.clone(); + let mut received = PDF417_TEST_WITH_EC; received[i] = random.gen_range(0..256); //random.gen_range(0..256);// random.nextInt(256); checkDecode(&mut received).expect("ok"); } @@ -80,7 +80,7 @@ fn testMaxErrors() { let mut random = getRandom(); for _testIterations in 0..100 { // for (int testIterations = 0; testIterations < 100; testIterations++) { // # iterations is kind of arbitrary - let mut received = PDF417_TEST_WITH_EC.clone(); + let mut received = PDF417_TEST_WITH_EC; corrupt(&mut received, MAX_ERRORS as u32, &mut random); checkDecode(&mut received).expect("ok"); } @@ -88,7 +88,7 @@ fn testMaxErrors() { #[test] fn testTooManyErrors() { - let mut received = PDF417_TEST_WITH_EC.clone(); + let mut received = PDF417_TEST_WITH_EC; let mut random = getRandom(); corrupt(&mut received, MAX_ERRORS as u32 + 1, &mut random); // try { diff --git a/src/pdf417/decoder/ec/modulus_gf.rs b/src/pdf417/decoder/ec/modulus_gf.rs index 2dbf451..539342b 100644 --- a/src/pdf417/decoder/ec/modulus_gf.rs +++ b/src/pdf417/decoder/ec/modulus_gf.rs @@ -38,9 +38,10 @@ impl ModulusGF { let mut expTable = vec![0u32; modulus as usize]; //new int[modulus]; let mut logTable = vec![0u32; modulus as usize]; //new int[modulus]; let mut x = 1; - for i in 0..modulus as usize { + for table_entry in expTable.iter_mut().take(modulus as usize) { + // for i in 0..modulus as usize { // for (int i = 0; i < modulus; i++) { - expTable[i] = x; + *table_entry = x; x = (x * generator) % modulus; } for i in 0..modulus as usize - 1 { @@ -49,18 +50,17 @@ impl ModulusGF { } // logTable[0] == 0 but this should never be used - let potential_self = Self { + // zero = new ModulusPoly(this, new int[]{0}); + // one = new ModulusPoly(this, new int[]{1}); + + Self { expTable, logTable, // zero: None, // one: None, modulus, generator, - }; - // zero = new ModulusPoly(this, new int[]{0}); - // one = new ModulusPoly(this, new int[]{1}); - - potential_self + } } pub fn add(&self, a: u32, b: u32) -> u32 { @@ -77,7 +77,7 @@ impl ModulusGF { pub fn log(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::ArithmeticException("".to_owned())) + Err(Exceptions::ArithmeticException(None)) } else { Ok(self.logTable[a as usize]) } @@ -85,7 +85,7 @@ impl ModulusGF { pub fn inverse(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::ArithmeticException("".to_owned())) + Err(Exceptions::ArithmeticException(None)) } else { Ok(self.expTable[self.modulus as usize - self.logTable[a as usize] as usize - 1]) } diff --git a/src/pdf417/decoder/ec/modulus_poly.rs b/src/pdf417/decoder/ec/modulus_poly.rs index c7bf9b3..13920bf 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -25,18 +25,18 @@ use super::ModulusGF; */ #[derive(Clone, Debug)] pub struct ModulusPoly { - field: Rc<&'static ModulusGF>, + field: &'static ModulusGF, coefficients: Vec, // zero: Option>, // one: Option>, } impl ModulusPoly { pub fn new( - field: Rc<&'static ModulusGF>, + field: &'static ModulusGF, coefficients: Vec, ) -> Result { if coefficients.is_empty() { - return Err(Exceptions::IllegalArgumentException("".to_owned())); + return Err(Exceptions::IllegalArgumentException(None)); } let orig_coefs = coefficients.clone(); let mut coefficients = coefficients; @@ -51,20 +51,21 @@ impl ModulusPoly { coefficients = vec![0]; } else { coefficients = vec![0u32; coefficientsLength - firstNonZero]; - coefficients[..].copy_from_slice(&&orig_coefs[firstNonZero..]); + coefficients[..].copy_from_slice(&orig_coefs[firstNonZero..]); // System.arraycopy(coefficients, // firstNonZero, // this.coefficients, // 0, // this.coefficients.length); } - } else { - coefficients = coefficients; } + // } else { + // coefficients = coefficients; + // } Ok(ModulusPoly { - field: field.clone(), - coefficients: coefficients, + field, + coefficients, // zero: Some(Self::getZero(field.clone())), // one: Some(Self::getOne(field.clone())), }) @@ -120,14 +121,14 @@ impl ModulusPoly { .field .add(self.field.multiply(a, result), self.coefficients[i]); } - return result; + result } pub fn add(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), - )); + ))); } if self.isZero() { return Ok(other); @@ -141,7 +142,7 @@ impl ModulusPoly { if smallerCoefficients.len() > largerCoefficients.len() { std::mem::swap(&mut smallerCoefficients, &mut largerCoefficients); } - let mut sumDiff = vec![0032; largerCoefficients.len()]; + let mut sumDiff = vec![0_u32; largerCoefficients.len()]; let lengthDiff = largerCoefficients.len() - smallerCoefficients.len(); // Copy high-order terms only found in higher-degree polynomial's coefficients sumDiff[..lengthDiff].copy_from_slice(&largerCoefficients[..lengthDiff]); @@ -155,31 +156,30 @@ impl ModulusPoly { } Ok(Rc::new( - ModulusPoly::new(self.field.clone(), sumDiff) - .expect("should always generate with known goods"), + ModulusPoly::new(self.field, sumDiff).expect("should always generate with known goods"), )) } pub fn subtract(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), - )); + ))); } if other.isZero() { return Ok(Rc::new(self.clone())); }; - self.add(other.negative().clone()) + self.add(other.negative()) } pub fn multiply(&self, other: Rc) -> Result, Exceptions> { if !(self.field == other.field) { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), - )); + ))); } if self.isZero() || other.isZero() { - return Ok(Self::getZero(self.field.clone()).clone()); + return Ok(Self::getZero(self.field)); } let aCoefficients = &self.coefficients; let aLength = aCoefficients.len(); @@ -199,77 +199,68 @@ impl ModulusPoly { } Ok(Rc::new( - ModulusPoly::new(self.field.clone(), product) - .expect("should always generate with known goods"), + ModulusPoly::new(self.field, product).expect("should always generate with known goods"), )) } pub fn negative(&self) -> Rc { let size = self.coefficients.len(); let mut negativeCoefficients = vec![0u32; size]; - for i in 0..size { + for (i, neg_coef) in negativeCoefficients.iter_mut().enumerate().take(size) { // for (int i = 0; i < size; i++) { - negativeCoefficients[i] = self.field.subtract(0, self.coefficients[i]); + *neg_coef = self.field.subtract(0, self.coefficients[i]); } Rc::new( - ModulusPoly::new(self.field.clone(), negativeCoefficients) + ModulusPoly::new(self.field, negativeCoefficients) .expect("should always generate with known goods"), ) } pub fn multiplyByScaler(&self, scalar: u32) -> Rc { if scalar == 0 { - return Self::getZero(self.field.clone()).clone(); + return Self::getZero(self.field); } if scalar == 1 { return Rc::new(self.clone()); } let size = self.coefficients.len(); let mut product = vec![0u32; size]; - for i in 0..size { + for (i, prod) in product.iter_mut().enumerate().take(size) { // for (int i = 0; i < size; i++) { - product[i] = self.field.multiply(self.coefficients[i], scalar); + *prod = self.field.multiply(self.coefficients[i], scalar); } Rc::new( - ModulusPoly::new(self.field.clone(), product) - .expect("should always generate with known goods"), + ModulusPoly::new(self.field, product).expect("should always generate with known goods"), ) } pub fn multiplyByMonomial(&self, degree: usize, coefficient: u32) -> Rc { if coefficient == 0 { - return Self::getZero(self.field.clone()).clone(); + return Self::getZero(self.field); } let size = self.coefficients.len(); let mut product = vec![0u32; size + degree]; - for i in 0..size { + for (i, prod) in product.iter_mut().enumerate().take(size) { // for (int i = 0; i < size; i++) { - product[i] = self.field.multiply(self.coefficients[i], coefficient); + *prod = self.field.multiply(self.coefficients[i], coefficient); } Rc::new( - ModulusPoly::new(self.field.clone(), product) - .expect("should always generate with known goods"), + ModulusPoly::new(self.field, product).expect("should always generate with known goods"), ) } - pub fn getZero(field: Rc<&'static ModulusGF>) -> Rc { - Rc::new( - ModulusPoly::new(field.clone(), vec![0]) - .expect("should always generate with known goods"), - ) + pub fn getZero(field: &'static ModulusGF) -> Rc { + Rc::new(ModulusPoly::new(field, vec![0]).expect("should always generate with known goods")) } - pub fn getOne(field: Rc<&'static ModulusGF>) -> Rc { - Rc::new( - ModulusPoly::new(field.clone(), vec![1]) - .expect("should always generate with known goods"), - ) + pub fn getOne(field: &'static ModulusGF) -> Rc { + Rc::new(ModulusPoly::new(field, vec![1]).expect("should always generate with known goods")) } pub fn buildMonomial( - field: Rc<&'static ModulusGF>, + field: &'static ModulusGF, degree: usize, coefficient: u32, ) -> Rc { @@ -282,8 +273,7 @@ impl ModulusPoly { let mut coefficients = vec![0_u32; degree + 1]; coefficients[0] = coefficient; Rc::new( - ModulusPoly::new(field.clone(), coefficients) - .expect("should always generate with known goods"), + ModulusPoly::new(field, coefficients).expect("should always generate with known goods"), ) } diff --git a/src/pdf417/decoder/pdf_417_codeword_decoder.rs b/src/pdf417/decoder/pdf_417_codeword_decoder.rs index e31bc84..4094228 100644 --- a/src/pdf417/decoder/pdf_417_codeword_decoder.rs +++ b/src/pdf417/decoder/pdf_417_codeword_decoder.rs @@ -92,11 +92,11 @@ fn getDecodedCodewordValue(moduleBitCount: &[u32]) -> i32 { fn getBitValue(moduleBitCount: &[u32]) -> i32 { let mut result: u64 = 0; - for i in 0..moduleBitCount.len() { + for (i, mbc) in moduleBitCount.iter().enumerate() { // for (int i = 0; i < moduleBitCount.length; i++) { - for _bit in 0..moduleBitCount[i] { + for _bit in 0..(*mbc) { // for (int bit = 0; bit < moduleBitCount[i]; bit++) { - result = (result << 1) | (if i % 2 == 0 { 1 } else { 0 }); + result = (result << 1) | u64::from(i % 2 == 0); //(if i % 2 == 0 { 1 } else { 0 }); } } result as i32 @@ -113,10 +113,9 @@ fn getClosestDecodedValue(moduleBitCount: &[u32]) -> i32 { } let mut bestMatchError = f32::MAX; let mut bestMatch = -1_i32; - for j in 0..RATIOS_TABLE.len() { + for (j, ratioTableRow) in RATIOS_TABLE.iter().enumerate() { // for (int j = 0; j < RATIOS_TABLE.length; j++) { let mut error = 0.0; - let ratioTableRow = &RATIOS_TABLE[j]; for k in 0..pdf_417_common::BARS_IN_MODULE as usize { // for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) { let diff = ratioTableRow[k] - bitCountRatios[k]; diff --git a/src/pdf417/decoder/pdf_417_decoder_test_case.rs b/src/pdf417/decoder/pdf_417_decoder_test_case.rs index 776d4a6..4be3d2b 100644 --- a/src/pdf417/decoder/pdf_417_decoder_test_case.rs +++ b/src/pdf417/decoder/pdf_417_decoder_test_case.rs @@ -432,7 +432,7 @@ fn encodeDecodeWithLength(input: &str, expectedLength: u32) { } fn encodeDecode(input: &str) -> u32 { - return encodeDecodeWithAll(input, None, false, true); + encodeDecodeWithAll(input, None, false, true) } fn encodeDecodeWithAll( @@ -451,9 +451,9 @@ fn encodeDecodeWithAll( if decode { let mut codewords = vec![0_u32; s.chars().count() + 1]; codewords[0] = codewords.len() as u32; - for i in 1..codewords.len() { + for (i, codeword) in codewords.iter_mut().enumerate().skip(1) { // for (int i = 1; i < codewords.length; i++) { - codewords[i] = s.chars().nth(i - 1).unwrap() as u32; + *codeword = s.chars().nth(i - 1).unwrap() as u32; } performDecodeTest(&codewords, input); } @@ -499,14 +499,9 @@ fn performPermutationTest(chars: &[char], length: u32, expectedTotal: u32) { } fn performEncodeTest(c: char, expectedLengths: &[u32]) { - for i in 0..expectedLengths.len() { - // for (int i = 0; i < expectedLengths.length; i++) { - let mut sb = String::new(); //new StringBuilder(); - for _j in 0..=i { - // for (int j = 0; j <= i; j++) { - sb.push(c); - } - encodeDecodeWithLength(&sb, expectedLengths[i]); + for (i, epected_length) in expectedLengths.iter().enumerate() { + let sb = vec![c; i + 1].into_iter().collect::(); + encodeDecodeWithLength(&sb, *epected_length); } } @@ -548,17 +543,17 @@ fn generateText( // } total += weights.iter().sum::(); - for i in 0..weights.len() { + for weight in weights.iter_mut() { // for (int i = 0; i < weights.length; i++) { - weights[i] /= total; + *weight /= total; } let mut cnt = 0; loop { let mut maxValue = 0.0; let mut maxIndex = 0; - for j in 0..weights.len() { + for (j, weight) in weights.iter().enumerate() { // for (int j = 0; j < weights.length; j++) { - let value = random.next_f32() * weights[j]; + let value = random.next_f32() * *weight; if value > maxValue { maxValue = value; maxIndex = j; @@ -571,7 +566,7 @@ fn generateText( for j in 0..wordLength.ceil() as u32 { // for (int j = 0; j < wordLength; j++) { let mut c = chars[maxIndex]; - if j == 0 && c >= 'a' && c <= 'z' && random.next_bool() { + if j == 0 && ('a'..='z').contains(&c) && random.next_bool() { c = char::from_u32(c as u32 - 'a' as u32 + 'A' as u32).unwrap(); } result.push(c); @@ -581,7 +576,7 @@ fn generateText( } cnt += 1; - if !(result.chars().count() < (maxWidth as isize - maxWordWidth as isize) as usize) { + if result.chars().count() >= (maxWidth as isize - maxWordWidth as isize) as usize { break; } } //while (result.length() < maxWidth - maxWordWidth); diff --git a/src/pdf417/decoder/pdf_417_scanning_decoder.rs b/src/pdf417/decoder/pdf_417_scanning_decoder.rs index fc84fc0..7a64f28 100644 --- a/src/pdf417/decoder/pdf_417_scanning_decoder.rs +++ b/src/pdf417/decoder/pdf_417_scanning_decoder.rs @@ -87,7 +87,7 @@ pub fn decode( } detectionRXingResult = merge(&mut leftRowIndicatorColumn, &mut rightRowIndicatorColumn)?; if detectionRXingResult.is_none() { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } // detectionRXingResult = detectionRXingResult; @@ -159,8 +159,8 @@ pub fn decode( minCodewordWidth, maxCodewordWidth, ); - if codeword.is_some() { - let codeword = codeword.unwrap(); + if let Some(codeword) = codeword { + // let codeword = codeword.unwrap(); //detectionRXingResultColumn.setCodeword(imageRow, codeword); detectionRXingResult .getDetectionRXingResultColumnMut(barcodeColumn) @@ -264,9 +264,13 @@ fn getBarcodeMetadata( leftRowIndicatorColumn: &mut Option, rightRowIndicatorColumn: &mut Option, ) -> Option { - let leftBarcodeMetadata; - - if leftRowIndicatorColumn.is_none() { + let leftBarcodeMetadata = if leftRowIndicatorColumn.is_none() + || leftRowIndicatorColumn + .as_mut() + .unwrap() + .getBarcodeMetadata() + .is_none() + { return if rightRowIndicatorColumn.is_none() { None } else { @@ -276,51 +280,30 @@ fn getBarcodeMetadata( .getBarcodeMetadata() }; } else { - if leftRowIndicatorColumn + leftRowIndicatorColumn .as_mut() .unwrap() .getBarcodeMetadata() - .is_none() - { - return if rightRowIndicatorColumn.is_none() { - None - } else { - rightRowIndicatorColumn - .as_mut() - .unwrap() - .getBarcodeMetadata() - }; - } else { - leftBarcodeMetadata = leftRowIndicatorColumn - .as_mut() - .unwrap() - .getBarcodeMetadata() - } - } + }; // if leftRowIndicatorColumn.is_none() || // (leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()).is_none() { // return if rightRowIndicatorColumn.is_none() {None} else {rightRowIndicatorColumn.getBarcodeMetadata()}; // } - let rightBarcodeMetadata; - - if rightRowIndicatorColumn.is_none() { - return leftBarcodeMetadata; - } else { - if rightRowIndicatorColumn + let rightBarcodeMetadata = if rightRowIndicatorColumn.is_none() + || rightRowIndicatorColumn .as_mut() .unwrap() .getBarcodeMetadata() .is_none() - { - return leftBarcodeMetadata; - } else { - rightBarcodeMetadata = rightRowIndicatorColumn - .as_mut() - .unwrap() - .getBarcodeMetadata(); - } - } + { + return leftBarcodeMetadata; + } else { + rightRowIndicatorColumn + .as_mut() + .unwrap() + .getBarcodeMetadata() + }; // if rightRowIndicatorColumn.is_none() || // (rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()).is_none() { // return leftBarcodeMetadata; @@ -392,7 +375,7 @@ fn getRowIndicatorColumn<'a>( fn adjustCodewordCount( detectionRXingResult: &DetectionRXingResult, - barcodeMatrix: &mut Vec>, + barcodeMatrix: &mut [Vec], ) -> Result<(), Exceptions> { let barcodeMatrix01 = &mut barcodeMatrix[0][1]; let numberOfCodewords = barcodeMatrix01.getValue(); @@ -400,20 +383,16 @@ fn adjustCodewordCount( * detectionRXingResult.getBarcodeRowCount() as isize - getNumberOfECCodeWords(detectionRXingResult.getBarcodeECLevel()) as isize) as u32; - if numberOfCodewords.len() == 0 { - if calculatedNumberOfCodewords < 1 - || calculatedNumberOfCodewords > pdf_417_common::MAX_CODEWORDS_IN_BARCODE - { - return Err(Exceptions::NotFoundException("".to_owned())); + if numberOfCodewords.is_empty() { + if !(1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords) { + return Err(Exceptions::NotFoundException(None)); } barcodeMatrix01.setValue(calculatedNumberOfCodewords); - } else if numberOfCodewords[0] != calculatedNumberOfCodewords { - if calculatedNumberOfCodewords >= 1 - && calculatedNumberOfCodewords <= pdf_417_common::MAX_CODEWORDS_IN_BARCODE - { - // The calculated one is more reliable as it is derived from the row indicator columns - barcodeMatrix01.setValue(calculatedNumberOfCodewords); - } + } else if numberOfCodewords[0] != calculatedNumberOfCodewords + && (1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords) + { + // The calculated one is more reliable as it is derived from the row indicator columns + barcodeMatrix01.setValue(calculatedNumberOfCodewords); } Ok(()) } @@ -438,7 +417,7 @@ fn createDecoderRXingResult( let values = barcodeMatrix[row as usize][column + 1].getValue(); let codewordIndex = row as usize * detectionRXingResult.getBarcodeColumnCount() + column; - if values.len() == 0 { + if values.is_empty() { erasures.push(codewordIndex as u32); } else if values.len() == 1 { codewords[codewordIndex] = values[0]; @@ -483,7 +462,7 @@ fn createDecoderRXingResultFromAmbiguousValues( codewords: &mut [u32], erasureArray: &mut [u32], ambiguousIndexes: &mut [u32], - ambiguousIndexValues: &Vec>, + ambiguousIndexValues: &[Vec], ) -> Result { let mut ambiguousIndexCount = vec![0; ambiguousIndexes.len()]; @@ -503,8 +482,8 @@ fn createDecoderRXingResultFromAmbiguousValues( // } catch (ChecksumException ignored) { // // // } - if ambiguousIndexCount.len() == 0 { - return Err(Exceptions::ChecksumException("".to_owned())); + if ambiguousIndexCount.is_empty() { + return Err(Exceptions::ChecksumException(None)); } for i in 0..ambiguousIndexCount.len() { // for (int i = 0; i < ambiguousIndexCount.length; i++) { @@ -514,14 +493,14 @@ fn createDecoderRXingResultFromAmbiguousValues( } else { ambiguousIndexCount[i] = 0; if i == ambiguousIndexCount.len() - 1 { - return Err(Exceptions::ChecksumException("".to_owned())); + return Err(Exceptions::ChecksumException(None)); } } } tries -= 1; } - Err(Exceptions::ChecksumException("".to_owned())) + Err(Exceptions::ChecksumException(None)) } fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec> { @@ -544,19 +523,25 @@ fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec= 0 { - if rowNumber as usize >= barcodeMatrix.len() { - // We have more rows than the barcode metadata allows for, ignore them. - continue; - } - barcodeMatrix[rowNumber as usize][column].setValue(codeword.getValue()); + // if let Some(codeword) = codeword { + // if codeword.is_some() { + let rowNumber = codeword.getRowNumber(); + if rowNumber >= 0 { + if rowNumber as usize >= barcodeMatrix.len() { + // We have more rows than the barcode metadata allows for, ignore them. + continue; } + barcodeMatrix[rowNumber as usize][column].setValue(codeword.getValue()); } + // } } } column += 1; @@ -580,7 +565,7 @@ fn getStartColumn( let mut codeword = &None; if isValidBarcodeColumn(detectionRXingResult, (barcodeColumn - offset) as usize) { codeword = detectionRXingResult - .getDetectionRXingResultColumn((barcodeColumn as isize - offset) as usize) + .getDetectionRXingResultColumn((barcodeColumn - offset) as usize) .as_ref() .unwrap() .getCodeword(imageRow); @@ -688,9 +673,7 @@ fn detectCodeword( startColumn, imageRow, ); - if moduleBitCount.is_none() { - return None; - } + moduleBitCount?; let mut moduleBitCount = moduleBitCount.unwrap(); let endColumn; @@ -811,7 +794,7 @@ fn adjustCodewordStartColumn( correctedStartColumn < maxColumn }) && leftToRight == image.get(correctedStartColumn, imageRow) { - if (codewordStartColumn as i64 - correctedStartColumn as i64).abs() as u32 + if (codewordStartColumn as i64 - correctedStartColumn as i64).unsigned_abs() as u32 > CODEWORD_SKEW_SIZE { return codewordStartColumn; @@ -824,12 +807,12 @@ fn adjustCodewordStartColumn( increment = -increment; leftToRight = !leftToRight; } - return correctedStartColumn; + correctedStartColumn } fn checkCodewordSkew(codewordSize: u32, minCodewordWidth: u32, maxCodewordWidth: u32) -> bool { - return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize - && codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE; + minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize + && codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE } fn decodeCodewords( @@ -838,7 +821,7 @@ fn decodeCodewords( erasures: &mut [u32], ) -> Result { if codewords.is_empty() { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } let numECCodewords = 1 << (ecLevel + 1); @@ -873,7 +856,7 @@ fn correctErrors( || numECCodewords > MAX_EC_CODEWORDS { // Too many errors or EC Codewords is corrupted - return Err(Exceptions::ChecksumException("".to_owned())); + return Err(Exceptions::ChecksumException(None)); } ec::error_correction::decode(codewords, numECCodewords, erasures) } @@ -885,21 +868,21 @@ fn verifyCodewordCount(codewords: &mut [u32], numECCodewords: u32) -> Result<(), if codewords.len() < 4 { // Codeword array size should be at least 4 allowing for // Count CW, At least one Data CW, Error Correction CW, Error Correction CW - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. let numberOfCodewords = codewords[0]; if numberOfCodewords > codewords.len() as u32 { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } if numberOfCodewords == 0 { // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) if numECCodewords < codewords.len() as u32 { codewords[0] = codewords.len() as u32 - numECCodewords; } else { - return Err(Exceptions::FormatException("".to_owned())); + return Err(Exceptions::FormatException(None)); } } Ok(()) diff --git a/src/pdf417/detector/detector.rs b/src/pdf417/detector/detector.rs index 5377a1b..3824337 100644 --- a/src/pdf417/detector/detector.rs +++ b/src/pdf417/detector/detector.rs @@ -287,24 +287,20 @@ fn findRowsWithPattern( // don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With // a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly // larger drift and don't check for skipped rows. - if ((previousRowLoc[0] as i32 - loc[0] as i32).abs() as u32) < MAX_PATTERN_DRIFT - && ((previousRowLoc[1] as i32 - loc[1] as i32).abs() as u32) < MAX_PATTERN_DRIFT + if (previousRowLoc[0] as i32 - loc[0] as i32).unsigned_abs() < MAX_PATTERN_DRIFT + && (previousRowLoc[1] as i32 - loc[1] as i32).unsigned_abs() < MAX_PATTERN_DRIFT { previousRowLoc = loc; skippedRowCount = 0; - } else { - if skippedRowCount > SKIPPED_ROW_COUNT_MAX { - break; - } else { - skippedRowCount += 1; - } - } - } else { - if skippedRowCount > SKIPPED_ROW_COUNT_MAX { + } else if skippedRowCount > SKIPPED_ROW_COUNT_MAX { break; } else { skippedRowCount += 1; } + } else if skippedRowCount > SKIPPED_ROW_COUNT_MAX { + break; + } else { + skippedRowCount += 1; } stopRow += 1; diff --git a/src/pdf417/encoder/barcode_row.rs b/src/pdf417/encoder/barcode_row.rs index 76cee96..24556e4 100644 --- a/src/pdf417/encoder/barcode_row.rs +++ b/src/pdf417/encoder/barcode_row.rs @@ -51,7 +51,7 @@ impl BarcodeRow { * @param black Black if true, white if false; */ fn set_bool(&mut self, x: usize, black: bool) { - self.row[x] = if black { 1 } else { 0 } + self.row[x] = u8::from(black); //if black { 1 } else { 0 } } /** @@ -74,9 +74,10 @@ impl BarcodeRow { */ pub fn getScaledRow(&self, scale: usize) -> Vec { let mut output = vec![0; self.row.len() * scale]; - for i in 0..output.len() { + for (i, row) in output.iter_mut().enumerate() { + // for i in 0..output.len() { // for (int i = 0; i < output.length; i++) { - output[i] = self.row[i / scale]; + *row = self.row[i / scale]; } output diff --git a/src/pdf417/encoder/compaction.rs b/src/pdf417/encoder/compaction.rs index 941b4d7..235ad01 100644 --- a/src/pdf417/encoder/compaction.rs +++ b/src/pdf417/encoder/compaction.rs @@ -40,9 +40,9 @@ impl TryFrom<&String> for Compaction { _ => {} } } - Err(Exceptions::FormatException(format!( + Err(Exceptions::FormatException(Some(format!( "Compaction must be 0-3 (inclusivie). Found: {}", value - ))) + )))) } } diff --git a/src/pdf417/encoder/pdf_417.rs b/src/pdf417/encoder/pdf_417.rs index c13eddd..2530f05 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -40,6 +40,12 @@ pub struct PDF417 { minRows: u32, } +impl Default for PDF417 { + fn default() -> Self { + Self::new() + } +} + impl PDF417 { pub fn new() -> Self { Self::with_compact_hint(false) @@ -102,7 +108,7 @@ impl PDF417 { } fn encodeChar(pattern: u32, len: u32, logic: &mut BarcodeRow) { - let mut map = 1 << len - 1; + let mut map = 1 << (len - 1); let mut last = (pattern & map) != 0; //Initialize to inverse of first bit let mut width = 0; for _i in 0..len { @@ -217,10 +223,10 @@ impl PDF417 { //2. step: construct data codewords if sourceCodeWords + errorCorrectionCodeWords + 1 > 929 { // +1 for symbol length CW - return Err(Exceptions::WriterException(format!( + return Err(Exceptions::WriterException(Some(format!( "Encoded message contains too many code words, message too big ({} bytes)", msg.chars().count() - ))); + )))); } let n = sourceCodeWords + pad + 1; let mut sb = String::with_capacity(n as usize); @@ -309,9 +315,9 @@ impl PDF417 { if let Some(dim) = dimension { Ok(dim) } else { - Err(Exceptions::WriterException( + Err(Exceptions::WriterException(Some( "Unable to fit message in columns".to_owned(), - )) + ))) } } diff --git a/src/pdf417/encoder/pdf_417_error_correction.rs b/src/pdf417/encoder/pdf_417_error_correction.rs index 0db181d..813ba4f 100644 --- a/src/pdf417/encoder/pdf_417_error_correction.rs +++ b/src/pdf417/encoder/pdf_417_error_correction.rs @@ -133,12 +133,12 @@ lazy_static! { */ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { if errorCorrectionLevel > 8 { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Error correction level must be between 0 and 8!".to_owned(), - )); + ))); // throw new IllegalArgumentException("Error correction level must be between 0 and 8!"); } - Ok(1 << errorCorrectionLevel + 1) + Ok(1 << (errorCorrectionLevel + 1)) } /** @@ -149,10 +149,10 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result Result { - if n <= 0 { - Err(Exceptions::IllegalArgumentException( + if n == 0 { + Err(Exceptions::IllegalArgumentException(Some( "n must be > 0".to_owned(), - )) + ))) } else if n <= 40 { Ok(2) } else if n <= 160 { @@ -162,9 +162,9 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result Result { let mut encoding = encoding; if msg.is_empty() { - return Err(Exceptions::WriterException( + return Err(Exceptions::WriterException(Some( "Empty message not allowed".to_owned(), - )); + ))); } if encoding.is_none() && !autoECI { for i in 0..msg.chars().count() { // for (int i = 0; i < msg.length(); i++) { if msg.chars().nth(i).unwrap() as u32 > 255 { - return Err(Exceptions::WriterException(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",msg.chars().nth(i).unwrap() as u32,msg.chars().nth(i).unwrap()))); + return Err(Exceptions::WriterException(Some(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",msg.chars().nth(i).unwrap() as u32,msg.chars().nth(i).unwrap())))); } } } @@ -223,7 +223,7 @@ pub fn encodeHighLevel( input = Box::new(NoECIInput::new(msg.to_owned())); if encoding.is_none() { encoding = Some(DEFAULT_ENCODING); - } else if !(DEFAULT_ENCODING.name() == encoding.as_ref().unwrap().name()) { + } else if DEFAULT_ENCODING.name() != encoding.as_ref().unwrap().name() { if let Some(eci) = CharacterSetECI::getCharacterSetECI(encoding.unwrap()) { // if (eci != null) { encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?; @@ -395,20 +395,18 @@ fn encodeText( } else { tmp.push(char::from_u32(ch as u32 - 65).unwrap()); } + } else if isAlphaLower(ch) { + submode = SUBMODE_LOWER; + tmp.push(27 as char); //ll + continue; + } else if isMixed(ch) { + submode = SUBMODE_MIXED; + tmp.push(28 as char); //ml + continue; } else { - if isAlphaLower(ch) { - submode = SUBMODE_LOWER; - tmp.push(27 as char); //ll - continue; - } else if isMixed(ch) { - submode = SUBMODE_MIXED; - tmp.push(28 as char); //ml - continue; - } else { - tmp.push(29 as char); //ps - tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); - //break; - } + tmp.push(29 as char); //ps + tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); + //break; } } // break; @@ -419,49 +417,44 @@ fn encodeText( } else { tmp.push(char::from_u32(ch as u32 - 97).unwrap()); } + } else if isAlphaUpper(ch) { + tmp.push(27 as char); //as + tmp.push(char::from_u32(ch as u32 - 65).unwrap()); + //space cannot happen here, it is also in "Lower" + //break; + } else if isMixed(ch) { + submode = SUBMODE_MIXED; + tmp.push(28 as char); //ml + continue; } else { - if isAlphaUpper(ch) { - tmp.push(27 as char); //as - tmp.push(char::from_u32(ch as u32 - 65).unwrap()); - //space cannot happen here, it is also in "Lower" - //break; - } else if isMixed(ch) { - submode = SUBMODE_MIXED; - tmp.push(28 as char); //ml - continue; - } else { - tmp.push(29 as char); //ps - tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); - //break; - } + tmp.push(29 as char); //ps + tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); + //break; } } // break; SUBMODE_MIXED => { if isMixed(ch) { tmp.push(char::from_u32(MIXED[ch as usize] as u32).unwrap()); + } else if isAlphaUpper(ch) { + submode = SUBMODE_ALPHA; + tmp.push(28 as char); //al + continue; + } else if isAlphaLower(ch) { + submode = SUBMODE_LOWER; + tmp.push(27 as char); //ll + continue; } else { - if isAlphaUpper(ch) { - submode = SUBMODE_ALPHA; - tmp.push(28 as char); //al + if startpos + idx + 1 < count + && !input.isECI(startpos + idx + 1)? + && isPunctuation(input.charAt((startpos + idx + 1) as usize)?) + { + submode = SUBMODE_PUNCTUATION; + tmp.push(25 as char); //pl continue; - } else if isAlphaLower(ch) { - submode = SUBMODE_LOWER; - tmp.push(27 as char); //ll - continue; - } else { - if startpos + idx + 1 < count { - if !input.isECI(startpos + idx + 1)? - && isPunctuation(input.charAt((startpos + idx + 1) as usize)?) - { - submode = SUBMODE_PUNCTUATION; - tmp.push(25 as char); //pl - continue; - } - } - tmp.push(29 as char); //ps - tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); } + tmp.push(29 as char); //ps + tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); } } _ => @@ -530,7 +523,7 @@ fn encodeMultiECIBinary( localEnd += 1; } - let localCount = localEnd - localStart; + let localCount = localEnd as i32 - localStart as i32; if localCount <= 0 { //done break; @@ -539,7 +532,7 @@ fn encodeMultiECIBinary( encodeBinary( &subBytes(input, localStart, localEnd), 0, - localCount, + localCount as u32, if localStart == startpos { startmode } else { @@ -561,7 +554,7 @@ pub fn subBytes(input: &Box, start: u32, end: u32) -> V // for (int i = start; i < end; i++) { result[i - start as usize] = input.charAt(i).unwrap() as u8; } - return result; + result } /** @@ -578,12 +571,10 @@ pub fn subBytes(input: &Box, start: u32, end: u32) -> V fn encodeBinary(bytes: &[u8], startpos: u32, count: u32, startmode: u32, sb: &mut String) { if count == 1 && startmode == TEXT_COMPACTION { sb.push(char::from_u32(SHIFT_TO_BYTE).unwrap()); + } else if (count % 6) == 0 { + sb.push(char::from_u32(LATCH_TO_BYTE).unwrap()); } else { - if (count % 6) == 0 { - sb.push(char::from_u32(LATCH_TO_BYTE).unwrap()); - } else { - sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).unwrap()); - } + sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).unwrap()); } let mut idx = startpos; @@ -597,14 +588,16 @@ fn encodeBinary(bytes: &[u8], startpos: u32, count: u32, startmode: u32, sb: &mu t <<= 8; t += bytes[idx as usize + i as usize] as i64; } - for i in 0..5 { + for ch in &mut chars { + // for i in 0..5 { // for (int i = 0; i < 5; i++) { - chars[i] = char::from_u32((t % 900) as u32).unwrap(); + *ch = char::from_u32((t % 900) as u32).unwrap(); t /= 900; } - for i in (0..chars.len()).rev() { + for ch in chars.into_iter().rev() { + // for i in (0..chars.len()).rev() { // for (int i = chars.length - 1; i >= 0; i--) { - sb.push(chars[i]); + sb.push(ch); } idx += 6; } @@ -639,7 +632,7 @@ fn encodeNumeric(input: &Box, startpos: u32, count: u32 let mut bigint: u128 = part.parse().unwrap(); loop { tmp.push(char::from_u32((bigint % num900) as u32).unwrap()); - bigint = bigint / num900; + bigint /= num900; if bigint == num0 { break; @@ -659,27 +652,27 @@ fn encodeNumeric(input: &Box, startpos: u32, count: u32 } fn isDigit(ch: char) -> bool { - return ch >= '0' && ch <= '9'; + ('0'..='9').contains(&ch) } fn isAlphaUpper(ch: char) -> bool { - return ch == ' ' || (ch >= 'A' && ch <= 'Z'); + ch == ' ' || ('A'..='Z').contains(&ch) } fn isAlphaLower(ch: char) -> bool { - return ch == ' ' || (ch >= 'a' && ch <= 'z'); + ch == ' ' || ('a'..='z').contains(&ch) } fn isMixed(ch: char) -> bool { - return MIXED[ch as usize] != -1; + MIXED[ch as usize] != -1 } fn isPunctuation(ch: char) -> bool { - return PUNCTUATION[ch as usize] != -1; + PUNCTUATION[ch as usize] != -1 } fn isText(ch: char) -> bool { - return ch == '\t' || ch == '\n' || ch == '\r' || (ch as u32 >= 32 && ch as u32 <= 126); + ch == '\t' || ch == '\n' || ch == '\r' || (ch as u32 >= 32 && ch as u32 <= 126) } /** @@ -789,10 +782,10 @@ fn determineConsecutiveBinaryCount( assert!(TypeId::of::() == TypeId::of::()); // assert!(input instanceof NoECIInput); let ch = input.charAt(idx).unwrap(); - return Err(Exceptions::WriterException(format!( + return Err(Exceptions::WriterException(Some(format!( "Non-encodable character detected: {} (Unicode: {})", ch, ch as u32 - ))); + )))); } } idx += 1; @@ -801,7 +794,7 @@ fn determineConsecutiveBinaryCount( } fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> { - if eci >= 0 && eci < 900 { + if (0..900).contains(&eci) { sb.push(char::from_u32(ECI_CHARSET).unwrap()); sb.push(char::from_u32(eci as u32).unwrap()); } else if eci < 810900 { @@ -812,10 +805,10 @@ fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> { sb.push(char::from_u32(ECI_USER_DEFINED).unwrap()); sb.push(char::from_u32((810900 - eci) as u32).unwrap()); } else { - return Err(Exceptions::WriterException(format!( + return Err(Exceptions::WriterException(Some(format!( "ECI number not in valid range from 0..811799, but was {}", eci - ))); + )))); } Ok(()) } @@ -830,7 +823,7 @@ impl ECIInput for NoECIInput { if let Some(ch) = self.0.chars().nth(index) { Ok(ch) } else { - Err(Exceptions::IndexOutOfBoundsException("".to_owned())) + Err(Exceptions::IndexOutOfBoundsException(None)) } } diff --git a/src/pdf417/pdf_417_reader.rs b/src/pdf417/pdf_417_reader.rs index 01675c5..e0ab944 100644 --- a/src/pdf417/pdf_417_reader.rs +++ b/src/pdf417/pdf_417_reader.rs @@ -32,6 +32,7 @@ use super::{ * * @author Guenther Grau */ +#[derive(Default)] pub struct PDF417Reader; impl Reader for PDF417Reader { @@ -57,7 +58,7 @@ impl Reader for PDF417Reader { let result = Self::decode(image, hints, false)?; if result.is_empty() { // if (result.length == 0 || result[0] == null) { - return Err(Exceptions::NotFoundException("".to_owned())); + return Err(Exceptions::NotFoundException(None)); } Ok(result[0].clone()) } @@ -83,12 +84,6 @@ impl MultipleBarcodeReader for PDF417Reader { } } -impl Default for PDF417Reader { - fn default() -> Self { - Self {} - } -} - impl PDF417Reader { pub fn new() -> Self { Self::default() @@ -102,7 +97,7 @@ impl PDF417Reader { let mut results = Vec::new(); //new ArrayList<>(); let detectorRXingResult = detector::detect_with_hints(image, hints, multiple)?; for points in detectorRXingResult.getPoints() { - let points_filtered = points.iter().filter_map(|e| e.clone()).collect(); + let points_filtered = points.iter().filter_map(|e| *e).collect(); // for (RXingResultPoint[] points : detectorRXingResult.getPoints()) { let decoderRXingResult = pdf_417_scanning_decoder::decode( detectorRXingResult.getBits(), diff --git a/src/pdf417/pdf_417_writer.rs b/src/pdf417/pdf_417_writer.rs index 6eb7713..7bb47ec 100644 --- a/src/pdf417/pdf_417_writer.rs +++ b/src/pdf417/pdf_417_writer.rs @@ -36,6 +36,7 @@ const DEFAULT_ERROR_CORRECTION_LEVEL: u32 = 2; * @author Jacob Haynes * @author qwandor@google.com (Andrew Walbran) */ +#[derive(Default)] pub struct PDF417Writer; impl Writer for PDF417Writer { @@ -58,10 +59,10 @@ impl Writer for PDF417Writer { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::PDF_417 { - return Err(Exceptions::IllegalArgumentException(format!( + return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode PDF_417, but got {}", format - ))); + )))); } let mut encoder = PDF417::new(); @@ -209,17 +210,18 @@ impl PDF417Writer { while y < input.len() { // for (int y = 0, yOutput = output.getHeight() - margin - 1; y < input.length; y++, yOutput--) { let inputY = &input[y]; - for x in 0..input[y].len() { + // for x in 0..input[y].len() { + for (x, x_index_val) in inputY.iter().enumerate().take(input[y].len()) { // for (int x = 0; x < input[0].length; x++) { // Zero is white in the byte matrix - if inputY[x] == 1 { + if x_index_val == &1 { output.set(x as u32 + margin, yOutput as u32); } } y += 1; yOutput -= 1; } - return output; + output } /** @@ -232,9 +234,10 @@ impl PDF417Writer { // This makes the direction consistent on screen when rotating the // screen; let inverseii = bitarray.len() - ii - 1; - for jj in 0..bitarray[0].len() { + for (jj, tmp_spot) in temp.iter_mut().enumerate().take(bitarray[0].len()) { + // for jj in 0..bitarray[0].len() { // for (int jj = 0; jj < bitarray[0].length; jj++) { - temp[jj][inverseii] = bitarray[ii][jj]; + tmp_spot[inverseii] = bitarray[ii][jj]; } } @@ -245,12 +248,6 @@ impl PDF417Writer { } } -impl Default for PDF417Writer { - fn default() -> Self { - Self {} - } -} - /** * Tests {@link PDF417Writer}. */ diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index 1593973..ee6e97f 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -165,9 +165,9 @@ impl PlanarYUVLuminanceSource { inverted: bool, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Crop rectangle does not fit within image data.".to_owned(), - )); + ))); } let mut new_s: Self = Self { @@ -200,26 +200,26 @@ impl PlanarYUVLuminanceSource { let output_offset = y * width; for x in 0..width { //for (int x = 0; x < width; x++) { - let grey = yuv[input_offset + x * THUMBNAIL_SCALE_FACTOR] & 0xff; + let grey = yuv[input_offset + x * THUMBNAIL_SCALE_FACTOR]; pixels[output_offset + x] = (0xFF000000 | (grey as u32 * 0x00010101)) as u8; } input_offset += self.data_width * THUMBNAIL_SCALE_FACTOR; } - return pixels; + pixels } /** * @return width of image from {@link #renderThumbnail()} */ pub fn getThumbnailWidth(&self) -> usize { - return self.getWidth() / THUMBNAIL_SCALE_FACTOR; + self.getWidth() / THUMBNAIL_SCALE_FACTOR } /** * @return height of image from {@link #renderThumbnail()} */ pub fn getThumbnailHeight(&self) -> usize { - return self.getHeight() / THUMBNAIL_SCALE_FACTOR; + self.getHeight() / THUMBNAIL_SCALE_FACTOR } fn reverseHorizontal(&mut self, width: usize, height: usize) { @@ -264,7 +264,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { if self.invert { row = self.invert_block_of_bytes(row); } - return row; + row } fn getMatrix(&self) -> Vec { @@ -309,7 +309,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { matrix = self.invert_block_of_bytes(matrix); } - return matrix; + matrix } fn getWidth(&self) -> usize { @@ -321,7 +321,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { } fn isCropSupported(&self) -> bool { - return true; + true } fn crop( @@ -343,12 +343,12 @@ impl LuminanceSource for PlanarYUVLuminanceSource { self.invert, ) { Ok(new) => Ok(Box::new(new)), - Err(_err) => Err(Exceptions::UnsupportedOperationException("".to_owned())), + Err(_err) => Err(Exceptions::UnsupportedOperationException(None)), } } fn isRotateSupported(&self) -> bool { - return false; + false } fn invert(&mut self) { diff --git a/src/qrcode/QRCodeWriterTestCase.rs b/src/qrcode/QRCodeWriterTestCase.rs index c2f32f7..3a1a55d 100644 --- a/src/qrcode/QRCodeWriterTestCase.rs +++ b/src/qrcode/QRCodeWriterTestCase.rs @@ -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] diff --git a/src/qrcode/decoder/VersionTestCase.rs b/src/qrcode/decoder/VersionTestCase.rs index 190d4cb..ba32789 100644 --- a/src/qrcode/decoder/VersionTestCase.rs +++ b/src/qrcode/decoder/VersionTestCase.rs @@ -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); diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index 259052e..27a6e17 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -36,10 +36,10 @@ impl BitMatrixParser { pub fn new(bit_matrix: BitMatrix) -> Result { 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 { 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 diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index 38a783d..9313a2c 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -55,7 +55,7 @@ impl DataBlock { ecLevel: ErrorCorrectionLevel, ) -> Result, 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; } } diff --git a/src/qrcode/decoder/data_mask.rs b/src/qrcode/decoder/data_mask.rs index 4efc467..7d60bbe 100755 --- a/src/qrcode/decoder/data_mask.rs +++ b/src/qrcode/decoder/data_mask.rs @@ -230,10 +230,10 @@ impl TryFrom 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 - ))), + )))), } } } diff --git a/src/qrcode/decoder/decoded_bit_stream_parser.rs b/src/qrcode/decoder/decoded_bit_stream_parser.rs index 65d72fc..c225043 100644 --- a/src/qrcode/decoder/decoded_bit_stream_parser.rs +++ b/src/qrcode/decoder/decoded_bit_stream_parser.rs @@ -37,12 +37,12 @@ const ALPHANUMERIC_CHARS: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" const GB2312_SUBSET: u32 = 1; pub fn decode( - bytes: &Vec, + bytes: &[u8], version: VersionRef, ecLevel: ErrorCorrectionLevel, hints: &DecodingHintDictionary, ) -> Result { - 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 { 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 { return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes); } - Err(Exceptions::FormatException("".to_owned())) + Err(Exceptions::FormatException(None)) } diff --git a/src/qrcode/decoder/decoder.rs b/src/qrcode/decoder/decoder.rs index fbff7f2..26c14b2 100644 --- a/src/qrcode/decoder/decoder.rs +++ b/src/qrcode/decoder/decoder.rs @@ -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 = 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 diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index fc9c9fc..55a8651 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -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::(); - 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 - ))); + )))); } } diff --git a/src/qrcode/decoder/mode.rs b/src/qrcode/decoder/mode.rs index 68fd4e2..b344916 100644 --- a/src/qrcode/decoder/mode.rs +++ b/src/qrcode/decoder/mode.rs @@ -68,10 +68,10 @@ impl Mode { { Ok(Self::HANZI) } - _ => Err(Exceptions::IllegalArgumentException(format!( + _ => Err(Exceptions::IllegalArgumentException(Some(format!( "{} is not valid", bits - ))), + )))), } } diff --git a/src/qrcode/decoder/qr_code_decoder_meta_data.rs b/src/qrcode/decoder/qr_code_decoder_meta_data.rs index 237b334..503fd84 100644 --- a/src/qrcode/decoder/qr_code_decoder_meta_data.rs +++ b/src/qrcode/decoder/qr_code_decoder_meta_data.rs @@ -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. } } diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index 88cd97b..f94cc42 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -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)) } /** diff --git a/src/qrcode/detector/alignment_pattern.rs b/src/qrcode/detector/alignment_pattern.rs index cbe9805..91934a5 100644 --- a/src/qrcode/detector/alignment_pattern.rs +++ b/src/qrcode/detector/alignment_pattern.rs @@ -64,7 +64,7 @@ impl AlignmentPattern { let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs(); return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize; } - return false; + false } /** diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index 2b9d380..b6c64c5 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -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; diff --git a/src/qrcode/detector/detector.rs b/src/qrcode/detector/detector.rs index d4e9514..a3dda4e 100644 --- a/src/qrcode/detector/detector.rs +++ b/src/qrcode/detector/detector.rs @@ -50,7 +50,7 @@ impl<'a> Detector<'_> { } pub fn getImage(&self) -> &BitMatrix { - &self.image + self.image } pub fn getRXingResultPointCallback(&self) -> &Option { @@ -80,16 +80,17 @@ impl<'a> Detector<'_> { &mut self, hints: &DecodingHintDictionary, ) -> Result { - 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 { 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( diff --git a/src/qrcode/detector/detector_test.rs b/src/qrcode/detector/detector_test.rs index d91a0b1..af67639 100644 --- a/src/qrcode/detector/detector_test.rs +++ b/src/qrcode/detector/detector_test.rs @@ -56,5 +56,5 @@ fn make_larger(input: &BitMatrix, factor: u32) -> BitMatrix { } } } - return output; + output } diff --git a/src/qrcode/detector/finder_pattern.rs b/src/qrcode/detector/finder_pattern.rs index 3b7bdb2..c965ff5 100644 --- a/src/qrcode/detector/finder_pattern.rs +++ b/src/qrcode/detector/finder_pattern.rs @@ -77,7 +77,7 @@ impl FinderPattern { let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs(); return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize; } - return false; + false } /** diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 8bbb257..e891412 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -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(); diff --git a/src/qrcode/encoder/EncoderTestCase.rs b/src/qrcode/encoder/EncoderTestCase.rs index e808197..d34c162 100644 --- a/src/qrcode/encoder/EncoderTestCase.rs +++ b/src/qrcode/encoder/EncoderTestCase.rs @@ -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]); } } diff --git a/src/qrcode/encoder/MaskUtilTestCase.rs b/src/qrcode/encoder/MaskUtilTestCase.rs index 5186b51..f881812 100644 --- a/src/qrcode/encoder/MaskUtilTestCase.rs +++ b/src/qrcode/encoder/MaskUtilTestCase.rs @@ -198,7 +198,7 @@ fn testGetDataMaskBitInternal(maskPattern: u32, expected: &Vec>) -> boo } } } - return true; + true } // See mask patterns on the page 43 of JISX0510:2004. diff --git a/src/qrcode/encoder/byte_matrix.rs b/src/qrcode/encoder/byte_matrix.rs index 2c3d43d..7cc9c4a 100644 --- a/src/qrcode/encoder/byte_matrix.rs +++ b/src/qrcode/encoder/byte_matrix.rs @@ -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 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); } } } diff --git a/src/qrcode/encoder/encoder.rs b/src/qrcode/encoder/encoder.rs index f8fe14a..3ec4b46 100644 --- a/src/qrcode/encoder/encoder.rs +++ b/src/qrcode/encoder/encoder.rs @@ -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 { - 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 { // "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 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)?; diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index e047f78..1b18180 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -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>, col: u32, from: i32, to: u32) -> bool { @@ -131,7 +131,7 @@ pub fn isWhiteVertical(array: &Vec>, 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 { - 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 } diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index fe4f307..686e884 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -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 { 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]); diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index 25f6e7b..6fb242a 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -117,7 +117,7 @@ impl MinimalEncoder { .map(|p| p.to_owned()) .collect::>(), 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) -> Result { - 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>>>>, + edges: &mut [Vec>>>], position: usize, edge: Option>, ) { 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>>>>, + edges: &mut [Vec>>>], from: usize, previous: Option>, ) { @@ -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::() //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) -> 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(¤t.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 diff --git a/src/qrcode/encoder/qr_code.rs b/src/qrcode/encoder/qr_code.rs index 63ec2e5..121b14f 100644 --- a/src/qrcode/encoder/qr_code.rs +++ b/src/qrcode/encoder/qr_code.rs @@ -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() + } +} diff --git a/src/qrcode/qr_code_reader.rs b/src/qrcode/qr_code_reader.rs index 225a6f0..f0ecfae 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -64,13 +64,13 @@ impl Reader for QRCodeReader { let mut points: Vec; 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) } diff --git a/src/qrcode/qr_code_writer.rs b/src/qrcode/qr_code_writer.rs index 472e371..115376d 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -58,25 +58,25 @@ impl Writer for QRCodeWriter { hints: &crate::EncodingHintDictionary, ) -> Result { 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 { 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(); } diff --git a/src/result_point_utils.rs b/src/result_point_utils.rs index d11a24a..de5fff4 100644 --- a/src/result_point_utils.rs +++ b/src/result_point_utils.rs @@ -68,12 +68,12 @@ pub fn orderBestPatterns(patterns: &mut [T; 3]) { * @return distance between two points */ pub fn distance(pattern1: &T, pattern2: &T) -> f32 { - return MathUtils::distance_float( + MathUtils::distance_float( pattern1.getX(), pattern1.getY(), pattern2.getX(), pattern2.getY(), - ); + ) } /** @@ -82,6 +82,5 @@ pub fn distance(pattern1: &T, pattern2: &T) -> f32 { pub fn crossProductZ(pointA: T, pointB: T, pointC: T) -> f32 { let bX = pointB.getX(); let bY = pointB.getY(); - return ((pointC.getX() - bX) * (pointA.getY() - bY)) - - ((pointC.getY() - bY) * (pointA.getX() - bX)); + ((pointC.getX() - bX) * (pointA.getY() - bY)) - ((pointC.getY() - bY) * (pointA.getX() - bX)) } diff --git a/src/rgb_luminance_source.rs b/src/rgb_luminance_source.rs index 2e88b8d..59aa994 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -53,7 +53,7 @@ impl LuminanceSource for RGBLuminanceSource { if self.invert { row = self.invert_block_of_bytes(row); } - return row; + row } fn getMatrix(&self) -> Vec { @@ -97,7 +97,7 @@ impl LuminanceSource for RGBLuminanceSource { if self.invert { matrix = self.invert_block_of_bytes(matrix); } - return matrix; + matrix } fn getWidth(&self) -> usize { @@ -109,7 +109,7 @@ impl LuminanceSource for RGBLuminanceSource { } fn isCropSupported(&self) -> bool { - return true; + true } fn crop( @@ -129,7 +129,7 @@ impl LuminanceSource for RGBLuminanceSource { height, ) { Ok(crop) => Ok(Box::new(crop)), - Err(_error) => Err(Exceptions::UnsupportedOperationException("".to_owned())), + Err(_error) => Err(Exceptions::UnsupportedOperationException(None)), } } @@ -139,7 +139,7 @@ impl LuminanceSource for RGBLuminanceSource { } impl RGBLuminanceSource { - pub fn new_with_width_height_pixels(width: usize, height: usize, pixels: &Vec) -> Self { + pub fn new_with_width_height_pixels(width: usize, height: usize, pixels: &[u32]) -> Self { //super(width, height); let dataWidth = width; @@ -166,8 +166,8 @@ impl RGBLuminanceSource { luminances, dataWidth, dataHeight, - left: left, - top: top, + left, + top, width, height, invert: false, @@ -175,7 +175,7 @@ impl RGBLuminanceSource { } fn new_complex( - pixels: &Vec, + pixels: &[u8], data_width: usize, data_height: usize, left: usize, @@ -184,12 +184,12 @@ impl RGBLuminanceSource { height: usize, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::IllegalArgumentException( + return Err(Exceptions::IllegalArgumentException(Some( "Crop rectangle does not fit within image data.".to_owned(), - )); + ))); } Ok(Self { - luminances: pixels.clone(), + luminances: pixels.to_owned(), dataWidth: data_width, dataHeight: data_height, left, diff --git a/src/rxing_result.rs b/src/rxing_result.rs index ccea0d4..a6769e6 100644 --- a/src/rxing_result.rs +++ b/src/rxing_result.rs @@ -82,7 +82,7 @@ impl RXingResult { ) -> Self { Self { text: text.to_owned(), - rawBytes: rawBytes, + rawBytes, numBits, resultPoints, format, @@ -107,14 +107,14 @@ impl RXingResult { * @return raw text encoded by the barcode */ pub fn getText(&self) -> &String { - return &self.text; + &self.text } /** * @return raw bytes encoded by the barcode, if applicable, otherwise {@code null} */ pub fn getRawBytes(&self) -> &Vec { - return &self.rawBytes; + &self.rawBytes } /** @@ -122,7 +122,7 @@ impl RXingResult { * @since 3.3.0 */ pub fn getNumBits(&self) -> usize { - return self.numBits; + self.numBits } /** @@ -131,7 +131,7 @@ impl RXingResult { * specific to the type of barcode that was decoded. */ pub fn getRXingResultPoints(&self) -> &Vec { - return &self.resultPoints; + &self.resultPoints } pub fn getRXingResultPointsMut(&mut self) -> &mut Vec { @@ -142,7 +142,7 @@ impl RXingResult { * @return {@link BarcodeFormat} representing the format of the barcode that was decoded */ pub fn getBarcodeFormat(&self) -> &BarcodeFormat { - return &self.format; + &self.format } /** @@ -153,7 +153,7 @@ impl RXingResult { pub fn getRXingResultMetadata( &self, ) -> &HashMap { - return &self.resultMetadata; + &self.resultMetadata } pub fn putMetadata( @@ -189,7 +189,7 @@ impl RXingResult { } pub fn getTimestamp(&self) -> u128 { - return self.timestamp; + self.timestamp } } diff --git a/src/rxing_result_point.rs b/src/rxing_result_point.rs index 439f670..e1f1305 100644 --- a/src/rxing_result_point.rs +++ b/src/rxing_result_point.rs @@ -34,11 +34,11 @@ impl RXingResultPoint { impl ResultPoint for RXingResultPoint { fn getX(&self) -> f32 { - return self.x; + self.x } fn getY(&self) -> f32 { - return self.y; + self.y } fn into_rxing_result_point(self) -> RXingResultPoint {