diff --git a/src/PlanarYUVLuminanceSourceTestCase.rs b/src/PlanarYUVLuminanceSourceTestCase.rs index d5a96ee..158a84d 100644 --- a/src/PlanarYUVLuminanceSourceTestCase.rs +++ b/src/PlanarYUVLuminanceSourceTestCase.rs @@ -75,7 +75,7 @@ fn test_crop() { .unwrap(); assert!(source.isCropSupported()); let cropMatrix = source.getMatrix(); - for r in 0..ROWS-2 { + for r in 0..ROWS - 2 { // for (int r = 0; r < ROWS - 2; r++) { assert_equals( &Y, @@ -85,7 +85,7 @@ fn test_crop() { COLS - 2, ); } - for r in 0..ROWS-2 { + for r in 0..ROWS - 2 { // for (int r = 0; r < ROWS - 2; r++) { assert_equals( &Y, diff --git a/src/RGBLuminanceSourceTestCase.rs b/src/RGBLuminanceSourceTestCase.rs index 1cf3bf7..bbdfb3e 100644 --- a/src/RGBLuminanceSourceTestCase.rs +++ b/src/RGBLuminanceSourceTestCase.rs @@ -24,49 +24,52 @@ // */ // public final class RGBLuminanceSourceTestCase extends Assert { -use crate::{RGBLuminanceSource, LuminanceSource}; +use crate::{LuminanceSource, RGBLuminanceSource}; - const SRC_DATA : [u32;9] = [0x000000, 0x7F7F7F, 0xFFFFFF, - 0xFF0000, 0x00FF00, 0x0000FF, - 0x0000FF, 0x00FF00, 0xFF0000]; +const SRC_DATA: [u32; 9] = [ + 0x000000, 0x7F7F7F, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0x0000FF, 0x00FF00, 0xFF0000, +]; - #[test] - fn testCrop() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec()); +#[test] +fn testCrop() { + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); assert!(SOURCE.isCropSupported()); let cropped = SOURCE.crop(1, 1, 1, 1).unwrap(); assert_eq!(1, cropped.getHeight()); assert_eq!(1, cropped.getWidth()); - assert_eq!(vec![ 0x7F ], cropped.getRow(0, &vec![0;0])); - } + assert_eq!(vec![0x7F], cropped.getRow(0, &vec![0; 0])); +} - #[test] - fn testMatrix() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec()); +#[test] +fn testMatrix() { + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); - assert_eq!(vec![ 0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F ], - SOURCE.getMatrix()); + assert_eq!( + vec![0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F], + SOURCE.getMatrix() + ); let croppedFullWidth = SOURCE.crop(0, 1, 3, 2).unwrap(); - assert_eq!(vec![ 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F ], - croppedFullWidth.getMatrix()); + assert_eq!( + vec![0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F], + croppedFullWidth.getMatrix() + ); let croppedCorner = SOURCE.crop(1, 1, 2, 2).unwrap(); - assert_eq!(vec![ 0x7F, 0x3F, 0x7F, 0x3F ], - croppedCorner.getMatrix()); - } + assert_eq!(vec![0x7F, 0x3F, 0x7F, 0x3F], croppedCorner.getMatrix()); +} - #[test] - fn testGetRow() { - let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec()); +#[test] +fn testGetRow() { + let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); - assert_eq!(vec![ 0x3F, 0x7F, 0x3F ], SOURCE.getRow(2, &vec![0;3])); - } + assert_eq!(vec![0x3F, 0x7F, 0x3F], SOURCE.getRow(2, &vec![0; 3])); +} - // #[test] - // fn testToString() { - // let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&src_data.to_vec()); +// #[test] +// fn testToString() { +// let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&src_data.to_vec()); - // assert_eq!("#+ \n#+#\n#+#\n", SOURCE.toString()); - // } +// assert_eq!("#+ \n#+#\n#+#\n", SOURCE.toString()); +// } // } diff --git a/src/aztec/EncoderTest.rs b/src/aztec/EncoderTest.rs index 7882222..0653581 100644 --- a/src/aztec/EncoderTest.rs +++ b/src/aztec/EncoderTest.rs @@ -176,8 +176,10 @@ fn testAztecWriter() { ); // Test AztecWriter defaults let data = "In ut magna vel mauris malesuada"; - let writer = AztecWriter{}; - let matrix = writer.encode(data, &BarcodeFormat::AZTEC, 0, 0).expect("matrix must exist"); + let writer = AztecWriter {}; + let matrix = writer + .encode(data, &BarcodeFormat::AZTEC, 0, 0) + .expect("matrix must exist"); let aztec = encoder::encode( data, encoder::DEFAULT_EC_PERCENT, @@ -731,7 +733,8 @@ fn testWriter( EncodeHintType::ERROR_CORRECTION, EncodeHintValue::ErrorCorrection(ecc_percent.to_string()), ); - let mut matrix = AztecWriter{}.encode_with_hints(data, &BarcodeFormat::AZTEC, 0, 0, &hints) + let mut matrix = AztecWriter {} + .encode_with_hints(data, &BarcodeFormat::AZTEC, 0, 0, &hints) .expect("encoder created"); let cset = match charset { diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index 20f9b33..6f43314 100644 --- a/src/aztec/aztec_reader.rs +++ b/src/aztec/aztec_reader.rs @@ -52,8 +52,8 @@ impl Reader for AztecReader { // let notFoundException = None; // let formatException = None; let mut detector = Detector::new(image.getBlackMatrix()?.clone()); - let points; - let decoderRXingResult: DecoderRXingResult; + let points; + let decoderRXingResult: DecoderRXingResult; // try { let detectorRXingResult = if let Ok(det) = detector.detect(false) { diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index dbbddaf..0c050f1 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use std::{ collections::HashMap}; +use std::collections::HashMap; use encoding::EncodingRef; diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index fa6fcd0..7cba097 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -14,11 +14,10 @@ * limitations under the License. */ - use crate::{ common::{ reedsolomon::{ - get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder, GenericGFRef, + get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonDecoder, }, BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult, }, diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index 5095389..910dee2 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -278,10 +278,10 @@ impl Detector { let mut color = true; - self.nb_center_layers = 1; + self.nb_center_layers = 1; while self.nb_center_layers < 9 { - // for nbCenterLayers in 1..9 { + // for nbCenterLayers in 1..9 { // for (nbCenterLayers = 1; nbCenterLayers < 9; nbCenterLayers++) { let pouta = self.get_first_different(&pina, color, 1, -1); let poutb = self.get_first_different(&pinb, color, 1, 1); @@ -319,7 +319,7 @@ impl Detector { color = !color; - self.nb_center_layers+=1; + self.nb_center_layers += 1; } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { @@ -634,8 +634,12 @@ impl Detector { let i_max = d.floor() as u32; //(int) Math.floor(d); for _i in 0..i_max { // for (int i = 0; i < iMax; i++) { - - if self.image.get(MathUtils::round(px) as u32, MathUtils::round(py) as u32) != color_model { + + if self + .image + .get(MathUtils::round(px) as u32, MathUtils::round(py) as u32) + != color_model + { error += 1; } px += dx; diff --git a/src/aztec/encoder/binary_shift_token.rs b/src/aztec/encoder/binary_shift_token.rs index b46654e..4160aa6 100644 --- a/src/aztec/encoder/binary_shift_token.rs +++ b/src/aztec/encoder/binary_shift_token.rs @@ -50,7 +50,9 @@ impl BinaryShiftToken { bit_array.appendBits(bsbc as u32 - 31, 5).unwrap(); } } - bit_array.appendBits(text[self.binary_shift_start as usize + i].into(), 8).expect("should never fail to append"); + bit_array + .appendBits(text[self.binary_shift_start as usize + i].into(), 8) + .expect("should never fail to append"); } } diff --git a/src/aztec/encoder/encoder.rs b/src/aztec/encoder/encoder.rs index c0cd2ed..dfc9857 100644 --- a/src/aztec/encoder/encoder.rs +++ b/src/aztec/encoder/encoder.rs @@ -19,7 +19,7 @@ use encoding::Encoding; use crate::{ common::{ reedsolomon::{ - get_predefined_genericgf, PredefinedGenericGF, ReedSolomonEncoder, GenericGFRef, + get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder, }, BitArray, BitMatrix, }, @@ -157,7 +157,7 @@ pub fn encode_bytes_with_charset( let ecc_bits = bits.getSize() as u32 * min_eccpercent / 100 + 11; let total_size_bits = bits.getSize() as u32 + ecc_bits; let mut compact; - let mut layers:u32; + let mut layers: u32; let mut total_bits_in_layer_var; let mut word_size; let mut stuffed_bits; diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index 766c0fa..e8b9e94 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -127,8 +127,8 @@ impl HighLevelEncoder { char_map[Self::MODE_DIGIT][b'.' as usize] = 13; let mixed_table = [ '\0', ' ', '\u{1}', '\u{2}', '\u{3}', '\u{4}', '\u{5}', '\u{6}', '\u{7}', '\u{8}', - '\t', '\n', '\u{000b}', '\u{000c}', '\r', '\u{001b}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{001f}', - '@', '\\', '^', '_', '`', '|', '~', '\u{007f}', + '\t', '\n', '\u{000b}', '\u{000c}', '\r', '\u{001b}', '\u{001c}', '\u{001d}', + '\u{001e}', '\u{001f}', '@', '\\', '^', '_', '`', '|', '~', '\u{007f}', ]; let mut i = 0; while i < mixed_table.len() { @@ -245,7 +245,8 @@ impl HighLevelEncoder { pub fn encode(&self) -> Result { let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0); if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) { - if eci != CharacterSetECI::ISO8859_1 {//} && eci != CharacterSetECI::Cp1252 { + if eci != CharacterSetECI::ISO8859_1 { + //} && eci != CharacterSetECI::Cp1252 { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { @@ -278,7 +279,7 @@ impl HighLevelEncoder { b':' if next_char == b' ' => 5, _ => 0, }; - + if pair_code > 0 { // We have one of the four special PUNCT pairs. Treat them specially. // Get a new set of states for the two new characters. diff --git a/src/aztec/encoder/mod.rs b/src/aztec/encoder/mod.rs index 3c9fd5c..0769dd0 100644 --- a/src/aztec/encoder/mod.rs +++ b/src/aztec/encoder/mod.rs @@ -1,15 +1,15 @@ mod aztec_code; -mod token; -mod simple_token; mod binary_shift_token; -mod state; mod high_level_encoder; +mod simple_token; +mod state; +mod token; pub mod encoder; pub use aztec_code::*; -pub use token::*; -pub use simple_token::*; pub use binary_shift_token::*; +pub use high_level_encoder::*; +pub use simple_token::*; pub use state::*; -pub use high_level_encoder::*; \ No newline at end of file +pub use token::*; diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index d072ea6..0871fc3 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -78,7 +78,8 @@ impl State { let mut bits_added = 3; /*if eci < 0 { token.add(0, 3); // 0: FNC1 - } else */if eci > 999999 { + } else */ + if eci > 999999 { return Err(Exceptions::IllegalArgumentException( "ECI code must be between 0 and 999999".to_owned(), )); @@ -151,15 +152,16 @@ impl State { bitCount += latch >> 16; mode = HighLevelEncoder::MODE_UPPER as u32; } - 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 + let deltaBitCount = + if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 { + 18 } else { - 8 - } - }; + if self.binary_shift_byte_count == 62 { + 9 + } else { + 8 + } + }; let mut result = State::new( token, mode, @@ -180,7 +182,10 @@ impl State { return self; } let mut token = self.token; - token.addBinaryShift(index - self.binary_shift_byte_count, self.binary_shift_byte_count); + token.addBinaryShift( + index - self.binary_shift_byte_count, + self.binary_shift_byte_count, + ); State::new(token, self.mode, 0, self.bit_count) } @@ -218,7 +223,7 @@ impl State { let mut bit_array = BitArray::new(); // Add each token to the result in forward order for symbol in symbols.into_iter().rev() { - // for i in (0..symbols.len()).rev() { + // for i in (0..symbols.len()).rev() { // for (int i = symbols.size() - 1; i >= 0; i--) { symbol.appendTo(&mut bit_array, text); } diff --git a/src/aztec/encoder/token.rs b/src/aztec/encoder/token.rs index 368c835..1acc189 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -36,7 +36,7 @@ impl TokenType { } } -#[derive(Debug,Clone,PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct Token { tokens: Vec, //current_pointer: usize, @@ -53,13 +53,13 @@ impl Token { // self.current_pointer -= 1; // &self.tokens[self.current_pointer] // } - pub fn add(&mut self, value: i32, bit_count: u32) { + pub fn add(&mut self, value: i32, bit_count: u32) { //self.current_pointer += 1; self.tokens .push(TokenType::Simple(SimpleToken::new(value, bit_count))); // &self.tokens[self.current_pointer] } - pub fn addBinaryShift(&mut self, start: u32, byte_count: u32) { + pub fn addBinaryShift(&mut self, start: u32, byte_count: u32) { //self.current_pointer += 1; self.tokens .push(TokenType::BinaryShift(BinaryShiftToken::new( @@ -78,7 +78,7 @@ impl Iterator for TokenIter { type Item = TokenType; fn next(&mut self) -> Option { - self.src.pop() + self.src.pop() } } diff --git a/src/aztec/mod.rs b/src/aztec/mod.rs index 2a888c8..418da72 100644 --- a/src/aztec/mod.rs +++ b/src/aztec/mod.rs @@ -11,8 +11,8 @@ pub use aztec_writer::*; #[cfg(test)] mod DecoderTest; #[cfg(test)] -mod EncoderTest; -#[cfg(test)] mod DetectorTest; +#[cfg(test)] +mod EncoderTest; -mod shared_test_methods; \ No newline at end of file +mod shared_test_methods; diff --git a/src/aztec/shared_test_methods.rs b/src/aztec/shared_test_methods.rs index c0d75be..b13b81e 100644 --- a/src/aztec/shared_test_methods.rs +++ b/src/aztec/shared_test_methods.rs @@ -5,30 +5,30 @@ use crate::common::BitArray; use lazy_static::lazy_static; lazy_static! { - static ref SPACES: Regex =Regex::new("\\s+").unwrap(); - static ref DOTX: Regex = Regex::new("[^.X]").unwrap(); + static ref SPACES: Regex = Regex::new("\\s+").unwrap(); + static ref DOTX: Regex = Regex::new("[^.X]").unwrap(); } -pub fn toBitArray( bits:&str) -> BitArray{ - let mut ba_in = BitArray::new(); +pub fn toBitArray(bits: &str) -> BitArray { + let mut ba_in = BitArray::new(); let str = DOTX.replace_all(bits, ""); for a_str in str.chars() { - // for (char aStr : str) { + // for (char aStr : str) { ba_in.appendBit(a_str == 'X'); } - + ba_in - } +} - pub fn toBooleanArray( bitArray:&BitArray) ->Vec{ - let mut result = vec![false;bitArray.getSize()]; +pub fn toBooleanArray(bitArray: &BitArray) -> Vec { + let mut result = vec![false; bitArray.getSize()]; for i in 0..result.len() { - // for (int i = 0; i < result.length; i++) { - result[i] = bitArray.get(i); + // for (int i = 0; i < result.length; i++) { + result[i] = bitArray.get(i); } - result - } + result +} - pub fn stripSpace( s:&str) -> String{ +pub fn stripSpace(s: &str) -> String { SPACES.replace_all(s, "").to_string() - } \ No newline at end of file +} diff --git a/src/barcode_format.rs b/src/barcode_format.rs index 501f78e..c09186f 100644 --- a/src/barcode_format.rs +++ b/src/barcode_format.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -74,4 +73,4 @@ pub enum BarcodeFormat { /** UPC/EAN extension format. Not a stand-alone format. */ UPC_EAN_EXTENSION, -} \ No newline at end of file +} diff --git a/src/binarizer.rs b/src/binarizer.rs index b0663e1..ee47a2c 100644 --- a/src/binarizer.rs +++ b/src/binarizer.rs @@ -1,4 +1,3 @@ - /* * Copyright 2009 ZXing authors * @@ -17,7 +16,10 @@ //package com.google.zxing; -use crate::{common::{BitArray, BitMatrix}, Exceptions, LuminanceSource}; +use crate::{ + common::{BitArray, BitMatrix}, + Exceptions, LuminanceSource, +}; /** * This class hierarchy provides a set of methods to convert luminance data to 1 bit data. @@ -73,4 +75,4 @@ pub trait Binarizer { fn getWidth(&self) -> usize; fn getHeight(&self) -> usize; -} \ No newline at end of file +} diff --git a/src/binary_bitmap.rs b/src/binary_bitmap.rs index dfb5044..7045342 100644 --- a/src/binary_bitmap.rs +++ b/src/binary_bitmap.rs @@ -1,4 +1,3 @@ - /* * Copyright 2009 ZXing authors * @@ -19,7 +18,10 @@ use std::fmt; -use crate::{common::{BitMatrix, BitArray}, Exceptions, Binarizer}; +use crate::{ + common::{BitArray, BitMatrix}, + Binarizer, Exceptions, +}; /** * This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects @@ -161,4 +163,4 @@ impl fmt::Display for BinaryBitmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.getBlackMatrix().unwrap()) } -} \ No newline at end of file +} diff --git a/src/buffered_image_luminance_source.rs b/src/buffered_image_luminance_source.rs index bd29f24..c269a88 100644 --- a/src/buffered_image_luminance_source.rs +++ b/src/buffered_image_luminance_source.rs @@ -27,7 +27,7 @@ use imageproc::geometric_transformations::rotate_about_center; use crate::LuminanceSource; // const MINUS_45_IN_RADIANS: f32 = -0.7853981633974483; // Math.toRadians(-45.0) -const MINUS_45_IN_RADIANS : f32 = std::f32::consts::FRAC_PI_4; +const MINUS_45_IN_RADIANS: f32 = std::f32::consts::FRAC_PI_4; /** * This LuminanceSource implementation is meant for J2SE clients and our blackbox unit tests. diff --git a/src/client/mod.rs b/src/client/mod.rs index d11ca02..d4cfe2f 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -1 +1 @@ -pub mod result; \ No newline at end of file +pub mod result; diff --git a/src/client/result/AbstractDoCoMoResultParser.rs b/src/client/result/AbstractDoCoMoResultParser.rs index de76197..796778a 100644 --- a/src/client/result/AbstractDoCoMoResultParser.rs +++ b/src/client/result/AbstractDoCoMoResultParser.rs @@ -13,7 +13,6 @@ // * See the License for the specific language governing permissions and // * limitations under the License. // */ - // package com.google.zxing.client.result; // /** diff --git a/src/client/result/AddressBookAUResultParser.rs b/src/client/result/AddressBookAUResultParser.rs index 6002802..1f409b5 100644 --- a/src/client/result/AddressBookAUResultParser.rs +++ b/src/client/result/AddressBookAUResultParser.rs @@ -62,7 +62,7 @@ pub fn parse(result: &RXingResult) -> Option { Vec::new() }, Vec::new(), - pronunciation.unwrap_or_default(),//"".to_owned(), + pronunciation.unwrap_or_default(), //"".to_owned(), phoneNumbers, Vec::new(), emails, //Vec::new(), diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index 9022977..651efa9 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -117,17 +117,17 @@ impl AddressBookParsedRXingResult { urls: Vec, geo: Vec, ) -> Result { - if phone_numbers.len() != phone_types.len() && phone_types.len() > 0{ + if phone_numbers.len() != phone_types.len() && phone_types.len() > 0 { return Err(Exceptions::IllegalArgumentException( "Phone numbers and types lengths differ".to_owned(), )); } - if emails.len() != email_types.len() && email_types.len() > 0{ + if emails.len() != email_types.len() && email_types.len() > 0 { return Err(Exceptions::IllegalArgumentException( "Emails and types lengths differ".to_owned(), )); } - if addresses.len() != address_types.len() && address_types.len() > 0{ + if addresses.len() != address_types.len() && address_types.len() > 0 { return Err(Exceptions::IllegalArgumentException( "Addresses and types lengths differ".to_owned(), )); diff --git a/src/client/result/BizcardResultParser.rs b/src/client/result/BizcardResultParser.rs index 09a0602..b1933f6 100644 --- a/src/client/result/BizcardResultParser.rs +++ b/src/client/result/BizcardResultParser.rs @@ -46,8 +46,10 @@ pub fn parse(result: &RXingResult) -> Option { let lastName = ResultParser::match_single_do_co_mo_prefixed_field("X:", &rawText, true) .unwrap_or_default(); let fullName = buildName(&firstName, &lastName); - let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true).unwrap_or_default(); - let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true).unwrap_or_default(); + let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true) + .unwrap_or_default(); + let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true) + .unwrap_or_default(); let addresses = ResultParser::match_do_co_mo_prefixed_field("A:", &rawText); let phoneNumber1 = ResultParser::match_single_do_co_mo_prefixed_field("B:", &rawText, true) .unwrap_or_default(); diff --git a/src/client/result/BookmarkDoCoMoResultParser.rs b/src/client/result/BookmarkDoCoMoResultParser.rs index b477cf3..a61d1ea 100644 --- a/src/client/result/BookmarkDoCoMoResultParser.rs +++ b/src/client/result/BookmarkDoCoMoResultParser.rs @@ -20,9 +20,7 @@ use crate::RXingResult; -use super::{ - ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser, -}; +use super::{ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser}; /** * @author Sean Owen @@ -40,7 +38,8 @@ pub fn parse(result: &RXingResult) -> Option { let uri = rawUri?[0].clone(); if URIResultParser::is_basically_valid_uri(&uri) { Some(ParsedClientResult::URIResult(URIParsedRXingResult::new( - uri, title.unwrap_or("".to_owned()), + uri, + title.unwrap_or("".to_owned()), ))) } else { None diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index 64a4dd4..7daf8ff 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -27,16 +27,14 @@ // import java.util.regex.Matcher; // import java.util.regex.Pattern; -use chrono::{ DateTime, NaiveDateTime, TimeZone, Utc}; +use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; use chrono_tz::Tz; -use regex::Regex; use lazy_static::lazy_static; +use regex::Regex; use crate::exceptions::Exceptions; -use super::{ - maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType -}; +use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType}; // const RFC2445_DURATION: &'static str = // "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?"; @@ -49,8 +47,9 @@ const RFC2445_DURATION_FIELD_UNITS: [i64; 5] = [ ]; lazy_static! { - static ref DATE_TIME : Regex = Regex::new("[0-9]{8}(T[0-9]{6}Z?)?").unwrap(); - static ref RFC2445_DURATION: Regex = Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap(); + static ref DATE_TIME: Regex = Regex::new("[0-9]{8}(T[0-9]{6}Z?)?").unwrap(); + static ref RFC2445_DURATION: Regex = + Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap(); } // const DATE_TIME: &'static str = "[0-9]{8}(T[0-9]{6}Z?)?"; diff --git a/src/client/result/CalendarParsedResultTestCase.rs b/src/client/result/CalendarParsedResultTestCase.rs index 27a4059..7b16456 100644 --- a/src/client/result/CalendarParsedResultTestCase.rs +++ b/src/client/result/CalendarParsedResultTestCase.rs @@ -34,7 +34,7 @@ // */ // public final class CalendarParsedRXingResultTestCase extends Assert { -use chrono::{NaiveDateTime}; +use chrono::NaiveDateTime; use crate::{ client::result::{ParsedClientResult, ParsedRXingResultType}, diff --git a/src/client/result/EmailAddressParsedResult.rs b/src/client/result/EmailAddressParsedResult.rs index e735e55..d6b4e87 100644 --- a/src/client/result/EmailAddressParsedResult.rs +++ b/src/client/result/EmailAddressParsedResult.rs @@ -16,7 +16,7 @@ // package com.google.zxing.client.result; -use super::{ ParsedRXingResult, ParsedRXingResultType, ResultParser}; +use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser}; /** * Represents a parsed result that encodes an email message including recipients, subject diff --git a/src/client/result/EmailAddressParsedResultTestCase.rs b/src/client/result/EmailAddressParsedResultTestCase.rs index 6510e61..253719b 100644 --- a/src/client/result/EmailAddressParsedResultTestCase.rs +++ b/src/client/result/EmailAddressParsedResultTestCase.rs @@ -22,7 +22,7 @@ // import org.junit.Test; use crate::{ - client::result::{ParsedClientResult, ParsedRXingResultType, ResultParser, ParsedRXingResult}, + client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType, ResultParser}, BarcodeFormat, RXingResult, }; diff --git a/src/client/result/EmailAddressResultParser.rs b/src/client/result/EmailAddressResultParser.rs index b4af925..d61d30b 100644 --- a/src/client/result/EmailAddressResultParser.rs +++ b/src/client/result/EmailAddressResultParser.rs @@ -27,11 +27,14 @@ use crate::RXingResult; use lazy_static::lazy_static; lazy_static! { - static ref COMMA :Regex = Regex::new(",").unwrap(); - static ref ATEXT_ALPHANUMERIC:Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); + static ref COMMA: Regex = Regex::new(",").unwrap(); + static ref ATEXT_ALPHANUMERIC: Regex = + Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); } -use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddressParsedRXingResult}; +use super::{ + EmailAddressParsedRXingResult, EmailDoCoMoResultParser, ParsedClientResult, ResultParser, +}; /** * Represents a result that encodes an e-mail address, either as a plain address @@ -39,74 +42,100 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr * * @author Sean Owen */ - pub fn parse(result: &RXingResult) -> Option { +pub fn parse(result: &RXingResult) -> Option { // let comma_regex = Regex::new(",").unwrap(); // private static final Pattern COMMA = Pattern.compile(","); let rawText = ResultParser::getMassagedText(result); if rawText.starts_with("mailto:") || rawText.starts_with("MAILTO:") { - // If it starts with mailto:, assume it is definitely trying to be an email address - let mut hostEmail = &rawText[7..]; - if let Some(queryStart) = hostEmail.find('?'){ - hostEmail = &hostEmail[..queryStart]; - } - // int queryStart = hostEmail.indexOf('?'); - // if (queryStart >= 0) { - // hostEmail = hostEmail.substring(0, queryStart); - // } - // try { - let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail){ - res - }else { - return None; + // If it starts with mailto:, assume it is definitely trying to be an email address + let mut hostEmail = &rawText[7..]; + if let Some(queryStart) = hostEmail.find('?') { + hostEmail = &hostEmail[..queryStart]; + } + // int queryStart = hostEmail.indexOf('?'); + // if (queryStart >= 0) { + // hostEmail = hostEmail.substring(0, queryStart); + // } + // try { + let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail) { + res + } else { + return None; }; hostEmail = tmp.as_str(); - // } catch (IllegalArgumentException iae) { - // return null; - // } - let mut tos = if hostEmail.is_empty() { - Vec::new() - }else { - COMMA.split(hostEmail).into_iter().map(|s| s.to_owned()).collect() - }; - // if (!hostEmail.isEmpty()) { - // tos = COMMA.split(hostEmail); - // } - let nameValues = ResultParser::parseNameValuePairs(&rawText); - let mut ccs:Vec = Vec::new(); - let mut bccs:Vec = Vec::new(); - let mut subject = "".to_owned(); - let mut body = "".to_owned(); - if let Some(nv) = nameValues { - // if (nameValues != null) { - if tos.is_empty() { - if let Some(tosString) = nv.get("to"){ - tos = COMMA.split(tosString).into_iter().map(|s| s.to_owned()).collect(); - } - // if tosString != null { - // tos = COMMA.split(tosString); - // } - } - if let Some(ccString) = nv.get("cc"){ - ccs = COMMA.split(ccString).into_iter().map(|s| s.to_owned()).collect(); - } - // if ccString != null { - // ccs = COMMA.split(ccString); + // } catch (IllegalArgumentException iae) { + // return null; // } - if let Some(bccString) = nv.get("bcc"){ - bccs = COMMA.split(bccString).into_iter().map(|s| s.to_owned()).collect(); - } - // if bccString != null { - // bccs = COMMA.split(bccString); + let mut tos = if hostEmail.is_empty() { + Vec::new() + } else { + COMMA + .split(hostEmail) + .into_iter() + .map(|s| s.to_owned()) + .collect() + }; + // if (!hostEmail.isEmpty()) { + // tos = COMMA.split(hostEmail); // } - 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()))); + let nameValues = ResultParser::parseNameValuePairs(&rawText); + let mut ccs: Vec = Vec::new(); + let mut bccs: Vec = Vec::new(); + let mut subject = "".to_owned(); + let mut body = "".to_owned(); + if let Some(nv) = nameValues { + // if (nameValues != null) { + if tos.is_empty() { + if let Some(tosString) = nv.get("to") { + tos = COMMA + .split(tosString) + .into_iter() + .map(|s| s.to_owned()) + .collect(); + } + // if tosString != null { + // tos = COMMA.split(tosString); + // } + } + if let Some(ccString) = nv.get("cc") { + ccs = COMMA + .split(ccString) + .into_iter() + .map(|s| s.to_owned()) + .collect(); + } + // if ccString != null { + // ccs = COMMA.split(ccString); + // } + if let Some(bccString) = nv.get("bcc") { + bccs = COMMA + .split(bccString) + .into_iter() + .map(|s| s.to_owned()) + .collect(); + } + // if bccString != null { + // bccs = COMMA.split(bccString); + // } + 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(), + ), + )); } else { - // let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); - if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText,&ATEXT_ALPHANUMERIC) { - return None; - } - return Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::new(rawText))); + // let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); + if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) { + return None; + } + return Some(ParsedClientResult::EmailResult( + EmailAddressParsedRXingResult::new(rawText), + )); } - } +} diff --git a/src/client/result/EmailDoCoMoResultParser.rs b/src/client/result/EmailDoCoMoResultParser.rs index 36671d4..6bb0611 100644 --- a/src/client/result/EmailDoCoMoResultParser.rs +++ b/src/client/result/EmailDoCoMoResultParser.rs @@ -24,13 +24,13 @@ use regex::Regex; use crate::RXingResult; -use super::{ParsedClientResult, ResultParser, EmailAddressParsedRXingResult}; +use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser}; use lazy_static::lazy_static; lazy_static! { - static ref ATEXT_ALPHANUMERIC :Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); - + static ref ATEXT_ALPHANUMERIC: Regex = + Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); } /** @@ -40,38 +40,41 @@ lazy_static! { * * @author Sean Owen */ - pub fn parse(result: &RXingResult) -> Option { - +pub fn parse(result: &RXingResult) -> Option { let rawText = ResultParser::getMassagedText(result); if !rawText.starts_with("MATMSG:") { - return None; + return None; } let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?; for to in &tos { - if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) { - return None; - } + if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) { + return None; + } } - let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false).unwrap_or_default(); - let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false).unwrap_or_default(); -Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body))) - } + let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false) + .unwrap_or_default(); + let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false) + .unwrap_or_default(); + Some(ParsedClientResult::EmailResult( + EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body), + )) +} - /** - * This implements only the most basic checking for an email address's validity -- that it contains - * an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of - * validity. We want to generally be lenient here since this class is only intended to encapsulate what's - * in a barcode, not "judge" it. - */ - pub fn isBasicallyValidEmailAddress( email:&str, regex:&Regex)-> bool { +/** + * This implements only the most basic checking for an email address's validity -- that it contains + * an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of + * validity. We want to generally be lenient here since this class is only intended to encapsulate what's + * in a barcode, not "judge" it. + */ +pub fn isBasicallyValidEmailAddress(email: &str, regex: &Regex) -> bool { let email_exists = !email.is_empty(); - let email_has_at = matches!(email.find('@'),Some(_)); + let email_has_at = matches!(email.find('@'), Some(_)); let email_alphamatcher = if let Some(mtch) = regex.find(email) { - mtch.start() ==0 && mtch.end() == email.len() - }else{ - false + mtch.start() == 0 && mtch.end() == email.len() + } else { + false }; email_exists && email_alphamatcher && email_has_at // return email != null && ATEXT_ALPHANUMERIC.matcher(email).matches() && email.indexOf('@') >= 0; - } +} diff --git a/src/client/result/ExpandedProductParsedResult.rs b/src/client/result/ExpandedProductParsedResult.rs index afc8f15..7a0a607 100644 --- a/src/client/result/ExpandedProductParsedResult.rs +++ b/src/client/result/ExpandedProductParsedResult.rs @@ -29,7 +29,7 @@ // import java.util.Map; // import java.util.Objects; -use std::{collections::HashMap}; +use std::collections::HashMap; use super::{ParsedRXingResult, ParsedRXingResultType}; diff --git a/src/client/result/ExpandedProductParsedResultTestCase.rs b/src/client/result/ExpandedProductParsedResultTestCase.rs index ee1db08..e751483 100644 --- a/src/client/result/ExpandedProductParsedResultTestCase.rs +++ b/src/client/result/ExpandedProductParsedResultTestCase.rs @@ -42,10 +42,7 @@ use std::collections::HashMap; -use crate::{ - client::result::{ParsedClientResult}, - RXingResult, BarcodeFormat, -}; +use crate::{client::result::ParsedClientResult, BarcodeFormat, RXingResult}; use super::ExpandedProductResultParser; diff --git a/src/client/result/GeoParsedResultTestCase.rs b/src/client/result/GeoParsedResultTestCase.rs index 4453282..e0f023d 100644 --- a/src/client/result/GeoParsedResultTestCase.rs +++ b/src/client/result/GeoParsedResultTestCase.rs @@ -41,7 +41,6 @@ pub fn testGeo1() { //doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1.0,2.0"); // I think 1.0 and 1 and 2.0 and 2 are similar enough here, correct me if i'm wrong. doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1,2"); - } #[test] pub fn testGeo2() { diff --git a/src/client/result/GeoResultParser.rs b/src/client/result/GeoResultParser.rs index f8a7c76..0080cdc 100644 --- a/src/client/result/GeoResultParser.rs +++ b/src/client/result/GeoResultParser.rs @@ -21,12 +21,12 @@ // import java.util.regex.Matcher; // import java.util.regex.Pattern; -use super::{GeoParsedRXingResult, ParsedClientResult, ResultParser}; +use super::{GeoParsedRXingResult, ParsedClientResult, ResultParser}; use lazy_static::lazy_static; lazy_static! { - static ref GEO_URL :regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap(); + 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.]+))?(?:\\?(.*))?"; @@ -42,89 +42,89 @@ const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9 // pub struct GeoRXingResultParser {} // impl RXingResultParser for GeoRXingResultParser { - pub fn parse(theRXingResult: &crate::RXingResult) -> Option { - let rawText = ResultParser::getMassagedText(theRXingResult); +pub fn parse(theRXingResult: &crate::RXingResult) -> Option { + let rawText = ResultParser::getMassagedText(theRXingResult); - if let Some(captures) = GEO_URL.captures(&rawText.to_lowercase()) { - let query = if let Some(q) = captures.get(4) { - q.as_str() - } else { - "" - }; + if let Some(captures) = GEO_URL.captures(&rawText.to_lowercase()) { + let query = if let Some(q) = captures.get(4) { + q.as_str() + } else { + "" + }; - let latitude = if let Some(la) = captures.get(1) { - if let Ok(laf64) = la.as_str().parse::() { - if laf64 > 90.0 || laf64 < -90.0 { - return None; - } - laf64 - } else { + let latitude = if let Some(la) = captures.get(1) { + if let Ok(laf64) = la.as_str().parse::() { + if laf64 > 90.0 || laf64 < -90.0 { return None; } + laf64 } else { return None; - }; - - let longitude = if let Some(lo) = captures.get(2) { - if let Ok(lof64) = lo.as_str().parse::() { - if lof64 > 180.0 || lof64 < -180.0 { - return None; - } - lof64 - } else { - return None; - } - } else { - return None; - }; - - let altitude = if let Some(al) = captures.get(3) { - if let Ok(alf64) = al.as_str().parse::() { - if alf64 < 0.0 { - return None; - } - alf64 - } else { - return None; - } - } else { - 0.0 - }; - // let longitude; - // let altitude; - // try { - // // latitude = Double.parseDouble(matcher.group(1)); - // // if (latitude > 90.0 || latitude < -90.0) { - // // return null; - // // } - // // longitude = Double.parseDouble(matcher.group(2)); - // // if (longitude > 180.0 || longitude < -180.0) { - // // return null; - // // } - // // if (matcher.group(3) == null) { - // // altitude = 0.0; - // // } else { - // // altitude = Double.parseDouble(matcher.group(3)); - // // if (altitude < 0.0) { - // // return null; - // // } - // // } - // } catch (NumberFormatException ignored) { - // return null; - // } - Some(ParsedClientResult::GeoResult(GeoParsedRXingResult::new( - latitude, - longitude, - altitude, - String::from(query), - ))) + } } else { return None; - } + }; - // Matcher matcher = GEO_URL_PATTERN.matcher(rawText); - // if (!matcher.matches()) { + let longitude = if let Some(lo) = captures.get(2) { + if let Ok(lof64) = lo.as_str().parse::() { + if lof64 > 180.0 || lof64 < -180.0 { + return None; + } + lof64 + } else { + return None; + } + } else { + return None; + }; + + let altitude = if let Some(al) = captures.get(3) { + if let Ok(alf64) = al.as_str().parse::() { + if alf64 < 0.0 { + return None; + } + alf64 + } else { + return None; + } + } else { + 0.0 + }; + // let longitude; + // let altitude; + // try { + // // latitude = Double.parseDouble(matcher.group(1)); + // // if (latitude > 90.0 || latitude < -90.0) { + // // return null; + // // } + // // longitude = Double.parseDouble(matcher.group(2)); + // // if (longitude > 180.0 || longitude < -180.0) { + // // return null; + // // } + // // if (matcher.group(3) == null) { + // // altitude = 0.0; + // // } else { + // // altitude = Double.parseDouble(matcher.group(3)); + // // if (altitude < 0.0) { + // // return null; + // // } + // // } + // } catch (NumberFormatException ignored) { // return null; // } + Some(ParsedClientResult::GeoResult(GeoParsedRXingResult::new( + latitude, + longitude, + altitude, + String::from(query), + ))) + } else { + return None; } + + // Matcher matcher = GEO_URL_PATTERN.matcher(rawText); + // if (!matcher.matches()) { + // return null; + // } +} // } diff --git a/src/client/result/ISBNParsedResult.rs b/src/client/result/ISBNParsedResult.rs index 183d5ca..5dc1136 100644 --- a/src/client/result/ISBNParsedResult.rs +++ b/src/client/result/ISBNParsedResult.rs @@ -23,11 +23,10 @@ use super::ParsedRXingResult; * * @author jbreiden@google.com (Jeff Breidenbach) */ -pub struct ISBNParsedRXingResult { - - isbn:String, +pub struct ISBNParsedRXingResult { + isbn: String, } - impl ParsedRXingResult for ISBNParsedRXingResult { +impl ParsedRXingResult for ISBNParsedRXingResult { fn getType(&self) -> super::ParsedRXingResultType { super::ParsedRXingResultType::ISBN } @@ -37,14 +36,12 @@ pub struct ISBNParsedRXingResult { } } - impl ISBNParsedRXingResult { - - pub fn new( isbn:String)->Self { - Self{ isbn } - } - - pub fn getISBN(&self) -> &str{ - &self.isbn - } +impl ISBNParsedRXingResult { + pub fn new(isbn: String) -> Self { + Self { isbn } + } + pub fn getISBN(&self) -> &str { + &self.isbn + } } diff --git a/src/client/result/ISBNResultParser.rs b/src/client/result/ISBNResultParser.rs index f1b0221..09b7cec 100644 --- a/src/client/result/ISBNResultParser.rs +++ b/src/client/result/ISBNResultParser.rs @@ -21,33 +21,35 @@ use crate::BarcodeFormat; -use super::{ ResultParser, ISBNParsedRXingResult, ParsedClientResult}; +use super::{ISBNParsedRXingResult, ParsedClientResult, ResultParser}; /** * Parses strings of digits that represent a ISBN. - * + * * @author jbreiden@google.com (Jeff Breidenbach) */ // pub struct ISBNRXingResultParser {} // impl RXingResultParser for ISBNRXingResultParser { - /** - * See ISBN-13 For Dummies - */ - pub fn parse(theRXingResult: &crate::RXingResult) -> Option { - let format = theRXingResult.getBarcodeFormat(); - if *format != BarcodeFormat::EAN_13 { +/** + * See ISBN-13 For Dummies + */ +pub fn parse(theRXingResult: &crate::RXingResult) -> Option { + let format = theRXingResult.getBarcodeFormat(); + if *format != BarcodeFormat::EAN_13 { return None; - } - let rawText = ResultParser::getMassagedText(theRXingResult); - let length = rawText.len(); - if length != 13 { - return None; - } - if !rawText.starts_with("978") && !rawText.starts_with("979") { - return None; - } - - Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new(rawText))) } + let rawText = ResultParser::getMassagedText(theRXingResult); + let length = rawText.len(); + if length != 13 { + return None; + } + if !rawText.starts_with("978") && !rawText.starts_with("979") { + return None; + } + + Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new( + rawText, + ))) +} // } diff --git a/src/client/result/ParsedResultType.rs b/src/client/result/ParsedResultType.rs index ba6f2bf..4cbd8f5 100644 --- a/src/client/result/ParsedResultType.rs +++ b/src/client/result/ParsedResultType.rs @@ -22,20 +22,18 @@ * * @author Sean Owen */ -#[derive(Debug,PartialEq, Eq,Hash)] +#[derive(Debug, PartialEq, Eq, Hash)] pub enum ParsedRXingResultType { - - ADDRESSBOOK, - EMAIL_ADDRESS, - PRODUCT, - URI, - TEXT, - GEO, - TEL, - SMS, - CALENDAR, - WIFI, - ISBN, - VIN, - + ADDRESSBOOK, + EMAIL_ADDRESS, + PRODUCT, + URI, + TEXT, + GEO, + TEL, + SMS, + CALENDAR, + WIFI, + ISBN, + VIN, } diff --git a/src/client/result/ProductParsedResult.rs b/src/client/result/ProductParsedResult.rs index 2a661cf..7f79a6b 100644 --- a/src/client/result/ProductParsedResult.rs +++ b/src/client/result/ProductParsedResult.rs @@ -23,15 +23,13 @@ use super::{ParsedRXingResult, ParsedRXingResultType}; * * @author dswitkin@google.com (Daniel Switkin) */ -pub struct ProductParsedRXingResult { - - product_id:String, - normalized_product_id:String, - +pub struct ProductParsedRXingResult { + product_id: String, + normalized_product_id: String, } impl ParsedRXingResult for ProductParsedRXingResult { fn getType(&self) -> super::ParsedRXingResultType { - ParsedRXingResultType::PRODUCT + ParsedRXingResultType::PRODUCT } fn getDisplayRXingResult(&self) -> String { @@ -39,23 +37,22 @@ impl ParsedRXingResult for ProductParsedRXingResult { } } impl ProductParsedRXingResult { - pub fn new(product_id:String) -> Self { - Self::with_normalized_id(product_id.clone(), product_id) - } - - pub fn with_normalized_id( product_id: String, normalized_product_id:String) -> Self { - Self{ - product_id, - normalized_product_id, + pub fn new(product_id: String) -> Self { + Self::with_normalized_id(product_id.clone(), product_id) } - } - pub fn getProductID(&self) -> &str{ - &self.product_id - } + pub fn with_normalized_id(product_id: String, normalized_product_id: String) -> Self { + Self { + product_id, + normalized_product_id, + } + } - pub fn getNormalizedProductID(&self) -> &str { - &self.normalized_product_id - } + pub fn getProductID(&self) -> &str { + &self.product_id + } + pub fn getNormalizedProductID(&self) -> &str { + &self.normalized_product_id + } } diff --git a/src/client/result/ProductParsedResultTestCase.rs b/src/client/result/ProductParsedResultTestCase.rs index 46ba362..29f6d36 100644 --- a/src/client/result/ProductParsedResultTestCase.rs +++ b/src/client/result/ProductParsedResultTestCase.rs @@ -27,31 +27,32 @@ * @author Sean Owen */ // public final class ProductParsedRXingResultTestCase extends Assert { - -use crate::{BarcodeFormat, RXingResult, client::result::{ParsedRXingResult, ParsedRXingResultType, ParsedClientResult}}; +use crate::{ + client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType}, + BarcodeFormat, RXingResult, +}; use super::ResultParser; - #[test] - fn test_product() { +#[test] +fn test_product() { do_test("123456789012", "123456789012", BarcodeFormat::UPC_A); do_test("00393157", "00393157", BarcodeFormat::EAN_8); do_test("5051140178499", "5051140178499", BarcodeFormat::EAN_13); do_test("01234565", "012345000065", BarcodeFormat::UPC_E); - } +} - fn do_test( contents:&str, normalized:&str, format:BarcodeFormat) { - let fake_rxing_result = RXingResult::new(contents, Vec::new(), Vec::new(), format); +fn do_test(contents: &str, normalized: &str, format: BarcodeFormat) { + let fake_rxing_result = RXingResult::new(contents, Vec::new(), Vec::new(), format); let result = ResultParser::parseRXingResult(&fake_rxing_result); assert_eq!(ParsedRXingResultType::PRODUCT, result.getType()); if let ParsedClientResult::ProductResult(product_rxing_result) = result { - assert_eq!(contents, product_rxing_result.getProductID()); - assert_eq!(normalized, product_rxing_result.getNormalizedProductID()); - }else{ - panic!("Expected ParsedClientResult::ProductResult") + assert_eq!(contents, product_rxing_result.getProductID()); + assert_eq!(normalized, product_rxing_result.getNormalizedProductID()); + } else { + panic!("Expected ParsedClientResult::ProductResult") } +} - } - -// } \ No newline at end of file +// } diff --git a/src/client/result/ProductResultParser.rs b/src/client/result/ProductResultParser.rs index 1159f12..5269e48 100644 --- a/src/client/result/ProductResultParser.rs +++ b/src/client/result/ProductResultParser.rs @@ -20,38 +20,42 @@ // import com.google.zxing.RXingResult; // import com.google.zxing.oned.UPCEReader; -use crate::{RXingResult, BarcodeFormat}; +use crate::{BarcodeFormat, RXingResult}; use super::{ParsedClientResult, ProductParsedRXingResult, ResultParser}; /** * Parses strings of digits that represent a UPC code. - * + * * @author dswitkin@google.com (Daniel Switkin) */ pub fn parse(result: &RXingResult) -> Option { -// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes. + // Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes. - let format = result.getBarcodeFormat(); - if !(format == &BarcodeFormat::UPC_A || format == &BarcodeFormat::UPC_E || - format == &BarcodeFormat::EAN_8 || format == &BarcodeFormat::EAN_13) { - return None; + let format = result.getBarcodeFormat(); + if !(format == &BarcodeFormat::UPC_A + || format == &BarcodeFormat::UPC_E + || format == &BarcodeFormat::EAN_8 + || format == &BarcodeFormat::EAN_13) + { + return None; } let rawText = ResultParser::getMassagedText(result); if !ResultParser::isStringOfDigits(&rawText, rawText.len()) { - return None; + return None; } - // Not actually checking the checksum again here + // Not actually checking the checksum again here 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 = UPCEReader.convertUPCEtoUPCA(rawText); + unimplemented!("UPCEReader is required to parse this"); + //normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText); } else { - normalizedProductID = rawText.clone(); + normalizedProductID = rawText.clone(); } - Some(ParsedClientResult::ProductResult(ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID))) - -} \ No newline at end of file + Some(ParsedClientResult::ProductResult( + ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID), + )) +} diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index a3ba1dc..0dfcbfb 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -38,9 +38,10 @@ use crate::{exceptions::Exceptions, RXingResult}; use super::{ AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser, BookmarkDoCoMoResultParser, EmailAddressResultParser, EmailDoCoMoResultParser, - ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult, ProductResultParser, SMSMMSResultParser, SMTPResultParser, TelResultParser, - TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser, - VEventResultParser, VINResultParser, WifiResultParser, SMSTOMMSTOResultParser, + ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult, + ProductResultParser, SMSMMSResultParser, SMSTOMMSTOResultParser, SMTPResultParser, + TelResultParser, TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser, + VEventResultParser, VINResultParser, WifiResultParser, }; /** @@ -92,7 +93,7 @@ use super::{ pub type ParserFunction = dyn Fn(&RXingResult) -> Option; lazy_static! { - static ref DIGITS :Regex = Regex::new("\\d+").unwrap(); + static ref DIGITS: Regex = Regex::new("\\d+").unwrap(); } // const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+"); diff --git a/src/client/result/SMSMMSParsedResultTestCase.rs b/src/client/result/SMSMMSParsedResultTestCase.rs index 9689046..0e5fc5b 100644 --- a/src/client/result/SMSMMSParsedResultTestCase.rs +++ b/src/client/result/SMSMMSParsedResultTestCase.rs @@ -84,11 +84,7 @@ fn do_test(contents: &str, number: &str, subject: &str, body: &str, via: &str, p assert_eq!(&vec![number], smsRXingResult.getNumbers()); assert_eq!(subject, smsRXingResult.getSubject()); assert_eq!(body, smsRXingResult.getBody()); - let vec_via = if via.is_empty() { - vec![] - }else { - vec![via] - }; + let vec_via = if via.is_empty() { vec![] } else { vec![via] }; assert_eq!(&vec_via, smsRXingResult.getVias()); assert_eq!(parsedURI, smsRXingResult.getSMSURI()); } else { diff --git a/src/client/result/SMSMMSResultParser.rs b/src/client/result/SMSMMSResultParser.rs index 051d513..4bf47e9 100644 --- a/src/client/result/SMSMMSResultParser.rs +++ b/src/client/result/SMSMMSResultParser.rs @@ -95,7 +95,11 @@ pub fn parse(result: &RXingResult) -> Option { add_number_via( &mut numbers, &mut vias, - &sms_uriwithout_query[(if last_comma > 0 { last_comma + 1} else {last_comma}) as usize..], + &sms_uriwithout_query[(if last_comma > 0 { + last_comma + 1 + } else { + last_comma + }) as usize..], ); Some(ParsedClientResult::SMSResult( @@ -110,7 +114,7 @@ pub fn parse(result: &RXingResult) -> Option { fn add_number_via(numbers: &mut Vec, vias: &mut Vec, number_part: &str) { if number_part.is_empty() { - return + return; } if let Some(number_end) = number_part.find(';') { // if numberEnd < 0 { diff --git a/src/client/result/SMSTOMMSTOResultParser.rs b/src/client/result/SMSTOMMSTOResultParser.rs index 40d22e8..714a170 100644 --- a/src/client/result/SMSTOMMSTOResultParser.rs +++ b/src/client/result/SMSTOMMSTOResultParser.rs @@ -32,25 +32,35 @@ use super::{ParsedClientResult, ResultParser, SMSParsedRXingResult}; * * @author Sean Owen */ - pub fn parse(result:&RXingResult) -> Option { +pub fn parse(result: &RXingResult) -> Option { let rawText = ResultParser::getMassagedText(result); - if !(rawText.starts_with("smsto:") || rawText.starts_with("SMSTO:") || - rawText.starts_with("mmsto:") || rawText.starts_with("MMSTO:")) { - return None; + if !(rawText.starts_with("smsto:") + || rawText.starts_with("SMSTO:") + || rawText.starts_with("mmsto:") + || rawText.starts_with("MMSTO:")) + { + return None; } // Thanks to dominik.wild for suggesting this enhancement to support // smsto:number:body URIs let mut number = &rawText[6..]; let mut body = ""; if let Some(body_start) = number.find(':') { - body = &number[body_start + 1..]; - number = &number[..body_start]; + body = &number[body_start + 1..]; + number = &number[..body_start]; } // let bodyStart = number.indexOf(':'); // if (bodyStart >= 0) { // body = number.substring(bodyStart + 1); // number = number.substring(0, bodyStart); // } - Some(ParsedClientResult::SMSResult(SMSParsedRXingResult::with_singles(number.to_owned(), String::from(""), String::from(""), body.to_owned()))) + Some(ParsedClientResult::SMSResult( + SMSParsedRXingResult::with_singles( + number.to_owned(), + String::from(""), + String::from(""), + body.to_owned(), + ), + )) // return new SMSParsedRXingResult(number, null, null, body); - } \ No newline at end of file +} diff --git a/src/client/result/SMTPResultParser.rs b/src/client/result/SMTPResultParser.rs index 12834bc..c70f841 100644 --- a/src/client/result/SMTPResultParser.rs +++ b/src/client/result/SMTPResultParser.rs @@ -20,7 +20,7 @@ use crate::RXingResult; -use super::{ResultParser, ParsedClientResult, EmailAddressParsedRXingResult}; +use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser}; /** *

Parses an "smtp:" URI result, whose format is not standardized but appears to be like: @@ -31,18 +31,18 @@ use super::{ResultParser, ParsedClientResult, EmailAddressParsedRXingResult}; pub fn parse(result: &RXingResult) -> Option { let rawText = ResultParser::getMassagedText(result); if !(rawText.starts_with("smtp:") || rawText.starts_with("SMTP:")) { - return None; + return None; } let mut emailAddress = &rawText[5..]; let mut subject = ""; let mut body = ""; if let Some(colon) = emailAddress.find(':') { - subject = &emailAddress[colon+1..]; - emailAddress = &emailAddress[..colon]; - if let Some(new_colon) = subject.find(':') { - body = &subject[new_colon+1..]; - subject = &subject[..new_colon]; - } + subject = &emailAddress[colon + 1..]; + emailAddress = &emailAddress[..colon]; + if let Some(new_colon) = subject.find(':') { + body = &subject[new_colon + 1..]; + subject = &subject[..new_colon]; + } } // let colon = emailAddress.indexOf(':'); // if (colon >= 0) { @@ -54,10 +54,18 @@ pub fn parse(result: &RXingResult) -> Option { // subject = subject.substring(0, colon); // } // } - Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(vec![emailAddress.to_owned()],Vec::new(), Vec::new(), subject.to_owned(), body.to_owned()))) + Some(ParsedClientResult::EmailResult( + EmailAddressParsedRXingResult::with_details( + vec![emailAddress.to_owned()], + Vec::new(), + Vec::new(), + subject.to_owned(), + body.to_owned(), + ), + )) // return new EmailAddressParsedRXingResult(new String[] {emailAddress}, // null, // null, // subject, // body); - } +} diff --git a/src/client/result/TelParsedResultTestCase.rs b/src/client/result/TelParsedResultTestCase.rs index 5731545..6bfd407 100644 --- a/src/client/result/TelParsedResultTestCase.rs +++ b/src/client/result/TelParsedResultTestCase.rs @@ -27,12 +27,8 @@ * @author Sean Owen */ // public final class TelParsedRXingResultTestCase extends Assert { - use crate::{ - client::result::{ - ParsedClientResult, ParsedRXingResult, ParsedRXingResultType, - - }, + client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType}, BarcodeFormat, RXingResult, }; diff --git a/src/client/result/TelResultParser.rs b/src/client/result/TelResultParser.rs index b10dffe..023d3fb 100644 --- a/src/client/result/TelResultParser.rs +++ b/src/client/result/TelResultParser.rs @@ -18,7 +18,7 @@ // import com.google.zxing.RXingResult; -use super::{TelParsedRXingResult, ParsedClientResult, ResultParser}; +use super::{ParsedClientResult, ResultParser, TelParsedRXingResult}; /** * Parses a "tel:" URI result, which specifies a phone number. @@ -29,21 +29,29 @@ use super::{TelParsedRXingResult, ParsedClientResult, ResultParser}; // impl RXingResultParser for TelRXingResultParser { - pub fn parse(theRXingResult: &crate::RXingResult) -> Option { - let rawText = ResultParser::getMassagedText(theRXingResult); - if !rawText.starts_with("tel:") && !rawText.starts_with("TEL:") { +pub fn parse(theRXingResult: &crate::RXingResult) -> Option { + let rawText = ResultParser::getMassagedText(theRXingResult); + if !rawText.starts_with("tel:") && !rawText.starts_with("TEL:") { return None; - } - // Normalize "TEL:" to "tel:" - let telURI = if rawText.starts_with("TEL:") {format!("tel:{}", &rawText[4..])} else {rawText.clone()}; - // Drop tel, query portion - let queryStart = rawText[4..].find('?'); - let number = if let Some(v) = queryStart { - &rawText[4..v+4] - }else { - &rawText[4..] - }; - // let number = queryStart < 0 ? : ; - Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(number.to_owned(), telURI.to_owned(), "".to_owned()))) } -// } \ No newline at end of file + // Normalize "TEL:" to "tel:" + let telURI = if rawText.starts_with("TEL:") { + format!("tel:{}", &rawText[4..]) + } else { + rawText.clone() + }; + // Drop tel, query portion + let queryStart = rawText[4..].find('?'); + let number = if let Some(v) = queryStart { + &rawText[4..v + 4] + } else { + &rawText[4..] + }; + // let number = queryStart < 0 ? : ; + Some(ParsedClientResult::TelResult(TelParsedRXingResult::new( + number.to_owned(), + telURI.to_owned(), + "".to_owned(), + ))) +} +// } diff --git a/src/client/result/URIParsedResult.rs b/src/client/result/URIParsedResult.rs index 3befaa1..7b332f7 100644 --- a/src/client/result/URIParsedResult.rs +++ b/src/client/result/URIParsedResult.rs @@ -41,9 +41,9 @@ impl ParsedRXingResult for URIParsedRXingResult { } impl URIParsedRXingResult { pub fn new(uri: String, title: String) -> Self { - Self { - uri: Self::massage_uri(&uri), - title + Self { + uri: Self::massage_uri(&uri), + title, } } @@ -79,8 +79,8 @@ impl URIParsedRXingResult { uri = format!("http://{}", &uri); // uri = updated_uri.as_str() } - }else { - uri = format!("http://{}", &uri); + } else { + uri = format!("http://{}", &uri); } uri diff --git a/src/client/result/URIResultParser.rs b/src/client/result/URIResultParser.rs index 31990c3..8a5d4cb 100644 --- a/src/client/result/URIResultParser.rs +++ b/src/client/result/URIResultParser.rs @@ -21,6 +21,7 @@ // import java.util.regex.Matcher; // import java.util.regex.Pattern; +use lazy_static::lazy_static; /** * Tries to parse results that are a URI of some kind. * @@ -28,17 +29,19 @@ */ // public final class URIRXingResultParser extends RXingResultParser { use regex::Regex; -use lazy_static::lazy_static; use crate::RXingResult; use super::{ParsedClientResult, ResultParser, URIParsedRXingResult}; lazy_static! { - static ref ALLOWED_URI_CHARS :Regex = Regex::new( ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile"); - static ref USER_IN_HOST :Regex = Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile"); - static ref URL_WITH_PROTOCOL_PATTERN : Regex = Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap(); - static ref URL_WITHOUT_PROTOCOL_PATTERN :Regex = Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap(); + static ref ALLOWED_URI_CHARS: Regex = + Regex::new(ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile"); + static ref USER_IN_HOST: Regex = + Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile"); + static ref URL_WITH_PROTOCOL_PATTERN: Regex = Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap(); + static ref URL_WITHOUT_PROTOCOL_PATTERN: Regex = + 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]+"; @@ -79,15 +82,14 @@ pub fn parse(result: &RXingResult) -> Option { * to connect to yourbank.com at first glance. */ 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 { + let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) { + if fnd.start() == 0 && fnd.end() == uri.len() { + true + } else { + false + } + } else { false - } - }else{ - false }; let user = USER_IN_HOST.is_match(uri); diff --git a/src/client/result/VCardResultParser.rs b/src/client/result/VCardResultParser.rs index 2bdf219..21f1ea3 100644 --- a/src/client/result/VCardResultParser.rs +++ b/src/client/result/VCardResultParser.rs @@ -41,14 +41,15 @@ use uriparse::URI; use super::{AddressBookParsedRXingResult, ParsedClientResult, ResultParser}; lazy_static! { - static ref BEGIN_VCARD :Regex= Regex::new("(?i:BEGIN:VCARD)").unwrap(); - static ref VCARD_LIKE_DATE : Regex = Regex::new("\\d{4}-?\\d{2}-?\\d{2}").unwrap(); - static ref CR_LF_SPACE_TAB : Regex = Regex::new("\r\n[ \t]").unwrap(); - static ref NEWLINE_ESCAPE : Regex = Regex::new("\\\\[nN]").unwrap(); - static ref VCARD_ESCAPE : Regex = Regex::new("\\\\([,;\\\\])").unwrap(); - static ref EQUALS : Regex = Regex::new("=").unwrap(); - static ref UNESCAPED_SEMICOLONS : fancy_regex::Regex = fancy_regex::Regex::new("(?= 0 { // Really, end in \r\n + // while (i = rawText.indexOf('\n', i)) >= 0 { // Really, end in \r\n if i < rawText.len() as isize- 1 && // But if followed by tab or space, (rawText.chars().nth(i as usize+ 1)? == ' ' || // this is only a continuation rawText.chars().nth(i as usize+ 1)? == '\t') @@ -262,7 +263,7 @@ pub fn matchVCardPrefixedField( // if matches == null { // matches = new ArrayList<>(1); // lazy init // } - if i >= 1 && rawText.chars().nth(i as usize- 1)? == '\r' { + if i >= 1 && rawText.chars().nth(i as usize - 1)? == '\r' { i -= 1; // Back up over \r, which really should be there } let mut element = rawText[matchStart as usize..i as usize].to_owned(); @@ -293,7 +294,10 @@ pub fn matchVCardPrefixedField( .replace_all(&element, "") .to_mut() .to_owned(); - element = NEWLINE_ESCAPE.replace_all(&element, "\n").to_mut().to_owned(); + element = NEWLINE_ESCAPE + .replace_all(&element, "\n") + .to_mut() + .to_owned(); element = VCARD_ESCAPE.replace_all(&element, "$1").to_mut().to_owned(); // element = CR_LF_SPACE_TAB.matcher(element).replaceAll(""); // element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n"); diff --git a/src/client/result/VEventResultParser.rs b/src/client/result/VEventResultParser.rs index 05d51ae..2840011 100644 --- a/src/client/result/VEventResultParser.rs +++ b/src/client/result/VEventResultParser.rs @@ -131,20 +131,20 @@ fn matchSingleVCardPrefixedField(prefix: &str, rawText: &str) -> String { "".to_owned() } else { let tz_mod = if values.len() > 1 { - if let Some(v) = values.get(values.len()-2) { + if let Some(v) = values.get(values.len() - 2) { if let Some(tz_loc) = v.find("TZID=") { - v[tz_loc+5..].to_owned() - }else { + v[tz_loc + 5..].to_owned() + } else { "".to_owned() } - }else { + } else { "".to_owned() } - }else { + } else { "".to_owned() }; let root_time = values.last().unwrap().clone(); - format!("{}{}",root_time,tz_mod) + format!("{}{}", root_time, tz_mod) } } else { "".to_owned() diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 4249623..11abae3 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -32,7 +32,7 @@ use super::ParsedClientResult; use lazy_static::lazy_static; lazy_static! { - static ref IOQ_MATCHER : Regex = Regex::new(IOQ).unwrap(); + static ref IOQ_MATCHER: Regex = Regex::new(IOQ).unwrap(); static ref AZ09_MATCHER: Regex = Regex::new(AZ09).unwrap(); } @@ -45,7 +45,7 @@ pub fn parse(result: &RXingResult) -> Option { if result.getBarcodeFormat() != &BarcodeFormat::CODE_39 { return None; } - + 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(); diff --git a/src/client/result/WifiParsedResultTestCase.rs b/src/client/result/WifiParsedResultTestCase.rs index 369540d..3f1dd8d 100644 --- a/src/client/result/WifiParsedResultTestCase.rs +++ b/src/client/result/WifiParsedResultTestCase.rs @@ -27,74 +27,139 @@ * @author Vikram Aggarwal */ // public final class WifiParsedRXingResultTestCase extends Assert { - -use crate::{RXingResult, BarcodeFormat, client::result::{ParsedRXingResultType, ParsedRXingResult, ParsedClientResult}}; +use crate::{ + client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType}, + BarcodeFormat, RXingResult, +}; use super::ResultParser; - #[test] - fn testNoPassword() { +#[test] +fn testNoPassword() { doTest("WIFI:S:NoPassword;P:;T:;;", "NoPassword", "", "nopass"); doTest("WIFI:S:No Password;P:;T:;;", "No Password", "", "nopass"); - } +} - #[test] - fn testWep() { - doTest("WIFI:S:TenChars;P:0123456789;T:WEP;;", "TenChars", "0123456789", "WEP"); - doTest("WIFI:S:TenChars;P:abcde56789;T:WEP;;", "TenChars", "abcde56789", "WEP"); +#[test] +fn testWep() { + doTest( + "WIFI:S:TenChars;P:0123456789;T:WEP;;", + "TenChars", + "0123456789", + "WEP", + ); + doTest( + "WIFI:S:TenChars;P:abcde56789;T:WEP;;", + "TenChars", + "abcde56789", + "WEP", + ); // Non hex should not fail at this level - doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP"); + doTest( + "WIFI:S:TenChars;P:hellothere;T:WEP;;", + "TenChars", + "hellothere", + "WEP", + ); // Escaped semicolons - doTest("WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;", "Ten;;Chars", "0123456789", "WEP"); + doTest( + "WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;", + "Ten;;Chars", + "0123456789", + "WEP", + ); // Escaped colons - doTest("WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;", "Ten::Chars", "0123456789", "WEP"); + doTest( + "WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;", + "Ten::Chars", + "0123456789", + "WEP", + ); // TODO(vikrama) Need a test for SB as well. - } +} - /** - * Put in checks for the length of the password for wep. - */ - #[test] - fn testWpa() { +/** + * Put in checks for the length of the password for wep. + */ +#[test] +fn testWpa() { doTest("WIFI:S:TenChars;P:wow;T:WPA;;", "TenChars", "wow", "WPA"); - doTest("WIFI:S:TenChars;P:space is silent;T:WPA;;", "TenChars", "space is silent", "WPA"); - doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP"); + doTest( + "WIFI:S:TenChars;P:space is silent;T:WPA;;", + "TenChars", + "space is silent", + "WPA", + ); + doTest( + "WIFI:S:TenChars;P:hellothere;T:WEP;;", + "TenChars", + "hellothere", + "WEP", + ); // Escaped semicolons - doTest("WIFI:S:TenChars;P:hello\\;there;T:WEP;;", "TenChars", "hello;there", "WEP"); + doTest( + "WIFI:S:TenChars;P:hello\\;there;T:WEP;;", + "TenChars", + "hello;there", + "WEP", + ); // Escaped colons - doTest("WIFI:S:TenChars;P:hello\\:there;T:WEP;;", "TenChars", "hello:there", "WEP"); - } + doTest( + "WIFI:S:TenChars;P:hello\\:there;T:WEP;;", + "TenChars", + "hello:there", + "WEP", + ); +} - #[test] - fn testEscape() { - doTest("WIFI:T:WPA;S:test;P:my_password\\\\;;", "test", "my_password\\", "WPA"); - doTest("WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;", "My_WiFi_SSID", "abc123/", "WPA"); - doTest("WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;", "\"foo;bar\\baz\"", "", "WPA"); - doTest("WIFI:T:WPA;S:test;P:\\\"abcd\\\";;", "test", "\"abcd\"", "WPA"); - } +#[test] +fn testEscape() { + doTest( + "WIFI:T:WPA;S:test;P:my_password\\\\;;", + "test", + "my_password\\", + "WPA", + ); + doTest( + "WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;", + "My_WiFi_SSID", + "abc123/", + "WPA", + ); + doTest( + "WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;", + "\"foo;bar\\baz\"", + "", + "WPA", + ); + doTest( + "WIFI:T:WPA;S:test;P:\\\"abcd\\\";;", + "test", + "\"abcd\"", + "WPA", + ); +} - /** - * Given the string contents for the barcode, check that it matches our expectations - */ - fn doTest( contents:&str, - ssid:&str, - password:&str, - n_type:&str) { - let fakeRXingResult = RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE); +/** + * Given the string contents for the barcode, check that it matches our expectations + */ +fn doTest(contents: &str, ssid: &str, password: &str, n_type: &str) { + let fakeRXingResult = + RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE); let result = ResultParser::parseRXingResult(&fakeRXingResult); // Ensure it is a wifi code assert_eq!(ParsedRXingResultType::WIFI, result.getType()); - - if let ParsedClientResult::WiFiResult(wifiRXingResult) = result{ - assert_eq!(ssid, wifiRXingResult.getSsid()); - assert_eq!(password, wifiRXingResult.getPassword()); - assert_eq!(n_type, wifiRXingResult.getNetworkEncryption()); - }else { - panic!("Expected WIFI"); + + if let ParsedClientResult::WiFiResult(wifiRXingResult) = result { + assert_eq!(ssid, wifiRXingResult.getSsid()); + assert_eq!(password, wifiRXingResult.getPassword()); + assert_eq!(n_type, wifiRXingResult.getNetworkEncryption()); + } else { + panic!("Expected WIFI"); } - } +} // } diff --git a/src/client/result/WifiResultParser.rs b/src/client/result/WifiResultParser.rs index c38a95a..1e71527 100644 --- a/src/client/result/WifiResultParser.rs +++ b/src/client/result/WifiResultParser.rs @@ -18,9 +18,9 @@ // import com.google.zxing.RXingResult; -use crate::client::result::{WifiParsedRXingResult, ParsedClientResult}; +use crate::client::result::{ParsedClientResult, WifiParsedRXingResult}; -use super::{ResultParser}; +use super::ResultParser; // @SuppressWarnings("checkstyle:lineLength") /** @@ -43,46 +43,65 @@ use super::{ResultParser}; // pub struct WifiRXingResultParser {} // impl RXingResultParser for WifiRXingResultParser { - pub fn parse(theRXingResult: &crate::RXingResult) -> Option { - const WIFI_TEST : &'static str = "WIFI:"; +pub fn parse(theRXingResult: &crate::RXingResult) -> Option { + const WIFI_TEST: &'static str = "WIFI:"; - let rawText_unstripped = ResultParser::getMassagedText(theRXingResult); - if !rawText_unstripped.starts_with(WIFI_TEST) { + let rawText_unstripped = ResultParser::getMassagedText(theRXingResult); + if !rawText_unstripped.starts_with(WIFI_TEST) { return None; - } - let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned(); - let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false).unwrap_or(String::from("")); - if ssid.is_empty() { + } + let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned(); + let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false) + .unwrap_or(String::from("")); + if ssid.is_empty() { return None; - } - let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false).unwrap_or(String::from("")); - let n_type = if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false){ - nt - }else { - String::from("nopass") - }; - - // Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'. - // To try to retain backwards compatibility, we set one or the other based on whether the string - // is 'true' or 'false': - let mut hidden = false; - let mut phase2Method = ResultParser::matchSinglePrefixedField("PH2:", &rawText, ';', false); - let hValue = if let Some(hv) = ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false){ + } + let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false) + .unwrap_or(String::from("")); + let n_type = + if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) { + nt + } else { + String::from("nopass") + }; + + // Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'. + // To try to retain backwards compatibility, we set one or the other based on whether the string + // is 'true' or 'false': + let mut hidden = false; + let mut phase2Method = ResultParser::matchSinglePrefixedField("PH2:", &rawText, ';', false); + let hValue = if let Some(hv) = + ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false) + { // If PH2 was specified separately, or if the value is clearly boolean, interpret it as 'hidden' if phase2Method.is_some() || "true" == hv.to_lowercase() || "false" == hv.to_lowercase() { - hidden = hv.parse().unwrap();//Boolean.parseBoolean(hValue); + hidden = hv.parse().unwrap(); //Boolean.parseBoolean(hValue); } else { - phase2Method = Some(hv.clone()); + phase2Method = Some(hv.clone()); } hv - }else { + } else { String::from("") - }; - - let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false).unwrap_or(String::from("")); - let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false).unwrap_or(String::from("")); - let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false).unwrap_or(String::from("")); - - Some(ParsedClientResult::WiFiResult(WifiParsedRXingResult::with_details(n_type, ssid, pass, hidden, identity, anonymousIdentity, eapMethod, phase2Method.unwrap_or(String::from(""))))) - } + }; + + let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false) + .unwrap_or(String::from("")); + let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false) + .unwrap_or(String::from("")); + let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false) + .unwrap_or(String::from("")); + + Some(ParsedClientResult::WiFiResult( + WifiParsedRXingResult::with_details( + n_type, + ssid, + pass, + hidden, + identity, + anonymousIdentity, + eapMethod, + phase2Method.unwrap_or(String::from("")), + ), + )) +} // } diff --git a/src/client/result/mod.rs b/src/client/result/mod.rs index 2dbb20a..880e84a 100644 --- a/src/client/result/mod.rs +++ b/src/client/result/mod.rs @@ -1,48 +1,48 @@ -mod ParsedResult; -mod ResultParser; -mod TelParsedResult; -mod TextParsedResult; -mod ParsedResultType; -mod TelResultParser; -mod ISBNParsedResult; -mod ISBNResultParser; -mod WifiParsedResult; -mod WifiResultParser; -mod GeoResultParser; -mod GeoParsedResult; -mod SMSParsedResult; -mod SMSMMSResultParser; -mod ProductParsedResult; -mod ProductResultParser; -mod URIParsedResult; -mod URIResultParser; -mod URLTOResultParser; mod AbstractDoCoMoResultParser; +mod AddressBookAUResultParser; +mod AddressBookDoCoMoResultParser; +mod AddressBookParsedResult; +mod BizcardResultParser; mod BookmarkDoCoMoResultParser; -mod SMSTOMMSTOResultParser; +mod CalendarParsedResult; mod EmailAddressParsedResult; mod EmailAddressResultParser; mod EmailDoCoMoResultParser; -mod SMTPResultParser; -mod VINParsedResult; -mod VINResultParser; -mod AddressBookParsedResult; -mod AddressBookDoCoMoResultParser; -mod AddressBookAUResultParser; -mod VCardResultParser; -mod BizcardResultParser; -mod CalendarParsedResult; -mod VEventResultParser; mod ExpandedProductParsedResult; mod ExpandedProductResultParser; +mod GeoParsedResult; +mod GeoResultParser; +mod ISBNParsedResult; +mod ISBNResultParser; +mod ParsedResult; +mod ParsedResultType; +mod ProductParsedResult; +mod ProductResultParser; +mod ResultParser; +mod SMSMMSResultParser; +mod SMSParsedResult; +mod SMSTOMMSTOResultParser; +mod SMTPResultParser; +mod TelParsedResult; +mod TelResultParser; +mod TextParsedResult; +mod URIParsedResult; +mod URIResultParser; +mod URLTOResultParser; +mod VCardResultParser; +mod VEventResultParser; +mod VINParsedResult; +mod VINResultParser; +mod WifiParsedResult; +mod WifiResultParser; use std::fmt; +pub use ParsedResult::*; pub use ParsedResultType::*; pub use ResultParser::*; pub use TelParsedResult::*; pub use TextParsedResult::*; -pub use ParsedResult::*; // pub use TelResultParser::*; pub use ISBNParsedResult::*; // pub use ISBNResultParser::*; @@ -50,42 +50,42 @@ pub use WifiParsedResult::*; // pub use WifiResultParser::*; pub use GeoParsedResult::*; // pub use GeoResultParser::*; -pub use SMSParsedResult::*; -pub use ProductParsedResult::*; -pub use URIParsedResult::*; -pub use EmailAddressParsedResult::*; -pub use VINParsedResult::*; pub use AddressBookParsedResult::*; pub use CalendarParsedResult::*; pub use CalendarParsedResult::*; +pub use EmailAddressParsedResult::*; pub use ExpandedProductParsedResult::*; +pub use ProductParsedResult::*; +pub use SMSParsedResult::*; +pub use URIParsedResult::*; +pub use VINParsedResult::*; -#[cfg(test)] -mod TelParsedResultTestCase; -#[cfg(test)] -mod ISBNParsedResultTestCase; -#[cfg(test)] -mod WifiParsedResultTestCase; -#[cfg(test)] -mod GeoParsedResultTestCase; -#[cfg(test)] -mod SMSMMSParsedResultTestCase; -#[cfg(test)] -mod ProductParsedResultTestCase; -#[cfg(test)] -mod URIParsedResultTestCase; -#[cfg(test)] -mod EmailAddressParsedResultTestCase; -#[cfg(test)] -mod VINParsedResultTestCase; #[cfg(test)] mod AddressBookParsedResultTestCase; #[cfg(test)] mod CalendarParsedResultTestCase; #[cfg(test)] +mod EmailAddressParsedResultTestCase; +#[cfg(test)] mod ExpandedProductParsedResultTestCase; #[cfg(test)] +mod GeoParsedResultTestCase; +#[cfg(test)] +mod ISBNParsedResultTestCase; +#[cfg(test)] mod ParsedReaderResultTestCase; +#[cfg(test)] +mod ProductParsedResultTestCase; +#[cfg(test)] +mod SMSMMSParsedResultTestCase; +#[cfg(test)] +mod TelParsedResultTestCase; +#[cfg(test)] +mod URIParsedResultTestCase; +#[cfg(test)] +mod VINParsedResultTestCase; +#[cfg(test)] +mod WifiParsedResultTestCase; pub enum ParsedClientResult { TextResult(TextParsedRXingResult), @@ -143,6 +143,6 @@ impl ParsedRXingResult for ParsedClientResult { impl fmt::Display for ParsedClientResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f,"{}", self.getDisplayRXingResult()) + write!(f, "{}", self.getDisplayRXingResult()) } -} \ No newline at end of file +} diff --git a/src/common/BitArrayTestCase.rs b/src/common/BitArrayTestCase.rs index a7ce007..efd5252 100644 --- a/src/common/BitArrayTestCase.rs +++ b/src/common/BitArrayTestCase.rs @@ -29,127 +29,126 @@ use super::BitArray; use rand::Rng; - #[test] - fn test_get_set() { - let mut array = BitArray::with_size(33); +#[test] +fn test_get_set() { + let mut array = BitArray::with_size(33); for i in 0..33 { - // for (int i = 0; i < 33; i++) { - assert!(!array.get(i)); - array.set(i); - assert!(array.get(i)); + // for (int i = 0; i < 33; i++) { + assert!(!array.get(i)); + array.set(i); + assert!(array.get(i)); } - } +} - #[test] - fn test_get_next_set1() { - let array = BitArray::with_size(32); +#[test] +fn test_get_next_set1() { + let array = BitArray::with_size(32); for i in 0..array.getSize() { - // for (int i = 0; i < array.getSize(); i++) { - assert_eq!( 32, array.getNextSet(i), "{}", i); + // for (int i = 0; i < array.getSize(); i++) { + assert_eq!(32, array.getNextSet(i), "{}", i); } - let array = BitArray::with_size(33); - for i in 0..array.getSize(){ - // for (int i = 0; i < array.getSize(); i++) { - assert_eq!( 33, array.getNextSet(i), "{}", i); + let array = BitArray::with_size(33); + for i in 0..array.getSize() { + // for (int i = 0; i < array.getSize(); i++) { + assert_eq!(33, array.getNextSet(i), "{}", i); } - } - - #[test] - fn test_get_next_set2() { - let mut array = BitArray::with_size(33); - array.set(31); - for i in 0 ..array.getSize() { - // for (int i = 0; i < array.getSize(); i++) { - assert_eq!(if i <= 31 { 31} else {33}, array.getNextSet(i), "{}", i); - } - array = BitArray::with_size(33); - array.set(32); - for i in 0 ..array.getSize(){ - // for (int i = 0; i < array.getSize(); i++) { - assert_eq!(32, array.getNextSet(i), "{}", i); - } - } - - #[test] - fn test_get_next_set3() { - let mut array = BitArray::with_size(63); - array.set(31); - array.set(32); - for i in 0 .. array.getSize() { - // for (int i = 0; i < array.getSize(); i++) { - let expected; - if i <= 31 { - expected = 31; - } else if i == 32 { - expected = 32; - } else { - expected = 63; - } - assert_eq!(expected, array.getNextSet(i), "{}", i); - } - } +} - #[test] - fn test_get_next_set4() { - let mut array = BitArray::with_size(63); +#[test] +fn test_get_next_set2() { + let mut array = BitArray::with_size(33); + array.set(31); + for i in 0..array.getSize() { + // for (int i = 0; i < array.getSize(); i++) { + assert_eq!(if i <= 31 { 31 } else { 33 }, array.getNextSet(i), "{}", i); + } + array = BitArray::with_size(33); + array.set(32); + for i in 0..array.getSize() { + // for (int i = 0; i < array.getSize(); i++) { + assert_eq!(32, array.getNextSet(i), "{}", i); + } +} + +#[test] +fn test_get_next_set3() { + let mut array = BitArray::with_size(63); + array.set(31); + array.set(32); + for i in 0..array.getSize() { + // for (int i = 0; i < array.getSize(); i++) { + let expected; + if i <= 31 { + expected = 31; + } else if i == 32 { + expected = 32; + } else { + expected = 63; + } + assert_eq!(expected, array.getNextSet(i), "{}", i); + } +} + +#[test] +fn test_get_next_set4() { + let mut array = BitArray::with_size(63); array.set(33); array.set(40); - for i in 0..array.getSize(){ - // for (int i = 0; i < array.getSize(); i++) { - let expected; - if i <= 33 { - expected = 33; - } else if i <= 40 { - expected = 40; - } else { - expected = 63; - } - assert_eq!( expected, array.getNextSet(i), "{}", i); - } - } - - #[test] - fn test_get_next_set5() { - let mut r = rand::thread_rng(); - for _i in 0 .. 10 { - // for (int i = 0; i < 10; i++) { - let mut array = BitArray::with_size(1 + r.gen_range(0..100)); - let numSet = r.gen_range(0..20); - for _j in 0..numSet { - // for (int j = 0; j < numSet; j++) { - array.set(r.gen_range(0..array.getSize())); - } - let numQueries = r.gen_range(0..20); - for _j in 0..numQueries { - // for (int j = 0; j < numQueries; j++) { - let query = r.gen_range(0..array.getSize()); - let mut expected = query; - while expected < array.getSize() && !array.get(expected) { - expected+=1; + for i in 0..array.getSize() { + // for (int i = 0; i < array.getSize(); i++) { + let expected; + if i <= 33 { + expected = 33; + } else if i <= 40 { + expected = 40; + } else { + expected = 63; } - let actual = array.getNextSet(query); - assert_eq!(expected, actual); - } + assert_eq!(expected, array.getNextSet(i), "{}", i); } - } +} +#[test] +fn test_get_next_set5() { + let mut r = rand::thread_rng(); + for _i in 0..10 { + // for (int i = 0; i < 10; i++) { + let mut array = BitArray::with_size(1 + r.gen_range(0..100)); + let numSet = r.gen_range(0..20); + for _j in 0..numSet { + // for (int j = 0; j < numSet; j++) { + array.set(r.gen_range(0..array.getSize())); + } + let numQueries = r.gen_range(0..20); + for _j in 0..numQueries { + // for (int j = 0; j < numQueries; j++) { + let query = r.gen_range(0..array.getSize()); + let mut expected = query; + while expected < array.getSize() && !array.get(expected) { + expected += 1; + } + let actual = array.getNextSet(query); + assert_eq!(expected, actual); + } + } +} - #[test] - fn test_set_bulk() { - let mut array = BitArray::with_size(64); +#[test] +fn test_set_bulk() { + let mut array = BitArray::with_size(64); array.setBulk(32, 0xFFFF0000); for i in 0..48 { - // for (int i = 0; i < 48; i++) { - assert!(!array.get(i)); + // for (int i = 0; i < 48; i++) { + assert!(!array.get(i)); } for i in 48..64 { - // for (int i = 48; i < 64; i++) { - assert!(array.get(i)); + // for (int i = 48; i < 64; i++) { + assert!(array.get(i)); } - } +} - #[test] - fn test_append_bit(){ +#[test] +fn test_append_bit() { let mut array = BitArray::new(); array.appendBits(0x000001E, 6).expect("must append)"); let mut array_2 = BitArray::new(); @@ -161,57 +160,57 @@ use rand::Rng; array_2.appendBit(false); assert_eq!(array, array_2) - } +} - #[test] - fn test_set_range() { - let mut array = BitArray::with_size(64); +#[test] +fn test_set_range() { + let mut array = BitArray::with_size(64); array.setRange(28, 36).unwrap(); assert!(!array.get(27)); for i in 28..36 { - // for (int i = 28; i < 36; i++) { - assert!(array.get(i)); + // for (int i = 28; i < 36; i++) { + assert!(array.get(i)); } assert!(!array.get(36)); - } +} - #[test] - fn test_clear() { - let mut array = BitArray::with_size(32); +#[test] +fn test_clear() { + let mut array = BitArray::with_size(32); for i in 0..32 { - // for (int i = 0; i < 32; i++) { - array.set(i); + // for (int i = 0; i < 32; i++) { + array.set(i); } array.clear(); for i in 0..32 { - // for (int i = 0; i < 32; i++) { - assert!(!array.get(i)); + // for (int i = 0; i < 32; i++) { + assert!(!array.get(i)); } - } +} - #[test] - fn test_flip() { - let mut array = BitArray::with_size(32); +#[test] +fn test_flip() { + let mut array = BitArray::with_size(32); assert!(!array.get(5)); array.flip(5); assert!(array.get(5)); array.flip(5); assert!(!array.get(5)); - } +} - #[test] - fn test_get_array() { - let mut array = BitArray::with_size(64); +#[test] +fn test_get_array() { + let mut array = BitArray::with_size(64); array.set(0); array.set(63); let ints = array.getBitArray(); assert_eq!(1, ints[0]); assert_eq!(0b10_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00, ints[1]); - } +} - #[test] - fn test_is_range() { - let mut array = BitArray::with_size(64); +#[test] +fn test_is_range() { + let mut array = BitArray::with_size(64); assert!(array.isRange(0, 64, false).unwrap()); assert!(!array.isRange(0, 64, true).unwrap()); array.set(32); @@ -221,42 +220,46 @@ use rand::Rng; array.set(34); assert!(!array.isRange(31, 35, true).unwrap()); for i in 0..31 { - // for (int i = 0; i < 31; i++) { - array.set(i); + // for (int i = 0; i < 31; i++) { + array.set(i); } assert!(array.isRange(0, 33, true).unwrap()); for i in 33..64 { - // for (int i = 33; i < 64; i++) { - array.set(i); + // for (int i = 33; i < 64; i++) { + array.set(i); } assert!(array.isRange(0, 64, true).unwrap()); assert!(!array.isRange(0, 64, false).unwrap()); - } +} - #[test] - fn reverse_algorithm_test() { - let oldBits:Vec = vec![128, 256, 512, 6453324, 50934953]; +#[test] +fn reverse_algorithm_test() { + let oldBits: Vec = vec![128, 256, 512, 6453324, 50934953]; for size in 1..160 { - // for (int size = 1; size < 160; size++) { - let newBitsOriginal = reverse_original(&oldBits.clone(), size); - let mut newBitArray = BitArray::with_initial_values(oldBits.clone(), size); - newBitArray.reverse(); - let newBitsNew = newBitArray.getBitArray(); - assert!(arrays_are_equal(&newBitsOriginal, &newBitsNew, size / 32 + 1)); + // for (int size = 1; size < 160; size++) { + let newBitsOriginal = reverse_original(&oldBits.clone(), size); + let mut newBitArray = BitArray::with_initial_values(oldBits.clone(), size); + newBitArray.reverse(); + let newBitsNew = newBitArray.getBitArray(); + assert!(arrays_are_equal( + &newBitsOriginal, + &newBitsNew, + size / 32 + 1 + )); } - } +} - #[test] - fn test_clone() { - let array = BitArray::with_size(32); +#[test] +fn test_clone() { + let array = BitArray::with_size(32); array.clone().set(0); assert!(!array.get(0)); - } +} - #[test] - fn test_equals() { - let mut a = BitArray::with_size(32); - let mut b = BitArray::with_size(32); +#[test] +fn test_equals() { + let mut a = BitArray::with_size(32); + let mut b = BitArray::with_size(32); assert_eq!(a, b); // assert_eq!(a.hash(), b.hash()); assert_ne!(a, BitArray::with_size(31)); @@ -266,31 +269,31 @@ use rand::Rng; b.set(16); assert_eq!(a, b); // assert_eq!(a.hash(), b.hash()); - } +} - fn reverse_original( oldBits:&[u32], size:usize) -> Vec{ - let mut newBits = vec![0;oldBits.len()]; +fn reverse_original(oldBits: &[u32], size: usize) -> Vec { + let mut newBits = vec![0; oldBits.len()]; 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); - } + // for (int i = 0; i < size; i++) { + if bit_set(oldBits, size - i - 1) { + newBits[i / 32 as usize] |= 1 << (i & 0x1F); + } } return newBits; - } +} - fn bit_set( bits:&[u32], i:usize) -> bool{ +fn bit_set(bits: &[u32], i: usize) -> bool { return (bits[i / 32] & (1 << (i & 0x1F))) != 0; - } +} - fn arrays_are_equal( left :&[u32], right:&[u32], size:usize) -> bool{ +fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool { for i in 0..size { - // for (int i = 0; i < size; i++) { - if left[i] != right[i] { - return false; - } + // for (int i = 0; i < size; i++) { + if left[i] != right[i] { + return false; + } } return true; - } +} // } diff --git a/src/common/BitMatrixTestCase.rs b/src/common/BitMatrixTestCase.rs index 81f3527..1a3ac71 100644 --- a/src/common/BitMatrixTestCase.rs +++ b/src/common/BitMatrixTestCase.rs @@ -31,74 +31,74 @@ use crate::common::BitArray; use super::BitMatrix; - static BIT_MATRIX_POINTS : [u32;6] = [ 1, 2, 2, 0, 3, 1 ]; +static BIT_MATRIX_POINTS: [u32; 6] = [1, 2, 2, 0, 3, 1]; - #[test] - fn test_get_set() { - let mut matrix = BitMatrix::with_single_dimension(33); +#[test] +fn test_get_set() { + let mut matrix = BitMatrix::with_single_dimension(33); assert_eq!(33, matrix.getHeight()); for y in 0..33 { - // for (int y = 0; y < 33; y++) { - for x in 0..33 { - // for (int x = 0; x < 33; x++) { - if y * x % 3 == 0 { - matrix.set(x, y); + // for (int y = 0; y < 33; y++) { + for x in 0..33 { + // for (int x = 0; x < 33; x++) { + if y * x % 3 == 0 { + matrix.set(x, y); + } } - } } for y in 0..33 { - // for (int y = 0; y < 33; y++) { - for x in 0..33 { - // for (int x = 0; x < 33; x++) { - assert_eq!(y * x % 3 == 0, matrix.get(x, y)); - } + // for (int y = 0; y < 33; y++) { + for x in 0..33 { + // for (int x = 0; x < 33; x++) { + assert_eq!(y * x % 3 == 0, matrix.get(x, y)); + } } - } +} - #[test] - fn test_set_region() { - let mut matrix = BitMatrix::with_single_dimension(5); +#[test] +fn test_set_region() { + let mut matrix = BitMatrix::with_single_dimension(5); matrix.setRegion(1, 1, 3, 3).expect("must set"); for y in 0..5 { - // 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)); - } + // 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)); + } } - } +} - #[test] - fn test_enclosing() { - let mut matrix = BitMatrix::with_single_dimension(5); +#[test] +fn test_enclosing() { + let mut matrix = BitMatrix::with_single_dimension(5); assert!(matrix.getEnclosingRectangle().is_none()); matrix.setRegion(1, 1, 1, 1).expect("must set"); - assert_eq!(vec![ 1, 1, 1, 1 ], matrix.getEnclosingRectangle().unwrap()); + assert_eq!(vec![1, 1, 1, 1], matrix.getEnclosingRectangle().unwrap()); matrix.setRegion(1, 1, 3, 2).expect("must set"); - assert_eq!(vec![ 1, 1, 3, 2 ], matrix.getEnclosingRectangle().unwrap()); + assert_eq!(vec![1, 1, 3, 2], matrix.getEnclosingRectangle().unwrap()); matrix.setRegion(0, 0, 5, 5).expect("must set"); - assert_eq!(vec![ 0, 0, 5, 5 ], matrix.getEnclosingRectangle().unwrap()); - } + assert_eq!(vec![0, 0, 5, 5], matrix.getEnclosingRectangle().unwrap()); +} - #[test] - fn test_on_bit() { - let mut matrix = BitMatrix::with_single_dimension(5); +#[test] +fn test_on_bit() { + let mut matrix = BitMatrix::with_single_dimension(5); assert!(matrix.getTopLeftOnBit().is_none()); assert!(matrix.getBottomRightOnBit().is_none()); matrix.setRegion(1, 1, 1, 1).expect("must set"); - assert_eq!(vec![ 1, 1 ], matrix.getTopLeftOnBit().unwrap()); - assert_eq!(vec![ 1, 1 ], matrix.getBottomRightOnBit().unwrap()); + assert_eq!(vec![1, 1], matrix.getTopLeftOnBit().unwrap()); + assert_eq!(vec![1, 1], matrix.getBottomRightOnBit().unwrap()); matrix.setRegion(1, 1, 3, 2).expect("must set"); - assert_eq!(vec![ 1, 1 ], matrix.getTopLeftOnBit().unwrap()); - assert_eq!(vec![ 3, 2 ], matrix.getBottomRightOnBit().unwrap()); + assert_eq!(vec![1, 1], matrix.getTopLeftOnBit().unwrap()); + assert_eq!(vec![3, 2], matrix.getBottomRightOnBit().unwrap()); matrix.setRegion(0, 0, 5, 5).expect("must set"); - assert_eq!(vec![ 0, 0 ], matrix.getTopLeftOnBit().unwrap()); - assert_eq!(vec![ 4, 4 ], matrix.getBottomRightOnBit().unwrap()); - } + assert_eq!(vec![0, 0], matrix.getTopLeftOnBit().unwrap()); + assert_eq!(vec![4, 4], matrix.getBottomRightOnBit().unwrap()); +} - #[test] - fn test_rectangular_matrix() { - let mut matrix = BitMatrix::new(75, 20).unwrap(); +#[test] +fn test_rectangular_matrix() { + let mut matrix = BitMatrix::new(75, 20).unwrap(); assert_eq!(75, matrix.getWidth()); assert_eq!(20, matrix.getHeight()); matrix.set(10, 0); @@ -121,33 +121,33 @@ use super::BitMatrix; matrix.flip_coords(51, 3); assert!(!matrix.get(50, 2)); assert!(!matrix.get(51, 3)); - } +} - #[test] - fn test_rectangular_set_region() { - let mut matrix = BitMatrix::new(320, 240).unwrap(); +#[test] +fn test_rectangular_set_region() { + let mut matrix = BitMatrix::new(320, 240).unwrap(); assert_eq!(320, matrix.getWidth()); assert_eq!(240, matrix.getHeight()); matrix.setRegion(105, 22, 80, 12).expect("must set"); // Only bits in the region should be on for y in 0..240 { - // 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)); - } + // 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)); + } } - } +} - #[test] - fn test_get_row() { - let mut matrix = BitMatrix::new(102, 5).unwrap(); +#[test] +fn test_get_row() { + let mut matrix = BitMatrix::new(102, 5).unwrap(); for x in 0..102 { - // for (int x = 0; x < 102; x++) { - if (x & 0x03) == 0 { - matrix.set(x, 2); - } + // for (int x = 0; x < 102; x++) { + if (x & 0x03) == 0 { + matrix.set(x, 2); + } } // Should allocate @@ -155,27 +155,27 @@ use super::BitMatrix; assert_eq!(102, array.getSize()); // Should reallocate - let mut array2 = BitArray::with_size(60); + let mut array2 = BitArray::with_size(60); array2 = matrix.getRow(2, &array2); assert_eq!(102, array2.getSize()); // Should use provided object, with original BitArray size - let mut array3 = BitArray::with_size(200); + let mut array3 = BitArray::with_size(200); array3 = matrix.getRow(2, &array3); assert_eq!(200, array3.getSize()); for x in 0..102 { - // for (int x = 0; x < 102; x++) { - let on = (x & 0x03) == 0; - assert_eq!(on, array.get(x)); - assert_eq!(on, array2.get(x)); - assert_eq!(on, array3.get(x)); + // for (int x = 0; x < 102; x++) { + let on = (x & 0x03) == 0; + assert_eq!(on, array.get(x)); + assert_eq!(on, array2.get(x)); + assert_eq!(on, array3.get(x)); } - } +} - #[test] - fn test_rotate90_simple() { - let mut matrix = BitMatrix::new(3, 3).unwrap(); +#[test] +fn test_rotate90_simple() { + let mut matrix = BitMatrix::new(3, 3).unwrap(); matrix.set(0, 0); matrix.set(0, 1); matrix.set(1, 2); @@ -187,11 +187,11 @@ use super::BitMatrix; assert!(matrix.get(1, 2)); assert!(matrix.get(2, 1)); assert!(matrix.get(1, 0)); - } +} - #[test] - fn test_rotate180_simple() { - let mut matrix = BitMatrix::new(3, 3).unwrap(); +#[test] +fn test_rotate180_simple() { + let mut matrix = BitMatrix::new(3, 3).unwrap(); matrix.set(0, 0); matrix.set(0, 1); matrix.set(1, 2); @@ -203,85 +203,108 @@ use super::BitMatrix; assert!(matrix.get(2, 1)); assert!(matrix.get(1, 0)); assert!(matrix.get(0, 1)); - } +} - #[test] - fn test_rotate180_case() { +#[test] +fn test_rotate180_case() { test_rotate_180(7, 4); test_rotate_180(7, 5); test_rotate_180(8, 4); test_rotate_180(8, 5); - } +} - #[test] - fn test_parse() { - let emptyMatrix = BitMatrix::new(3, 3).unwrap(); - let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); +#[test] +fn test_parse() { + let emptyMatrix = BitMatrix::new(3, 3).unwrap(); + let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); fullMatrix.setRegion(0, 0, 3, 3).expect("must set"); - let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); + let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); centerMatrix.setRegion(1, 1, 1, 1).expect("must set"); - let emptyMatrix24 = BitMatrix::new(2, 4).unwrap(); + let emptyMatrix24 = BitMatrix::new(2, 4).unwrap(); - assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \n \n", "x", " ").unwrap()); - assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \r\r\n \n\r", "x", " ").unwrap()); - assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \n ", "x", " ").unwrap()); + assert_eq!( + emptyMatrix, + BitMatrix::parse_strings(" \n \n \n", "x", " ").unwrap() + ); + assert_eq!( + emptyMatrix, + BitMatrix::parse_strings(" \n \r\r\n \n\r", "x", " ").unwrap() + ); + assert_eq!( + emptyMatrix, + BitMatrix::parse_strings(" \n \n ", "x", " ").unwrap() + ); - assert_eq!(fullMatrix, BitMatrix::parse_strings("xxx\nxxx\nxxx\n", "x", " ").unwrap()); + assert_eq!( + fullMatrix, + BitMatrix::parse_strings("xxx\nxxx\nxxx\n", "x", " ").unwrap() + ); - assert_eq!(centerMatrix, BitMatrix::parse_strings(" \n x \n \n", "x", " ").unwrap()); - assert_eq!(centerMatrix, BitMatrix::parse_strings(" \n x \n \n", "x ", " ").unwrap()); - - assert!(BitMatrix::parse_strings(" \n xy\n \n", "x", " ").is_err()); - + assert_eq!( + centerMatrix, + BitMatrix::parse_strings(" \n x \n \n", "x", " ").unwrap() + ); + assert_eq!( + centerMatrix, + BitMatrix::parse_strings(" \n x \n \n", "x ", " ").unwrap() + ); - assert_eq!(emptyMatrix24, BitMatrix::parse_strings(" \n \n \n \n", "x", " ").unwrap()); + assert!(BitMatrix::parse_strings(" \n xy\n \n", "x", " ").is_err()); - assert_eq!(centerMatrix, BitMatrix::parse_strings(¢erMatrix.toString("x", "."), "x", ".").unwrap()); - } + assert_eq!( + emptyMatrix24, + BitMatrix::parse_strings(" \n \n \n \n", "x", " ").unwrap() + ); - #[test] - fn test_parse_boolean() { - let emptyMatrix = BitMatrix::new(3, 3).unwrap(); - let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); + assert_eq!( + centerMatrix, + BitMatrix::parse_strings(¢erMatrix.toString("x", "."), "x", ".").unwrap() + ); +} + +#[test] +fn test_parse_boolean() { + let emptyMatrix = BitMatrix::new(3, 3).unwrap(); + let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); fullMatrix.setRegion(0, 0, 3, 3).expect("must set"); - let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); + let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); centerMatrix.setRegion(1, 1, 1, 1).expect("must set"); - let emptyMatrix24 = BitMatrix::new(2, 4).unwrap(); + let emptyMatrix24 = BitMatrix::new(2, 4).unwrap(); - let mut matrix = vec![vec![false;3];3]; + let mut matrix = vec![vec![false; 3]; 3]; // boolean[][] matrix = new boolean[3][3]; assert_eq!(emptyMatrix, BitMatrix::parse_bools(&matrix)); matrix[1][1] = true; assert_eq!(centerMatrix, BitMatrix::parse_bools(&matrix)); for arr in matrix.iter_mut() { - // for (boolean[] arr : matrix) { - arr[..].clone_from_slice(&[true, true, true]) + // for (boolean[] arr : matrix) { + arr[..].clone_from_slice(&[true, true, true]) } assert_eq!(fullMatrix, BitMatrix::parse_bools(&matrix)); - } +} - #[test] - fn test_unset() { +#[test] +fn test_unset() { let emptyMatrix = BitMatrix::new(3, 3).unwrap(); - let mut matrix = emptyMatrix.clone(); + let mut matrix = emptyMatrix.clone(); matrix.set(1, 1); assert_ne!(emptyMatrix, matrix); matrix.unset(1, 1); assert_eq!(emptyMatrix, matrix); matrix.unset(1, 1); assert_eq!(emptyMatrix, matrix); - } +} - #[test] - fn test_xor_case() { - let emptyMatrix = BitMatrix::new(3, 3).unwrap(); - let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); +#[test] +fn test_xor_case() { + let emptyMatrix = BitMatrix::new(3, 3).unwrap(); + let mut fullMatrix = BitMatrix::new(3, 3).unwrap(); fullMatrix.setRegion(0, 0, 3, 3).expect("must set"); - let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); + let mut centerMatrix = BitMatrix::new(3, 3).unwrap(); centerMatrix.setRegion(1, 1, 1, 1).expect("must set"); - let mut invertedCenterMatrix = fullMatrix.clone(); + let mut invertedCenterMatrix = fullMatrix.clone(); invertedCenterMatrix.unset(1, 1); - let badMatrix = BitMatrix::new(4, 4).unwrap(); + let badMatrix = BitMatrix::new(4, 4).unwrap(); test_XOR(&emptyMatrix, &emptyMatrix, &emptyMatrix); test_XOR(&emptyMatrix, ¢erMatrix, ¢erMatrix); @@ -314,58 +337,61 @@ use super::BitMatrix; // } catch (IllegalArgumentException ex) { // // good // } - } +} - fn matrix_to_string( result:&BitMatrix) -> String{ +fn matrix_to_string(result: &BitMatrix) -> String { assert_eq!(1, result.getHeight()); - let mut builder = String::with_capacity(result.getWidth().try_into().unwrap()); + let mut builder = String::with_capacity(result.getWidth().try_into().unwrap()); for i in 0..result.getWidth() { - // for (int i = 0; i < result.getWidth(); i++) { - builder.push(if result.get(i, 0) {'1'} else {'0'}); + // for (int i = 0; i < result.getWidth(); i++) { + builder.push(if result.get(i, 0) { '1' } else { '0' }); } return builder; - } +} - fn test_XOR( dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) { +fn test_XOR(dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) { let mut matrix = dataMatrix.clone(); matrix.xor(flipMatrix).expect("must set"); assert_eq!(*expectedMatrix, matrix); - } +} - fn test_rotate_180( width:u32, height:u32) { - let mut input = get_input(width, height); +fn test_rotate_180(width: u32, height: u32) { + let mut input = get_input(width, height); input.rotate180(); let expected = get_expected(width, height); - for y in 0..height{ - // for (int y = 0; y < height; y++) { - for x in 0..width{ - // for (int x = 0; x < width; x++) { - assert_eq!( expected.get(x, y), input.get(x, y), "({},{})", x, y); - } + for y in 0..height { + // for (int y = 0; y < height; y++) { + for x in 0..width { + // for (int x = 0; x < width; x++) { + assert_eq!(expected.get(x, y), input.get(x, y), "({},{})", x, y); + } } - } +} - fn get_expected( width:u32, height:u32) -> BitMatrix{ - let mut result = BitMatrix::new(width, height).unwrap(); +fn get_expected(width: u32, height: u32) -> BitMatrix { + let mut result = BitMatrix::new(width, height).unwrap(); let mut i = 0; while i < BIT_MATRIX_POINTS.len() { - // for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) { - result.set(width - 1 - BIT_MATRIX_POINTS[i], height - 1 - BIT_MATRIX_POINTS[i + 1]); - i += 2; + // for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) { + result.set( + width - 1 - BIT_MATRIX_POINTS[i], + height - 1 - BIT_MATRIX_POINTS[i + 1], + ); + i += 2; } return result; - } +} - fn get_input( width:u32, height:u32) -> BitMatrix{ - let mut result = BitMatrix::new(width, height).unwrap(); +fn get_input(width: u32, height: u32) -> BitMatrix { + let mut result = BitMatrix::new(width, height).unwrap(); let mut i = 0; - while i < BIT_MATRIX_POINTS.len(){ - // for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) { - result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]); - i+=2; + while i < BIT_MATRIX_POINTS.len() { + // for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) { + result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]); + i += 2; } return result; - } +} // } diff --git a/src/common/BitSourceTestCase.rs b/src/common/BitSourceTestCase.rs index 00a1727..d754693 100644 --- a/src/common/BitSourceTestCase.rs +++ b/src/common/BitSourceTestCase.rs @@ -26,10 +26,10 @@ use super::BitSource; - #[test] - fn test_source() { - let bytes:Vec = vec![ 1, 2, 3, 4, 5]; - let mut source = BitSource::new(bytes); +#[test] +fn test_source() { + let bytes: Vec = vec![1, 2, 3, 4, 5]; + let mut source = BitSource::new(bytes); assert_eq!(40, source.available()); assert_eq!(0, source.readBits(1).unwrap()); assert_eq!(39, source.available()); @@ -45,6 +45,6 @@ use super::BitSource; assert_eq!(6, source.available()); assert_eq!(5, source.readBits(6).unwrap()); assert_eq!(0, source.available()); - } +} -// } \ No newline at end of file +// } diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 42ac843..ac7225d 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -19,7 +18,7 @@ // import java.util.Arrays; -use std::{fmt, cmp}; +use std::{cmp, fmt}; use crate::Exceptions; @@ -402,4 +401,4 @@ impl fmt::Display for BitArray { } write!(f, "{}", _str) } -} \ No newline at end of file +} diff --git a/src/common/bit_matrix.rs b/src/common/bit_matrix.rs index b7a0520..d7a53e0 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -393,7 +392,7 @@ impl BitMatrix { pub fn rotate180(&mut self) { let mut topRow = BitArray::with_size(self.width as usize); let mut bottomRow = BitArray::with_size(self.width as usize); - let maxHeight = (self.height + 1) / 2; + let maxHeight = (self.height + 1) / 2; for i in 0..maxHeight { //for (int i = 0; i < maxHeight; i++) { topRow = self.getRow(i, &topRow); @@ -410,9 +409,9 @@ impl BitMatrix { * Modifies this {@code BitMatrix} to represent the same but rotated 90 degrees counterclockwise */ pub fn rotate90(&mut self) { - let newWidth = self.height; - let newHeight = self.width; - let newRowSize = (newWidth + 31) / 32; + let newWidth = self.height; + let newHeight = self.width; + let newRowSize = (newWidth + 31) / 32; let mut newBits = vec![0; (newRowSize * newHeight).try_into().unwrap()]; for y in 0..self.height { @@ -625,4 +624,4 @@ impl fmt::Display for BitMatrix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.toString("X ", " ")) } -} \ No newline at end of file +} diff --git a/src/common/bit_source.rs b/src/common/bit_source.rs index 9e0cbba..efbcad2 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -122,4 +121,4 @@ impl BitSource { pub fn available(&self) -> usize { return 8 * (self.bytes.len() - self.byte_offset) - self.bit_offset; } -} \ No newline at end of file +} diff --git a/src/common/bit_source_builder.rs b/src/common/bit_source_builder.rs index fd6f34c..8826556 100644 --- a/src/common/bit_source_builder.rs +++ b/src/common/bit_source_builder.rs @@ -1,4 +1,3 @@ - /* * Copyright 2008 ZXing authors * @@ -65,4 +64,4 @@ impl BitSourceBuilder { } &self.output } -} \ No newline at end of file +} diff --git a/src/common/character_set_eci.rs b/src/common/character_set_eci.rs index 2d8c511..e04f265 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -1,4 +1,3 @@ - /* * Copyright 2008 ZXing authors * @@ -286,4 +285,4 @@ impl CharacterSetECI { _ => None, } } -} \ No newline at end of file +} diff --git a/src/common/decoder_rxing_result.rs b/src/common/decoder_rxing_result.rs index 9c39c3b..a8e2a4e 100644 --- a/src/common/decoder_rxing_result.rs +++ b/src/common/decoder_rxing_result.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -206,4 +205,4 @@ impl DecoderRXingResult { pub fn getSymbologyModifier(&self) -> u32 { self.symbologyModifier } -} \ No newline at end of file +} diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index eeaf523..807c6b6 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -21,7 +20,7 @@ use crate::Exceptions; -use super::{BitMatrix, PerspectiveTransform, GridSampler}; +use super::{BitMatrix, GridSampler, PerspectiveTransform}; /** * @author Sean Owen @@ -118,4 +117,4 @@ impl GridSampler for DefaultGridSampler { } return Ok(bits); } -} \ No newline at end of file +} diff --git a/src/common/detector/mod.rs b/src/common/detector/mod.rs index 833577a..fcd6de6 100644 --- a/src/common/detector/mod.rs +++ b/src/common/detector/mod.rs @@ -4,4 +4,4 @@ mod monochrome_rectangle_detector; pub use monochrome_rectangle_detector::*; mod white_rectangle_detector; -pub use white_rectangle_detector::*; \ No newline at end of file +pub use white_rectangle_detector::*; diff --git a/src/common/detector/monochrome_rectangle_detector.rs b/src/common/detector/monochrome_rectangle_detector.rs index 648af26..bd27d97 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -16,7 +16,7 @@ //package com.google.zxing.common.detector; -use crate::{Exceptions, RXingResultPoint, common::BitMatrix, ResultPoint}; +use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; /** *

A somewhat generic detector that looks for a barcode-like rectangular region within an image. @@ -34,7 +34,9 @@ pub struct MonochromeRectangleDetector { impl MonochromeRectangleDetector { pub fn new(image: &BitMatrix) -> Self { - Self { image: image.clone() } + Self { + image: image.clone(), + } } /** @@ -50,7 +52,7 @@ impl MonochromeRectangleDetector { pub fn detect(&self) -> Result, Exceptions> { let height = self.image.getHeight() as i32; let width = self.image.getWidth() as i32; - let halfHeight= height / 2; + 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)); @@ -168,48 +170,37 @@ impl MonochromeRectangleDetector { } if range.is_none() { if let Some(lastRange) = lastRange_z { - // lastRange was found - if deltaX == 0 { - let lastY = y - deltaY; - if lastRange[0] < centerX { - 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, - lastY as f32, - )); + // lastRange was found + if deltaX == 0 { + let lastY = y - deltaY; + if lastRange[0] < centerX { + 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, + lastY as f32, + )); + } + return Ok(RXingResultPoint::new(lastRange[0] as f32, lastY as f32)); + } else { + return Ok(RXingResultPoint::new(lastRange[1] as f32, lastY as f32)); } - return Ok(RXingResultPoint::new( - lastRange[0] as f32, - lastY as f32, - )); } else { - return Ok(RXingResultPoint::new( - lastRange[1] as f32, - lastY as f32, - )); - } - } else { - let lastX = x - deltaX; - if lastRange[0] < centerY { - if lastRange[1] > centerY { - return Ok(RXingResultPoint::new( - lastX as f32, - lastRange[if deltaX < 0 { 0 } else { 1 }] as f32, - )); + let lastX = x - deltaX; + if lastRange[0] < centerY { + if lastRange[1] > centerY { + return Ok(RXingResultPoint::new( + lastX as f32, + lastRange[if deltaX < 0 { 0 } else { 1 }] as f32, + )); + } + return Ok(RXingResultPoint::new(lastX as f32, lastRange[0] as f32)); + } else { + return Ok(RXingResultPoint::new(lastX as f32, lastRange[1] as f32)); } - return Ok(RXingResultPoint::new( - lastX as f32, - lastRange[0] as f32, - )); - } else { - return Ok(RXingResultPoint::new( - lastX as f32, - lastRange[1] as f32, - )); } } - }}else { + } else { return Err(Exceptions::NotFoundException("".to_owned())); } lastRange_z = range; @@ -309,4 +300,4 @@ impl MonochromeRectangleDetector { None }; } -} \ No newline at end of file +} diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index f9cd1d9..8b16976 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -16,7 +16,7 @@ //package com.google.zxing.common.detector; -use crate::{RXingResultPoint, Exceptions, common::BitMatrix, ResultPoint}; +use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; use super::MathUtils; @@ -59,13 +59,7 @@ impl WhiteRectangleDetector { * @param y y position of search center * @throws NotFoundException if image is too small to accommodate {@code initSize} */ - pub fn new( - image: &BitMatrix, - initSize: i32, - x: i32, - y: i32, - ) -> Result { - + pub fn new(image: &BitMatrix, initSize: i32, x: i32, y: i32) -> Result { let halfsize = initSize / 2; let leftInit = x - halfsize; @@ -81,7 +75,7 @@ impl WhiteRectangleDetector { return Err(Exceptions::NotFoundException("".to_owned())); } - Ok(Self{ + Ok(Self { image: image.clone(), height: image.getHeight() as i32, width: image.getWidth() as i32, @@ -126,7 +120,9 @@ impl WhiteRectangleDetector { // . | // ..... let mut right_border_not_white = true; - while (right_border_not_white || !at_least_one_black_point_found_on_right) && right < self.width { + while (right_border_not_white || !at_least_one_black_point_found_on_right) + && right < self.width + { right_border_not_white = self.contains_black_point(up, down, right, false); if right_border_not_white { right += 1; @@ -146,7 +142,8 @@ impl WhiteRectangleDetector { // . . // .___. let mut bottom_border_not_white = true; - while (bottom_border_not_white || !at_least_one_black_point_found_on_bottom) && down < self.height + while (bottom_border_not_white || !at_least_one_black_point_found_on_bottom) + && down < self.height { bottom_border_not_white = self.contains_black_point(left, right, down, true); if bottom_border_not_white { diff --git a/src/common/eci_encoder_set.rs b/src/common/eci_encoder_set.rs index f3115f0..8382225 100644 --- a/src/common/eci_encoder_set.rs +++ b/src/common/eci_encoder_set.rs @@ -1,4 +1,3 @@ - /* * Copyright 2021 ZXing authors * @@ -24,7 +23,7 @@ // import java.util.ArrayList; // import java.util.List; -use encoding::{EncodingRef, Encoding}; +use encoding::{Encoding, EncodingRef}; use unicode_segmentation::UnicodeSegmentation; use super::CharacterSetECI; @@ -251,4 +250,4 @@ impl ECIEncoderSet { let encoder = self.encoders[encoderIndex]; encoder.encode(s, encoding::EncoderTrap::Replace).unwrap() } -} \ No newline at end of file +} diff --git a/src/common/eci_input.rs b/src/common/eci_input.rs index b84db68..c4287cf 100644 --- a/src/common/eci_input.rs +++ b/src/common/eci_input.rs @@ -1,4 +1,3 @@ - /* * Copyright 2021 ZXing authors * @@ -106,4 +105,4 @@ pub trait ECIInput { */ fn getECIValue(&self, index: usize) -> Result; fn haveNCharacters(&self, index: usize, n: usize) -> bool; -} \ No newline at end of file +} diff --git a/src/common/eci_string_builder.rs b/src/common/eci_string_builder.rs index d1c1aaf..547013e 100644 --- a/src/common/eci_string_builder.rs +++ b/src/common/eci_string_builder.rs @@ -1,4 +1,3 @@ - /* * Copyright 2022 ZXing authors * @@ -24,7 +23,7 @@ use std::fmt; -use encoding::{EncodingRef, Encoding}; +use encoding::{Encoding, EncodingRef}; use crate::Exceptions; @@ -81,7 +80,11 @@ impl ECIStringBuilder { * @param value string to append */ pub fn append_string(&mut self, value: &str) { - value.as_bytes().iter().map(|b| self.current_bytes.push(*b)).count(); + value + .as_bytes() + .iter() + .map(|b| self.current_bytes.push(*b)) + .count(); // self.current_bytes.push(value.as_bytes()); } @@ -170,4 +173,4 @@ impl fmt::Display for ECIStringBuilder { //self.encodeCurrentBytesIfAny(); write!(f, "{}", self.result) } -} \ No newline at end of file +} diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index 0009b45..6d151ba 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -1,4 +1,3 @@ - /* * Copyright 2009 ZXing authors * @@ -21,9 +20,9 @@ // import com.google.zxing.LuminanceSource; // import com.google.zxing.NotFoundException; -use crate::{Exceptions, LuminanceSource, Binarizer}; +use crate::{Binarizer, Exceptions, LuminanceSource}; -use super::{BitMatrix, BitArray}; +use super::{BitArray, BitMatrix}; /** * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable @@ -244,4 +243,4 @@ impl GlobalHistogramBinarizer { Ok((bestValley as u32) << GlobalHistogramBinarizer::LUMINANCE_SHIFT) } -} \ No newline at end of file +} diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index c027bfe..1bcd1bd 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -197,4 +196,4 @@ pub trait GridSampler { } Ok(()) } -} \ No newline at end of file +} diff --git a/src/common/hybrid_binarizer.rs b/src/common/hybrid_binarizer.rs index 62cfb0b..950a14c 100644 --- a/src/common/hybrid_binarizer.rs +++ b/src/common/hybrid_binarizer.rs @@ -20,9 +20,9 @@ // import com.google.zxing.LuminanceSource; // import com.google.zxing.NotFoundException; -use crate::{LuminanceSource, Binarizer, Exceptions}; +use crate::{Binarizer, Exceptions, LuminanceSource}; -use super::{GlobalHistogramBinarizer, BitMatrix, BitArray}; +use super::{BitArray, BitMatrix, GlobalHistogramBinarizer}; /** * This class implements a local thresholding algorithm, which while slower than the @@ -317,4 +317,4 @@ impl HybridBinarizer { } blackPoints } -} \ No newline at end of file +} diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index 4a9baf4..2e1337b 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -20,7 +20,7 @@ // import java.util.ArrayList; // import java.util.List; -use std::{rc::Rc, fmt}; +use std::{fmt, rc::Rc}; use encoding::EncodingRef; use unicode_segmentation::UnicodeSegmentation; @@ -141,7 +141,7 @@ impl ECIInput for MinimalECIInput { if index >= self.length() as u32 { return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); } - Ok(self.bytes[index as usize] > 255)// && self.bytes[index as usize] <= u16::MAX) + Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) } /** @@ -383,11 +383,11 @@ impl MinimalECIInput { } } - struct InputEdge { - c: String, - encoderIndex: usize, //the encoding of this edge - previous: Option>, - cachedTotalSize: usize, +struct InputEdge { + c: String, + encoderIndex: usize, //the encoding of this edge + previous: Option>, + cachedTotalSize: usize, } impl InputEdge { pub fn new( @@ -493,4 +493,4 @@ impl fmt::Display for MinimalECIInput { } write!(f, "{}", result) } -} \ No newline at end of file +} diff --git a/src/common/mod.rs b/src/common/mod.rs index 9322742..b4197a9 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -18,7 +18,6 @@ mod BitSourceTestCase; #[cfg(test)] mod PerspectiveTransformTestCase; - mod string_utils; pub use string_utils::*; @@ -99,9 +98,8 @@ pub use eci_encoder_set::*; mod minimal_eci_input; pub use minimal_eci_input::*; - mod global_histogram_binarizer; pub use global_histogram_binarizer::*; mod hybrid_binarizer; -pub use hybrid_binarizer::*; \ No newline at end of file +pub use hybrid_binarizer::*; diff --git a/src/common/perspective_transform.rs b/src/common/perspective_transform.rs index 3584d09..f5f293e 100644 --- a/src/common/perspective_transform.rs +++ b/src/common/perspective_transform.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -210,4 +209,4 @@ impl PerspectiveTransform { self.a13 * other.a31 + self.a23 * other.a32 + self.a33 * other.a33, ); } -} \ No newline at end of file +} diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index 9bdfdbe..8d859ef 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -2,7 +2,7 @@ use std::fmt; use crate::Exceptions; -use super::{GenericGFRef, GenericGFPoly}; +use super::{GenericGFPoly, GenericGFRef}; /** *

This class contains utility methods for performing mathematical operations over @@ -175,4 +175,4 @@ impl fmt::Display for GenericGF { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "GF({:#06x},{}", self.primitive, self.size) } -} \ No newline at end of file +} diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index 1f9f53b..dc75096 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -20,7 +20,7 @@ use std::fmt; use crate::Exceptions; -use super::{GenericGFRef, GenericGF}; +use super::{GenericGF, GenericGFRef}; /** *

Represents a polynomial whose coefficients are elements of a GF. @@ -337,4 +337,4 @@ impl fmt::Display for GenericGFPoly { } write!(f, "{}", result) } -} \ No newline at end of file +} diff --git a/src/common/reedsolomon/mod.rs b/src/common/reedsolomon/mod.rs index 07b5c51..664cc34 100644 --- a/src/common/reedsolomon/mod.rs +++ b/src/common/reedsolomon/mod.rs @@ -78,4 +78,4 @@ mod reedsolomon_decoder; pub use reedsolomon_decoder::*; mod reedsolomon_encoder; -pub use reedsolomon_encoder::*; \ No newline at end of file +pub use reedsolomon_encoder::*; diff --git a/src/common/reedsolomon/reedsolomon_decoder.rs b/src/common/reedsolomon/reedsolomon_decoder.rs index a38bdc4..e890ba5 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -18,7 +18,7 @@ use crate::Exceptions; -use super::{GenericGFRef, GenericGFPoly, GenericGF}; +use super::{GenericGF, GenericGFPoly, GenericGFRef}; /** *

Implements Reed-Solomon decoding, as the name implies.

@@ -308,4 +308,4 @@ impl ReedSolomonDecoder { } return result; } -} \ No newline at end of file +} diff --git a/src/common/string_utils.rs b/src/common/string_utils.rs index b696e89..7320f79 100644 --- a/src/common/string_utils.rs +++ b/src/common/string_utils.rs @@ -20,9 +20,9 @@ // import java.nio.charset.StandardCharsets; // import java.util.Map; -use encoding::{EncodingRef, Encoding}; +use encoding::{Encoding, EncodingRef}; -use crate::{DecodingHintDictionary, DecodeHintType, DecodeHintValue}; +use crate::{DecodeHintType, DecodeHintValue, DecodingHintDictionary}; use lazy_static::lazy_static; @@ -272,4 +272,4 @@ impl StringUtils { // Otherwise, we take a wild guess with platform encoding return encoding::all::UTF_8; } -} \ No newline at end of file +} diff --git a/src/decode_hints.rs b/src/decode_hints.rs index 2e2cc28..f35b6e3 100644 --- a/src/decode_hints.rs +++ b/src/decode_hints.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -201,4 +200,4 @@ pub enum DecodeHintValue { */ AlsoInverted(bool), // End of enumeration values. -} \ No newline at end of file +} diff --git a/src/dimension.rs b/src/dimension.rs index fa2d2b2..5976a16 100644 --- a/src/dimension.rs +++ b/src/dimension.rs @@ -1,4 +1,3 @@ - /* * Copyright 2012 ZXing authors * @@ -45,4 +44,4 @@ impl fmt::Display for Dimension { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}x{}", self.0, self.1) } -} \ No newline at end of file +} diff --git a/src/encode_hints.rs b/src/encode_hints.rs index d892231..4b3fa56 100644 --- a/src/encode_hints.rs +++ b/src/encode_hints.rs @@ -1,4 +1,3 @@ - /* * Copyright 2008 ZXing authors * @@ -327,4 +326,4 @@ pub enum EncodeHintValue { * exclusive. */ Code128Compact(String), -} \ No newline at end of file +} diff --git a/src/exceptions.rs b/src/exceptions.rs index 938666a..463555b 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -1,6 +1,6 @@ use std::{error::Error, fmt}; -#[derive(Debug,PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub enum Exceptions { IllegalArgumentException(String), UnsupportedOperationException(String), diff --git a/src/lib.rs b/src/lib.rs index b466e6a..20517f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,6 @@ mod buffered_image_luminance_source; #[cfg(feature = "image")] pub use buffered_image_luminance_source::*; - #[cfg(test)] mod PlanarYUVLuminanceSourceTestCase; diff --git a/src/luminance_source.rs b/src/luminance_source.rs index 65b6d7c..201cbcf 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -1,4 +1,3 @@ - /* * Copyright 2009 ZXing authors * @@ -170,4 +169,4 @@ pub trait LuminanceSource { } return result.toString(); }*/ -} \ No newline at end of file +} diff --git a/src/maxicode/decoder/bit_matrix_parser.rs b/src/maxicode/decoder/bit_matrix_parser.rs index 3ce6cda..1133daf 100644 --- a/src/maxicode/decoder/bit_matrix_parser.rs +++ b/src/maxicode/decoder/bit_matrix_parser.rs @@ -16,40 +16,139 @@ use crate::common::BitMatrix; -const BITNR : [[i16;30];33] = [ - [121,120,127,126,133,132,139,138,145,144,151,150,157,156,163,162,169,168,175,174,181,180,187,186,193,192,199,198, -2, -2], - [123,122,129,128,135,134,141,140,147,146,153,152,159,158,165,164,171,170,177,176,183,182,189,188,195,194,201,200,816, -3], - [125,124,131,130,137,136,143,142,149,148,155,154,161,160,167,166,173,172,179,178,185,184,191,190,197,196,203,202,818,817], - [283,282,277,276,271,270,265,264,259,258,253,252,247,246,241,240,235,234,229,228,223,222,217,216,211,210,205,204,819, -3], - [285,284,279,278,273,272,267,266,261,260,255,254,249,248,243,242,237,236,231,230,225,224,219,218,213,212,207,206,821,820], - [287,286,281,280,275,274,269,268,263,262,257,256,251,250,245,244,239,238,233,232,227,226,221,220,215,214,209,208,822, -3], - [289,288,295,294,301,300,307,306,313,312,319,318,325,324,331,330,337,336,343,342,349,348,355,354,361,360,367,366,824,823], - [291,290,297,296,303,302,309,308,315,314,321,320,327,326,333,332,339,338,345,344,351,350,357,356,363,362,369,368,825, -3], - [293,292,299,298,305,304,311,310,317,316,323,322,329,328,335,334,341,340,347,346,353,352,359,358,365,364,371,370,827,826], - [409,408,403,402,397,396,391,390, 79, 78, -2, -2, 13, 12, 37, 36, 2, -1, 44, 43,109,108,385,384,379,378,373,372,828, -3], - [411,410,405,404,399,398,393,392, 81, 80, 40, -2, 15, 14, 39, 38, 3, -1, -1, 45,111,110,387,386,381,380,375,374,830,829], - [413,412,407,406,401,400,395,394, 83, 82, 41, -3, -3, -3, -3, -3, 5, 4, 47, 46,113,112,389,388,383,382,377,376,831, -3], - [415,414,421,420,427,426,103,102, 55, 54, 16, -3, -3, -3, -3, -3, -3, -3, 20, 19, 85, 84,433,432,439,438,445,444,833,832], - [417,416,423,422,429,428,105,104, 57, 56, -3, -3, -3, -3, -3, -3, -3, -3, 22, 21, 87, 86,435,434,441,440,447,446,834, -3], - [419,418,425,424,431,430,107,106, 59, 58, -3, -3, -3, -3, -3, -3, -3, -3, -3, 23, 89, 88,437,436,443,442,449,448,836,835], - [481,480,475,474,469,468, 48, -2, 30, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0, 53, 52,463,462,457,456,451,450,837, -3], - [483,482,477,476,471,470, 49, -1, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -1,465,464,459,458,453,452,839,838], - [485,484,479,478,473,472, 51, 50, 31, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 1, -2, 42,467,466,461,460,455,454,840, -3], - [487,486,493,492,499,498, 97, 96, 61, 60, -3, -3, -3, -3, -3, -3, -3, -3, -3, 26, 91, 90,505,504,511,510,517,516,842,841], - [489,488,495,494,501,500, 99, 98, 63, 62, -3, -3, -3, -3, -3, -3, -3, -3, 28, 27, 93, 92,507,506,513,512,519,518,843, -3], - [491,490,497,496,503,502,101,100, 65, 64, 17, -3, -3, -3, -3, -3, -3, -3, 18, 29, 95, 94,509,508,515,514,521,520,845,844], - [559,558,553,552,547,546,541,540, 73, 72, 32, -3, -3, -3, -3, -3, -3, 10, 67, 66,115,114,535,534,529,528,523,522,846, -3], - [561,560,555,554,549,548,543,542, 75, 74, -2, -1, 7, 6, 35, 34, 11, -2, 69, 68,117,116,537,536,531,530,525,524,848,847], - [563,562,557,556,551,550,545,544, 77, 76, -2, 33, 9, 8, 25, 24, -1, -2, 71, 70,119,118,539,538,533,532,527,526,849, -3], - [565,564,571,570,577,576,583,582,589,588,595,594,601,600,607,606,613,612,619,618,625,624,631,630,637,636,643,642,851,850], - [567,566,573,572,579,578,585,584,591,590,597,596,603,602,609,608,615,614,621,620,627,626,633,632,639,638,645,644,852, -3], - [569,568,575,574,581,580,587,586,593,592,599,598,605,604,611,610,617,616,623,622,629,628,635,634,641,640,647,646,854,853], - [727,726,721,720,715,714,709,708,703,702,697,696,691,690,685,684,679,678,673,672,667,666,661,660,655,654,649,648,855, -3], - [729,728,723,722,717,716,711,710,705,704,699,698,693,692,687,686,681,680,675,674,669,668,663,662,657,656,651,650,857,856], - [731,730,725,724,719,718,713,712,707,706,701,700,695,694,689,688,683,682,677,676,671,670,665,664,659,658,653,652,858, -3], - [733,732,739,738,745,744,751,750,757,756,763,762,769,768,775,774,781,780,787,786,793,792,799,798,805,804,811,810,860,859], - [735,734,741,740,747,746,753,752,759,758,765,764,771,770,777,776,783,782,789,788,795,794,801,800,807,806,813,812,861, -3], - [737,736,743,742,749,748,755,754,761,760,767,766,773,772,779,778,785,784,791,790,797,796,803,802,809,808,815,814,863,862] +const BITNR: [[i16; 30]; 33] = [ + [ + 121, 120, 127, 126, 133, 132, 139, 138, 145, 144, 151, 150, 157, 156, 163, 162, 169, 168, + 175, 174, 181, 180, 187, 186, 193, 192, 199, 198, -2, -2, + ], + [ + 123, 122, 129, 128, 135, 134, 141, 140, 147, 146, 153, 152, 159, 158, 165, 164, 171, 170, + 177, 176, 183, 182, 189, 188, 195, 194, 201, 200, 816, -3, + ], + [ + 125, 124, 131, 130, 137, 136, 143, 142, 149, 148, 155, 154, 161, 160, 167, 166, 173, 172, + 179, 178, 185, 184, 191, 190, 197, 196, 203, 202, 818, 817, + ], + [ + 283, 282, 277, 276, 271, 270, 265, 264, 259, 258, 253, 252, 247, 246, 241, 240, 235, 234, + 229, 228, 223, 222, 217, 216, 211, 210, 205, 204, 819, -3, + ], + [ + 285, 284, 279, 278, 273, 272, 267, 266, 261, 260, 255, 254, 249, 248, 243, 242, 237, 236, + 231, 230, 225, 224, 219, 218, 213, 212, 207, 206, 821, 820, + ], + [ + 287, 286, 281, 280, 275, 274, 269, 268, 263, 262, 257, 256, 251, 250, 245, 244, 239, 238, + 233, 232, 227, 226, 221, 220, 215, 214, 209, 208, 822, -3, + ], + [ + 289, 288, 295, 294, 301, 300, 307, 306, 313, 312, 319, 318, 325, 324, 331, 330, 337, 336, + 343, 342, 349, 348, 355, 354, 361, 360, 367, 366, 824, 823, + ], + [ + 291, 290, 297, 296, 303, 302, 309, 308, 315, 314, 321, 320, 327, 326, 333, 332, 339, 338, + 345, 344, 351, 350, 357, 356, 363, 362, 369, 368, 825, -3, + ], + [ + 293, 292, 299, 298, 305, 304, 311, 310, 317, 316, 323, 322, 329, 328, 335, 334, 341, 340, + 347, 346, 353, 352, 359, 358, 365, 364, 371, 370, 827, 826, + ], + [ + 409, 408, 403, 402, 397, 396, 391, 390, 79, 78, -2, -2, 13, 12, 37, 36, 2, -1, 44, 43, 109, + 108, 385, 384, 379, 378, 373, 372, 828, -3, + ], + [ + 411, 410, 405, 404, 399, 398, 393, 392, 81, 80, 40, -2, 15, 14, 39, 38, 3, -1, -1, 45, 111, + 110, 387, 386, 381, 380, 375, 374, 830, 829, + ], + [ + 413, 412, 407, 406, 401, 400, 395, 394, 83, 82, 41, -3, -3, -3, -3, -3, 5, 4, 47, 46, 113, + 112, 389, 388, 383, 382, 377, 376, 831, -3, + ], + [ + 415, 414, 421, 420, 427, 426, 103, 102, 55, 54, 16, -3, -3, -3, -3, -3, -3, -3, 20, 19, 85, + 84, 433, 432, 439, 438, 445, 444, 833, 832, + ], + [ + 417, 416, 423, 422, 429, 428, 105, 104, 57, 56, -3, -3, -3, -3, -3, -3, -3, -3, 22, 21, 87, + 86, 435, 434, 441, 440, 447, 446, 834, -3, + ], + [ + 419, 418, 425, 424, 431, 430, 107, 106, 59, 58, -3, -3, -3, -3, -3, -3, -3, -3, -3, 23, 89, + 88, 437, 436, 443, 442, 449, 448, 836, 835, + ], + [ + 481, 480, 475, 474, 469, 468, 48, -2, 30, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0, 53, + 52, 463, 462, 457, 456, 451, 450, 837, -3, + ], + [ + 483, 482, 477, 476, 471, 470, 49, -1, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, + -1, 465, 464, 459, 458, 453, 452, 839, 838, + ], + [ + 485, 484, 479, 478, 473, 472, 51, 50, 31, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 1, -2, + 42, 467, 466, 461, 460, 455, 454, 840, -3, + ], + [ + 487, 486, 493, 492, 499, 498, 97, 96, 61, 60, -3, -3, -3, -3, -3, -3, -3, -3, -3, 26, 91, + 90, 505, 504, 511, 510, 517, 516, 842, 841, + ], + [ + 489, 488, 495, 494, 501, 500, 99, 98, 63, 62, -3, -3, -3, -3, -3, -3, -3, -3, 28, 27, 93, + 92, 507, 506, 513, 512, 519, 518, 843, -3, + ], + [ + 491, 490, 497, 496, 503, 502, 101, 100, 65, 64, 17, -3, -3, -3, -3, -3, -3, -3, 18, 29, 95, + 94, 509, 508, 515, 514, 521, 520, 845, 844, + ], + [ + 559, 558, 553, 552, 547, 546, 541, 540, 73, 72, 32, -3, -3, -3, -3, -3, -3, 10, 67, 66, + 115, 114, 535, 534, 529, 528, 523, 522, 846, -3, + ], + [ + 561, 560, 555, 554, 549, 548, 543, 542, 75, 74, -2, -1, 7, 6, 35, 34, 11, -2, 69, 68, 117, + 116, 537, 536, 531, 530, 525, 524, 848, 847, + ], + [ + 563, 562, 557, 556, 551, 550, 545, 544, 77, 76, -2, 33, 9, 8, 25, 24, -1, -2, 71, 70, 119, + 118, 539, 538, 533, 532, 527, 526, 849, -3, + ], + [ + 565, 564, 571, 570, 577, 576, 583, 582, 589, 588, 595, 594, 601, 600, 607, 606, 613, 612, + 619, 618, 625, 624, 631, 630, 637, 636, 643, 642, 851, 850, + ], + [ + 567, 566, 573, 572, 579, 578, 585, 584, 591, 590, 597, 596, 603, 602, 609, 608, 615, 614, + 621, 620, 627, 626, 633, 632, 639, 638, 645, 644, 852, -3, + ], + [ + 569, 568, 575, 574, 581, 580, 587, 586, 593, 592, 599, 598, 605, 604, 611, 610, 617, 616, + 623, 622, 629, 628, 635, 634, 641, 640, 647, 646, 854, 853, + ], + [ + 727, 726, 721, 720, 715, 714, 709, 708, 703, 702, 697, 696, 691, 690, 685, 684, 679, 678, + 673, 672, 667, 666, 661, 660, 655, 654, 649, 648, 855, -3, + ], + [ + 729, 728, 723, 722, 717, 716, 711, 710, 705, 704, 699, 698, 693, 692, 687, 686, 681, 680, + 675, 674, 669, 668, 663, 662, 657, 656, 651, 650, 857, 856, + ], + [ + 731, 730, 725, 724, 719, 718, 713, 712, 707, 706, 701, 700, 695, 694, 689, 688, 683, 682, + 677, 676, 671, 670, 665, 664, 659, 658, 653, 652, 858, -3, + ], + [ + 733, 732, 739, 738, 745, 744, 751, 750, 757, 756, 763, 762, 769, 768, 775, 774, 781, 780, + 787, 786, 793, 792, 799, 798, 805, 804, 811, 810, 860, 859, + ], + [ + 735, 734, 741, 740, 747, 746, 753, 752, 759, 758, 765, 764, 771, 770, 777, 776, 783, 782, + 789, 788, 795, 794, 801, 800, 807, 806, 813, 812, 861, -3, + ], + [ + 737, 736, 743, 742, 749, 748, 755, 754, 761, 760, 767, 766, 773, 772, 779, 778, 785, 784, + 791, 790, 797, 796, 803, 802, 809, 808, 815, 814, 863, 862, + ], ]; /** @@ -59,30 +158,28 @@ const BITNR : [[i16;30];33] = [ pub struct BitMatrixParser(BitMatrix); impl BitMatrixParser { - - /** - * @param bitMatrix {@link BitMatrix} to parse - */ - pub fn new( bitMatrix: BitMatrix) -> Self{ - Self(bitMatrix) - } - - pub fn readCodewords(&self) -> [u8;144] { - 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 (int y = 0; y < height; y++) { - let bitnrRow = BITNR[y]; - 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)); - } - } + /** + * @param bitMatrix {@link BitMatrix} to parse + */ + pub fn new(bitMatrix: BitMatrix) -> Self { + Self(bitMatrix) } - result - } + pub fn readCodewords(&self) -> [u8; 144] { + 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 (int y = 0; y < height; y++) { + let bitnrRow = BITNR[y]; + 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)); + } + } + } + result + } } diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index 03c1a5c..2cdb6ec 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -254,8 +254,10 @@ fn subtract_two_single_char_strings(str1: &str, str2: &str) -> usize { let str1_bytes = str1.as_bytes(); let str2_bytes = str2.as_bytes(); - let str1_u16 = ((str1_bytes[0] as usize) << 4) + ((str1_bytes[1] as usize) << 2) + str1_bytes[2] as usize; - let str2_u16 = ((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize; + let str1_u16 = + ((str1_bytes[0] as usize) << 4) + ((str1_bytes[1] as usize) << 2) + str1_bytes[2] as 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 } diff --git a/src/maxicode/decoder/mod.rs b/src/maxicode/decoder/mod.rs index fc1e18c..1d56451 100644 --- a/src/maxicode/decoder/mod.rs +++ b/src/maxicode/decoder/mod.rs @@ -3,4 +3,4 @@ pub mod decoded_bit_stream_parser; pub mod decoder; pub use bit_matrix_parser::*; -pub use decoder::*; \ No newline at end of file +pub use decoder::*; diff --git a/src/maxicode/mod.rs b/src/maxicode/mod.rs index d1ac838..0b16aca 100644 --- a/src/maxicode/mod.rs +++ b/src/maxicode/mod.rs @@ -1,4 +1,4 @@ pub mod decoder; mod maxi_code_reader; -pub use maxi_code_reader::*; \ No newline at end of file +pub use maxi_code_reader::*; diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index e26f475..4825fa2 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -1,4 +1,3 @@ - // /* // * Copyright 2013 ZXing authors // * @@ -361,4 +360,4 @@ impl LuminanceSource for PlanarYUVLuminanceSource { fn invert(&mut self) { self.invert = !self.invert; } -} \ No newline at end of file +} diff --git a/src/qrcode/QRCodeWriterTestCase.rs b/src/qrcode/QRCodeWriterTestCase.rs index e4b24b0..c2f32f7 100644 --- a/src/qrcode/QRCodeWriterTestCase.rs +++ b/src/qrcode/QRCodeWriterTestCase.rs @@ -14,12 +14,9 @@ * limitations under the License. */ -use std::{ - collections::HashMap, - path::{ PathBuf}, -}; +use std::{collections::HashMap, path::PathBuf}; -use image::{DynamicImage}; +use image::DynamicImage; use crate::{ common::BitMatrix, qrcode::QRCodeWriter, BarcodeFormat, EncodeHintType, EncodeHintValue, Writer, @@ -85,7 +82,7 @@ fn testQRCodeWriter() { // The QR should be multiplied up to fit, with extra padding if necessary let bigEnough = 256; let writer = QRCodeWriter {}; - let matrix = writer.encode_with_hints( + let matrix = writer.encode_with_hints( "http://www.google.com/", &BarcodeFormat::QR_CODE, bigEnough, diff --git a/src/qrcode/decoder/DataMaskTestCase.rs b/src/qrcode/decoder/DataMaskTestCase.rs index 3e5eaf1..543e032 100644 --- a/src/qrcode/decoder/DataMaskTestCase.rs +++ b/src/qrcode/decoder/DataMaskTestCase.rs @@ -28,21 +28,18 @@ type MaskCondition = fn(u32, u32) -> bool; fn testMask0() { testMaskAcrossDimensions(DataMask::DATA_MASK_000, |i, j| ((i + j) % 2 == 0)); testMaskAcrossDimensionsU8(0, |i, j| ((i + j) % 2 == 0)); - } #[test] fn testMask1() { testMaskAcrossDimensions(DataMask::DATA_MASK_001, |i, j| i % 2 == 0); testMaskAcrossDimensionsU8(1, |i, j| i % 2 == 0); - } #[test] fn testMask2() { testMaskAcrossDimensions(DataMask::DATA_MASK_010, |i, j| j % 3 == 0); testMaskAcrossDimensionsU8(2, |i, j| j % 3 == 0); - } #[test] @@ -62,9 +59,7 @@ fn testMask5() { testMaskAcrossDimensions(DataMask::DATA_MASK_101, |i, j| { (i * j) % 2 + (i * j) % 3 == 0 }); - testMaskAcrossDimensionsU8(5, |i, j| { - (i * j) % 2 + (i * j) % 3 == 0 - }); + testMaskAcrossDimensionsU8(5, |i, j| (i * j) % 2 + (i * j) % 3 == 0); } #[test] @@ -72,9 +67,7 @@ fn testMask6() { testMaskAcrossDimensions(DataMask::DATA_MASK_110, |i, j| { ((i * j) % 2 + (i * j) % 3) % 2 == 0 }); - testMaskAcrossDimensionsU8(6, |i, j| { - ((i * j) % 2 + (i * j) % 3) % 2 == 0 - }); + testMaskAcrossDimensionsU8(6, |i, j| ((i * j) % 2 + (i * j) % 3) % 2 == 0); } #[test] @@ -82,9 +75,7 @@ fn testMask7() { testMaskAcrossDimensions(DataMask::DATA_MASK_111, |i, j| { ((i + j) % 2 + (i * j) % 3) % 2 == 0 }); - testMaskAcrossDimensionsU8(7, |i, j| { - ((i + j) % 2 + (i * j) % 3) % 2 == 0 - }); + testMaskAcrossDimensionsU8(7, |i, j| ((i + j) % 2 + (i * j) % 3) % 2 == 0); } fn testMaskAcrossDimensionsU8(mask: u8, condition: MaskCondition) { diff --git a/src/qrcode/decoder/FormatInformationTestCase.rs b/src/qrcode/decoder/FormatInformationTestCase.rs index 4e3376f..4562c5c 100644 --- a/src/qrcode/decoder/FormatInformationTestCase.rs +++ b/src/qrcode/decoder/FormatInformationTestCase.rs @@ -14,57 +14,97 @@ * limitations under the License. */ -use crate::qrcode::decoder::{FormatInformation, ErrorCorrectionLevel}; +use crate::qrcode::decoder::{ErrorCorrectionLevel, FormatInformation}; /** * @author Sean Owen */ +const MASKED_TEST_FORMAT_INFO: u32 = 0x2BED; +const UNMASKED_TEST_FORMAT_INFO: u32 = MASKED_TEST_FORMAT_INFO ^ 0x5412; - const MASKED_TEST_FORMAT_INFO : u32 = 0x2BED; - const UNMASKED_TEST_FORMAT_INFO : u32= MASKED_TEST_FORMAT_INFO ^ 0x5412; - - #[test] - fn testBitsDiffering() { +#[test] +fn testBitsDiffering() { assert_eq!(0, FormatInformation::numBitsDiffering(1, 1)); assert_eq!(1, FormatInformation::numBitsDiffering(0, 2)); assert_eq!(2, FormatInformation::numBitsDiffering(1, 2)); assert_eq!(32, FormatInformation::numBitsDiffering(-1i32 as u32, 0)); - } +} - #[test] - fn testDecode() { +#[test] +fn testDecode() { // Normal case - let expected = - FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO); + let expected = FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO, + MASKED_TEST_FORMAT_INFO, + ); assert!(expected.is_some()); let expected = expected.unwrap(); - assert_eq!( 0x07, expected.getDataMask()); + assert_eq!(0x07, expected.getDataMask()); assert_eq!(ErrorCorrectionLevel::Q, expected.getErrorCorrectionLevel()); // where the code forgot the mask! - assert_eq!(expected, - FormatInformation::decodeFormatInformation(UNMASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).expect("return")); - } + assert_eq!( + expected, + FormatInformation::decodeFormatInformation( + UNMASKED_TEST_FORMAT_INFO, + MASKED_TEST_FORMAT_INFO + ) + .expect("return") + ); +} - #[test] - fn testDecodeWithBitDifference() { - let expected = - FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).unwrap(); +#[test] +fn testDecodeWithBitDifference() { + let expected = FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO, + MASKED_TEST_FORMAT_INFO, + ) + .unwrap(); // 1,2,3,4 bits difference - assert_eq!(expected, FormatInformation::decodeFormatInformation( - MASKED_TEST_FORMAT_INFO ^ 0x01, MASKED_TEST_FORMAT_INFO ^ 0x01).expect("return")); - assert_eq!(expected, FormatInformation::decodeFormatInformation( - MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x03).expect("return")); - assert_eq!(expected, FormatInformation::decodeFormatInformation( - MASKED_TEST_FORMAT_INFO ^ 0x07, MASKED_TEST_FORMAT_INFO ^ 0x07).expect("return")); + assert_eq!( + expected, + FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO ^ 0x01, + MASKED_TEST_FORMAT_INFO ^ 0x01 + ) + .expect("return") + ); + assert_eq!( + expected, + FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO ^ 0x03, + MASKED_TEST_FORMAT_INFO ^ 0x03 + ) + .expect("return") + ); + assert_eq!( + expected, + FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO ^ 0x07, + MASKED_TEST_FORMAT_INFO ^ 0x07 + ) + .expect("return") + ); assert!(FormatInformation::decodeFormatInformation( - MASKED_TEST_FORMAT_INFO ^ 0x0F, MASKED_TEST_FORMAT_INFO ^ 0x0F).is_none()); - } + MASKED_TEST_FORMAT_INFO ^ 0x0F, + MASKED_TEST_FORMAT_INFO ^ 0x0F + ) + .is_none()); +} - #[test] - fn testDecodeWithMisread() { - let expected = - FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).unwrap(); - assert_eq!(expected, FormatInformation::decodeFormatInformation( - MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x0F).unwrap()); - } +#[test] +fn testDecodeWithMisread() { + let expected = FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO, + MASKED_TEST_FORMAT_INFO, + ) + .unwrap(); + assert_eq!( + expected, + FormatInformation::decodeFormatInformation( + MASKED_TEST_FORMAT_INFO ^ 0x03, + MASKED_TEST_FORMAT_INFO ^ 0x0F + ) + .unwrap() + ); +} diff --git a/src/qrcode/decoder/ModeTestCase.rs b/src/qrcode/decoder/ModeTestCase.rs index db93ff2..143e803 100644 --- a/src/qrcode/decoder/ModeTestCase.rs +++ b/src/qrcode/decoder/ModeTestCase.rs @@ -18,34 +18,50 @@ use crate::qrcode::decoder::Version; use super::Mode; - /** * @author Sean Owen */ - #[test] - fn testForBits() { +#[test] +fn testForBits() { assert_eq!(Mode::TERMINATOR, Mode::forBits(0x00).unwrap()); assert_eq!(Mode::NUMERIC, Mode::forBits(0x01).unwrap()); assert_eq!(Mode::ALPHANUMERIC, Mode::forBits(0x02).unwrap()); assert_eq!(Mode::BYTE, Mode::forBits(0x04).unwrap()); assert_eq!(Mode::KANJI, Mode::forBits(0x08).unwrap()); - } +} - #[test] - #[should_panic] - fn testBadMode() { +#[test] +#[should_panic] +fn testBadMode() { assert!(Mode::forBits(0x10).is_ok()); - } +} - #[test] - fn testCharacterCount() { +#[test] +fn testCharacterCount() { // Spot check a few values - assert_eq!(10, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(5).unwrap())); - assert_eq!(12, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(26).unwrap())); - assert_eq!(14, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(40).unwrap())); - assert_eq!(9, Mode::ALPHANUMERIC.getCharacterCountBits(Version::getVersionForNumber(6).unwrap())); - assert_eq!(8, Mode::BYTE.getCharacterCountBits(Version::getVersionForNumber(7).unwrap())); - assert_eq!(8, Mode::KANJI.getCharacterCountBits(Version::getVersionForNumber(8).unwrap())); - } - + assert_eq!( + 10, + Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(5).unwrap()) + ); + assert_eq!( + 12, + Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(26).unwrap()) + ); + assert_eq!( + 14, + Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(40).unwrap()) + ); + assert_eq!( + 9, + Mode::ALPHANUMERIC.getCharacterCountBits(Version::getVersionForNumber(6).unwrap()) + ); + assert_eq!( + 8, + Mode::BYTE.getCharacterCountBits(Version::getVersionForNumber(7).unwrap()) + ); + assert_eq!( + 8, + Mode::KANJI.getCharacterCountBits(Version::getVersionForNumber(8).unwrap()) + ); +} diff --git a/src/qrcode/decoder/VersionTestCase.rs b/src/qrcode/decoder/VersionTestCase.rs index 826b015..190d4cb 100644 --- a/src/qrcode/decoder/VersionTestCase.rs +++ b/src/qrcode/decoder/VersionTestCase.rs @@ -14,35 +14,36 @@ * limitations under the License. */ -use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions}; - +use crate::{ + qrcode::decoder::{ErrorCorrectionLevel, Version}, + Exceptions, +}; /** * @author Sean Owen */ - - #[test] - #[should_panic] - fn testBadVersion() { +#[test] +#[should_panic] +fn testBadVersion() { assert!(Version::getVersionForNumber(0).is_ok()); - } +} - #[test] - fn testVersionForNumber() { +#[test] +fn testVersionForNumber() { for i in 1..=40 { - // for (int i = 1; i <= 40; i++) { - checkVersion(Version::getVersionForNumber(i), i, 4 * i + 17); + // for (int i = 1; i <= 40; i++) { + checkVersion(Version::getVersionForNumber(i), i, 4 * i + 17); } - } +} - fn checkVersion( version:Result<&Version,Exceptions>, number:u32, dimension:u32) { +fn checkVersion(version: Result<&Version, Exceptions>, number: u32, dimension: u32) { assert!(version.is_ok()); let version = version.unwrap(); assert_eq!(number, version.getVersionNumber()); // assertNotNull(version.getAlignmentPatternCenters()); if number > 1 { - assert!(version.getAlignmentPatternCenters().len() > 0); + assert!(version.getAlignmentPatternCenters().len() > 0); } assert_eq!(dimension, version.getDimensionForVersion()); let _tmp = version.getECBlocksForLevel(ErrorCorrectionLevel::H); @@ -56,18 +57,23 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions}; // assertNotNull(version.getECBlocksForLevel(ErrorCorrectionLevel::M)); // assertNotNull(version.getECBlocksForLevel(ErrorCorrectionLevel::Q)); // assertNotNull(version.buildFunctionPattern()); - } +} - #[test] - fn testGetProvisionalVersionForDimension() { +#[test] +fn testGetProvisionalVersionForDimension() { for i in 1..=40 { - // for (int i = 1; i <= 40; i++) { - assert_eq!(i, Version::getProvisionalVersionForDimension(4 * i + 17).expect("must exist for supplied values").getVersionNumber()); + // for (int i = 1; i <= 40; i++) { + assert_eq!( + i, + Version::getProvisionalVersionForDimension(4 * i + 17) + .expect("must exist for supplied values") + .getVersionNumber() + ); } - } +} - #[test] - fn testDecodeVersionInformation() { +#[test] +fn testDecodeVersionInformation() { // Spot check doTestVersion(7, 0x07C94); doTestVersion(12, 0x0C762); @@ -75,11 +81,10 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions}; doTestVersion(22, 0x168C9); doTestVersion(27, 0x1B08E); doTestVersion(32, 0x209D5); - } - - fn doTestVersion( expectedVersion:u32, mask:u32) { +} + +fn doTestVersion(expectedVersion: u32, mask: u32) { let version = Version::decodeVersionInformation(mask); assert!(version.is_ok()); assert_eq!(expectedVersion, version.unwrap().getVersionNumber()); - } - +} diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index 575266c..259052e 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -82,7 +82,7 @@ impl BitMatrixParser { let dimension = self.bitMatrix.getHeight(); let mut formatInfoBits2 = 0; let jMin = dimension - 7; - for j in (jMin..=dimension-1).rev() { + for j in (jMin..=dimension - 1).rev() { // for (int j = dimension - 1; j >= jMin; j--) { formatInfoBits2 = self.copyBit(8, j, formatInfoBits2); } diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index d7d3901..38a783d 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -16,7 +16,7 @@ use crate::Exceptions; -use super::{VersionRef, ErrorCorrectionLevel}; +use super::{ErrorCorrectionLevel, VersionRef}; /** *

Encapsulates a block of data within a QR Code. QR Codes may split their data into @@ -26,118 +26,120 @@ use super::{VersionRef, ErrorCorrectionLevel}; * @author Sean Owen */ pub struct DataBlock { - - numDataCodewords:u32, - codewords:Vec, + numDataCodewords: u32, + codewords: Vec, } impl DataBlock { - - fn new( numDataCodewords:u32, codewords:Vec) -> Self{ - Self{ - numDataCodewords, - codewords, - } - } - - /** - *

When QR Codes use multiple data blocks, they are actually interleaved. - * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - * method will separate the data into original blocks.

- * - * @param rawCodewords bytes as read directly from the QR Code - * @param version version of the QR Code - * @param ecLevel error-correction level of the QR Code - * @return DataBlocks containing original bytes, "de-interleaved" from representation in the - * QR Code - */ - pub fn getDataBlocks( rawCodewords:&[u8], - version:VersionRef, - ecLevel:ErrorCorrectionLevel) -> Result,Exceptions> { - - if rawCodewords.len() as u32 != version.getTotalCodewords() { - return Err(Exceptions::IllegalArgumentException("".to_owned())) + fn new(numDataCodewords: u32, codewords: Vec) -> Self { + Self { + numDataCodewords, + codewords, + } } - // Figure out the number and size of data blocks used by this version and - // error correction level - let ecBlocks = version.getECBlocksForLevel(ecLevel); + /** + *

When QR Codes use multiple data blocks, they are actually interleaved. + * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This + * method will separate the data into original blocks.

+ * + * @param rawCodewords bytes as read directly from the QR Code + * @param version version of the QR Code + * @param ecLevel error-correction level of the QR Code + * @return DataBlocks containing original bytes, "de-interleaved" from representation in the + * QR Code + */ + pub fn getDataBlocks( + rawCodewords: &[u8], + version: VersionRef, + ecLevel: ErrorCorrectionLevel, + ) -> Result, Exceptions> { + if rawCodewords.len() as u32 != version.getTotalCodewords() { + return Err(Exceptions::IllegalArgumentException("".to_owned())); + } - // First count the total number of data blocks - let mut _totalBlocks = 0; - let ecBlockArray = ecBlocks.getECBlocks(); - for ecBlock in ecBlockArray { - // for (Version.ECB ecBlock : ecBlockArray) { - _totalBlocks += ecBlock.getCount(); + // Figure out the number and size of data blocks used by this version and + // error correction level + let ecBlocks = version.getECBlocksForLevel(ecLevel); + + // First count the total number of data blocks + let mut _totalBlocks = 0; + let ecBlockArray = ecBlocks.getECBlocks(); + for ecBlock in ecBlockArray { + // for (Version.ECB ecBlock : ecBlockArray) { + _totalBlocks += ecBlock.getCount(); + } + + // Now establish DataBlocks of the appropriate size and number of data codewords + let mut result = Vec::new(); + let mut numRXingResultBlocks = 0; + for ecBlock in ecBlockArray { + // for (Version.ECB ecBlock : ecBlockArray) { + for _i in 0..ecBlock.getCount() { + // for (int i = 0; i < ecBlock.getCount(); i++) { + let numDataCodewords = ecBlock.getDataCodewords(); + let numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords; + // result[numRXingResultBlocks] = DataBlock::new(numDataCodewords, vec![0u8;numBlockCodewords as usize]); + result.push(DataBlock::new( + numDataCodewords, + vec![0u8; numBlockCodewords as usize], + )); + numRXingResultBlocks += 1; + } + } + + // All blocks have the same amount of data, except that the last n + // (where n may be 0) have 1 more byte. Figure out where these start. + let shorterBlocksTotalCodewords = result[0].codewords.len(); + let mut longerBlocksStartAt = result.len() - 1; + loop { + //while longerBlocksStartAt >= 0 { + let numCodewords = result[longerBlocksStartAt].codewords.len(); + if numCodewords == shorterBlocksTotalCodewords { + break; + } + longerBlocksStartAt -= 1; + } + longerBlocksStartAt += 1; + + let shorterBlocksNumDataCodewords = + shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock() as usize; + // The last elements of result may be 1 element longer; + // first fill out as many elements as all of them have + let mut rawCodewordsOffset = 0; + for i in 0..shorterBlocksNumDataCodewords { + // for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { + for j in 0..numRXingResultBlocks { + // for (int j = 0; j < numRXingResultBlocks; j++) { + result[j].codewords[i] = rawCodewords[rawCodewordsOffset]; + rawCodewordsOffset += 1; + } + } + // Fill out the last data block in the longer ones + for j in longerBlocksStartAt..numRXingResultBlocks { + // for (int j = longerBlocksStartAt; j < numRXingResultBlocks; j++) { + result[j].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 (int j = 0; j < numRXingResultBlocks; j++) { + let iOffset = if j < longerBlocksStartAt { i } else { i + 1 }; + result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset]; + rawCodewordsOffset += 1; + } + } + Ok(result) } - // Now establish DataBlocks of the appropriate size and number of data codewords - let mut result = Vec::new(); - let mut numRXingResultBlocks = 0; - for ecBlock in ecBlockArray { - // for (Version.ECB ecBlock : ecBlockArray) { - for _i in 0..ecBlock.getCount() { - // for (int i = 0; i < ecBlock.getCount(); i++) { - let numDataCodewords = ecBlock.getDataCodewords(); - let numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords; - // result[numRXingResultBlocks] = DataBlock::new(numDataCodewords, vec![0u8;numBlockCodewords as usize]); - result.push( DataBlock::new(numDataCodewords, vec![0u8;numBlockCodewords as usize])); - numRXingResultBlocks += 1; - } + pub fn getNumDataCodewords(&self) -> u32 { + self.numDataCodewords } - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 more byte. Figure out where these start. - let shorterBlocksTotalCodewords = result[0].codewords.len(); - let mut longerBlocksStartAt = result.len() - 1; - loop { - //while longerBlocksStartAt >= 0 { - let numCodewords = result[longerBlocksStartAt].codewords.len(); - if numCodewords == shorterBlocksTotalCodewords { - break; - } - longerBlocksStartAt-=1; + pub fn getCodewords(&self) -> &[u8] { + &self.codewords } - longerBlocksStartAt+=1; - - let shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock() as usize; - // The last elements of result may be 1 element longer; - // first fill out as many elements as all of them have - let mut rawCodewordsOffset = 0; - for i in 0..shorterBlocksNumDataCodewords { - // for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { - for j in 0..numRXingResultBlocks { - // for (int j = 0; j < numRXingResultBlocks; j++) { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset]; - rawCodewordsOffset += 1; - } - } - // Fill out the last data block in the longer ones - for j in longerBlocksStartAt..numRXingResultBlocks{ - // for (int j = longerBlocksStartAt; j < numRXingResultBlocks; j++) { - result[j].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 (int j = 0; j < numRXingResultBlocks; j++) { - let iOffset = if j < longerBlocksStartAt {i} else {i + 1}; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset]; - rawCodewordsOffset += 1; - } - } - Ok(result) - } - - pub fn getNumDataCodewords(&self) -> u32{ - self. numDataCodewords - } - - pub fn getCodewords(&self) -> &[u8] { - &self.codewords - } - } diff --git a/src/qrcode/decoder/data_mask.rs b/src/qrcode/decoder/data_mask.rs index 6e88498..4efc467 100755 --- a/src/qrcode/decoder/data_mask.rs +++ b/src/qrcode/decoder/data_mask.rs @@ -27,7 +27,7 @@ use crate::{common::BitMatrix, Exceptions}; * * @author Sean Owen */ -#[derive(Copy,Clone,Eq, PartialEq)] +#[derive(Copy, Clone, Eq, PartialEq)] pub enum DataMask { // See ISO 18004:2006 6.8.1 /** @@ -222,15 +222,18 @@ impl TryFrom for DataMask { fn try_from(value: u8) -> Result { match value { - 0=>Ok(DataMask::DATA_MASK_000), - 1=>Ok(DataMask::DATA_MASK_001), - 2=>Ok(DataMask::DATA_MASK_010), - 3=>Ok(DataMask::DATA_MASK_011), - 4=>Ok(DataMask::DATA_MASK_100), - 5=>Ok(DataMask::DATA_MASK_101), - 6=>Ok(DataMask::DATA_MASK_110), - 7=>Ok(DataMask::DATA_MASK_111), - _=>Err(Exceptions::IllegalArgumentException(format!("{} is not between 0 and 7",value))), + 0 => Ok(DataMask::DATA_MASK_000), + 1 => Ok(DataMask::DATA_MASK_001), + 2 => Ok(DataMask::DATA_MASK_010), + 3 => Ok(DataMask::DATA_MASK_011), + 4 => Ok(DataMask::DATA_MASK_100), + 5 => Ok(DataMask::DATA_MASK_101), + 6 => Ok(DataMask::DATA_MASK_110), + 7 => Ok(DataMask::DATA_MASK_111), + _ => Err(Exceptions::IllegalArgumentException(format!( + "{} is not between 0 and 7", + value + ))), } } -} \ No newline at end of file +} diff --git a/src/qrcode/decoder/decoded_bit_stream_parser.rs b/src/qrcode/decoder/decoded_bit_stream_parser.rs index 28d21c7..65d72fc 100644 --- a/src/qrcode/decoder/decoded_bit_stream_parser.rs +++ b/src/qrcode/decoder/decoded_bit_stream_parser.rs @@ -286,17 +286,19 @@ fn decodeByteSegment( encoding = CharacterSetECI::getCharset(currentCharacterSetECI.as_ref().unwrap()); } - let encode_string = if currentCharacterSetECI.is_some() && currentCharacterSetECI.as_ref().unwrap() == &CharacterSetECI::Cp437 { - { - use codepage_437::BorrowFromCp437; - use codepage_437::CP437_CONTROL; + let encode_string = if currentCharacterSetECI.is_some() + && currentCharacterSetECI.as_ref().unwrap() == &CharacterSetECI::Cp437 + { + { + use codepage_437::BorrowFromCp437; + use codepage_437::CP437_CONTROL; - String::borrow_from_cp437(&readBytes, &CP437_CONTROL) - } - }else { - encoding - .decode(&readBytes, encoding::DecoderTrap::Strict) - .unwrap() + String::borrow_from_cp437(&readBytes, &CP437_CONTROL) + } + } else { + encoding + .decode(&readBytes, encoding::DecoderTrap::Strict) + .unwrap() }; // let encode_string = encoding diff --git a/src/qrcode/decoder/decoder.rs b/src/qrcode/decoder/decoder.rs index f210f66..61eec89 100644 --- a/src/qrcode/decoder/decoder.rs +++ b/src/qrcode/decoder/decoder.rs @@ -198,7 +198,7 @@ fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<() codewordsInts[i] = codewordBytes[i]; // & 0xFF; } - let mut sending_code_words : Vec = codewordsInts.iter().map(|x| *x as i32).collect(); + let mut sending_code_words: Vec = codewordsInts.iter().map(|x| *x as i32).collect(); if let Err(e) = RS_DECODER.decode( &mut sending_code_words, diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index 6b30954..fc9c9fc 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -88,15 +88,15 @@ impl From for u8 { } impl FromStr for ErrorCorrectionLevel { - type Err=Exceptions; + type Err = Exceptions; fn from_str(s: &str) -> Result { // First try to see if the string is just the name of the value let as_str = match s.to_uppercase().as_str() { "L" => Some(ErrorCorrectionLevel::L), "M" => Some(ErrorCorrectionLevel::M), - "Q" =>Some(ErrorCorrectionLevel::Q), - "H" =>Some(ErrorCorrectionLevel::H), + "Q" => Some(ErrorCorrectionLevel::Q), + "H" => Some(ErrorCorrectionLevel::H), _ => None, }; @@ -110,7 +110,10 @@ impl FromStr for ErrorCorrectionLevel { return number_possible.unwrap().try_into(); } - return Err(Exceptions::IllegalArgumentException(format!("could not parse {} into an ec level", s))) + return Err(Exceptions::IllegalArgumentException(format!( + "could not parse {} into an ec level", + s + ))); } } diff --git a/src/qrcode/decoder/format_information.rs b/src/qrcode/decoder/format_information.rs index 3d91c2f..087e182 100644 --- a/src/qrcode/decoder/format_information.rs +++ b/src/qrcode/decoder/format_information.rs @@ -101,12 +101,12 @@ impl FormatInformation { ) -> Option { let formatInfo = Self::doDecodeFormatInformation(masked_format_info1, masked_format_info2); if formatInfo.is_some() { - return formatInfo + return formatInfo; } // Should return null, but, some QR codes apparently // do not mask this info. Try again by actually masking the pattern // first - Self::doDecodeFormatInformation( + Self::doDecodeFormatInformation( masked_format_info1 ^ FORMAT_INFO_MASK_QR, masked_format_info2 ^ FORMAT_INFO_MASK_QR, ) diff --git a/src/qrcode/decoder/mod.rs b/src/qrcode/decoder/mod.rs index 437277b..495b4b3 100644 --- a/src/qrcode/decoder/mod.rs +++ b/src/qrcode/decoder/mod.rs @@ -1,32 +1,32 @@ -mod version; -mod mode; -mod error_correction_level; -mod format_information; -mod data_block; -mod qr_code_decoder_meta_data; -mod data_mask; mod bit_matrix_parser; +mod data_block; +mod data_mask; pub mod decoded_bit_stream_parser; pub mod decoder; +mod error_correction_level; +mod format_information; +mod mode; +mod qr_code_decoder_meta_data; +mod version; -#[cfg(test)] -mod ErrorCorrectionLevelTestCase; -#[cfg(test)] -mod ModeTestCase; -#[cfg(test)] -mod VersionTestCase; -#[cfg(test)] -mod FormatInformationTestCase; #[cfg(test)] mod DataMaskTestCase; #[cfg(test)] mod DecodedBitStreamParserTestCase; +#[cfg(test)] +mod ErrorCorrectionLevelTestCase; +#[cfg(test)] +mod FormatInformationTestCase; +#[cfg(test)] +mod ModeTestCase; +#[cfg(test)] +mod VersionTestCase; -pub use version::*; -pub use mode::*; +pub use bit_matrix_parser::*; +pub use data_block::*; +pub use data_mask::*; pub use error_correction_level::*; pub use format_information::*; -pub use data_block::*; +pub use mode::*; pub use qr_code_decoder_meta_data::*; -pub use data_mask::*; -pub use bit_matrix_parser::*; \ No newline at end of file +pub use version::*; diff --git a/src/qrcode/decoder/qr_code_decoder_meta_data.rs b/src/qrcode/decoder/qr_code_decoder_meta_data.rs index 937ad5f..237b334 100644 --- a/src/qrcode/decoder/qr_code_decoder_meta_data.rs +++ b/src/qrcode/decoder/qr_code_decoder_meta_data.rs @@ -24,31 +24,30 @@ use crate::RXingResultPoint; */ pub struct QRCodeDecoderMetaData(bool); -impl QRCodeDecoderMetaData { - pub fn new( mirrored:bool) -> Self { - Self(mirrored) - } - - /** - * @return true if the QR Code was mirrored. - */ - pub fn isMirrored(&self) -> bool{ - self.0 - } - - /** - * Apply the result points' order correction due to mirroring. - * - * @param points Array of points to apply mirror correction to. - */ - pub fn applyMirroredCorrection(&self, points : &mut [RXingResultPoint]) { - if !self.0 || points.is_empty() || points.len() < 3 { - return +impl QRCodeDecoderMetaData { + pub fn new(mirrored: bool) -> Self { + Self(mirrored) } - let bottom_left = points[0]; - points[0] = points[2]; - points[2] = bottom_left; - // No need to 'fix' top-left and alignment pattern. - } + /** + * @return true if the QR Code was mirrored. + */ + pub fn isMirrored(&self) -> bool { + self.0 + } + + /** + * Apply the result points' order correction due to mirroring. + * + * @param points Array of points to apply mirror correction to. + */ + pub fn applyMirroredCorrection(&self, points: &mut [RXingResultPoint]) { + if !self.0 || points.is_empty() || points.len() < 3 { + return; + } + let bottom_left = points[0]; + points[0] = points[2]; + points[2] = bottom_left; + // No need to 'fix' top-left and alignment pattern. + } } diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index de8bd38..88cd97b 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -156,7 +156,7 @@ impl Version { /** * See ISO 18004:2006 Annex E */ - pub fn buildFunctionPattern(&self) -> Result { + pub fn buildFunctionPattern(&self) -> Result { let dimension = self.getDimensionForVersion(); let mut bitMatrix = BitMatrix::with_single_dimension(dimension); @@ -932,7 +932,7 @@ impl fmt::Display for Version { * will be the same across all blocks within one version.

*/ #[derive(Debug)] - pub struct ECBlocks { +pub struct ECBlocks { ecCodewordsPerBlock: u32, ecBlocks: Vec, } diff --git a/src/qrcode/detector/alignment_pattern.rs b/src/qrcode/detector/alignment_pattern.rs index 24f8d41..cbe9805 100644 --- a/src/qrcode/detector/alignment_pattern.rs +++ b/src/qrcode/detector/alignment_pattern.rs @@ -24,7 +24,7 @@ use crate::{RXingResultPoint, ResultPoint}; * * @author Sean Owen */ -#[derive(Debug,Clone, Copy,PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq)] pub struct AlignmentPattern { estimatedModuleSize: f32, point: (f32, f32), @@ -40,7 +40,10 @@ impl ResultPoint for AlignmentPattern { } fn into_rxing_result_point(self) -> RXingResultPoint { - RXingResultPoint { x: self.point.0, y: self.point.1 } + RXingResultPoint { + x: self.point.0, + y: self.point.1, + } } } diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index 5ec5c39..2b9d380 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -97,7 +97,7 @@ impl AlignmentPatternFinder { // Search from middle outwards let i = (middleI as i32 + (if (iGen & 0x01) == 0 { - (iGen as i32 + 1) / 2 + (iGen as i32 + 1) / 2 } else { -((iGen as i32 + 1) / 2) })) as u32; @@ -172,7 +172,7 @@ impl AlignmentPatternFinder { * figures the location of the center of this black/white/black run. */ fn centerFromEnd(stateCount: &[u32], end: u32) -> f32 { - (end as f32 - stateCount[2] as f32) - stateCount[1] as f32 / 2.0 + (end as f32 - stateCount[2] as f32) - stateCount[1] as f32 / 2.0 } /** @@ -237,15 +237,21 @@ impl AlignmentPatternFinder { } // Now also count down from center - i = startI as i32+ 1; - while i < maxI as i32 && image.get(centerJ, i as u32) && self.crossCheckStateCount[1] <= maxCount { + i = startI as i32 + 1; + while i < maxI as i32 + && image.get(centerJ, i as u32) + && self.crossCheckStateCount[1] <= maxCount + { self.crossCheckStateCount[1] += 1; i += 1; } if i == maxI as i32 || self.crossCheckStateCount[1] > maxCount { return f32::NAN; } - while i < maxI as i32 && !image.get(centerJ, i as u32) && self.crossCheckStateCount[2] <= maxCount { + while i < maxI as i32 + && !image.get(centerJ, i as u32) + && self.crossCheckStateCount[2] <= maxCount + { self.crossCheckStateCount[2] += 1; i += 1; } @@ -288,7 +294,7 @@ impl AlignmentPatternFinder { ) -> Option { let stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; let centerJ = Self::centerFromEnd(stateCount, j); - let centerI = self.crossCheckVertical( + let centerI = self.crossCheckVertical( i, centerJ.floor() as u32, 2 * stateCount[1], diff --git a/src/qrcode/detector/detector.rs b/src/qrcode/detector/detector.rs index cc7d183..fe5fe6b 100644 --- a/src/qrcode/detector/detector.rs +++ b/src/qrcode/detector/detector.rs @@ -18,8 +18,7 @@ use std::collections::HashMap; use crate::{ common::{ - detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler, - PerspectiveTransform, + detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler, PerspectiveTransform, }, qrcode::decoder::Version, result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, @@ -338,10 +337,11 @@ impl Detector { let mut scale = 1.0; let mut otherToX = fromX as i32 - (toX as i32 - fromX as i32); if otherToX < 0 { - scale = fromX as f32 / (fromX as i32- otherToX) as f32; + scale = fromX as f32 / (fromX as i32 - otherToX) as f32; otherToX = 0; } else if otherToX as u32 >= self.image.getWidth() { - scale = (self.image.getWidth() as i32 - 1 - fromX as i32) as f32 / (otherToX - fromX as i32) as f32; + scale = (self.image.getWidth() as i32 - 1 - fromX as i32) as f32 + / (otherToX - fromX as i32) as f32; otherToX = self.image.getWidth() as i32 - 1; } let mut otherToY = (fromY as f32 - (toY as f32 - fromY as f32) * scale).floor() as i32; @@ -351,12 +351,18 @@ impl Detector { scale = fromY as f32 / (fromY as i32 - otherToY) as f32; otherToY = 0; } else if otherToY as u32 >= self.image.getHeight() { - scale = (self.image.getHeight() as i32 - 1 - fromY as i32) as f32 / (otherToY - fromY as i32) as f32; + scale = (self.image.getHeight() as i32 - 1 - fromY as i32) as f32 + / (otherToY - fromY as i32) as f32; otherToY = self.image.getHeight() as i32 - 1; } - otherToX = (fromX as f32+ (otherToX as f32 - fromX as f32) * scale).floor() as i32; + 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 as u32, + fromY as u32, + otherToX as u32, + otherToY as u32, + ); // Middle pixel is double-counted this way; subtract 1 return result - 1.0; @@ -462,7 +468,7 @@ impl Detector { // Look for an alignment pattern (3 modules in size) around where it // should be let allowance = (allowanceFactor * overallEstModuleSize) as u32; - let alignmentAreaLeftX = 0.max(estAlignmentX as i32- allowance as i32) as u32; + 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())); diff --git a/src/qrcode/detector/finder_pattern.rs b/src/qrcode/detector/finder_pattern.rs index 487eed9..3b7bdb2 100644 --- a/src/qrcode/detector/finder_pattern.rs +++ b/src/qrcode/detector/finder_pattern.rs @@ -40,7 +40,10 @@ impl ResultPoint for FinderPattern { } fn into_rxing_result_point(self) -> RXingResultPoint { - RXingResultPoint { x: self.point.0, y: self.point.1 } + RXingResultPoint { + x: self.point.0, + y: self.point.1, + } } } diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 0902566..2762377 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -16,7 +16,7 @@ use crate::{ common::BitMatrix, result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions, - RXingResultPointCallback, ResultPoint, + RXingResultPointCallback, ResultPoint, }; use super::{FinderPattern, FinderPatternInfo}; @@ -76,7 +76,6 @@ impl FinderPatternFinder { &mut self, hints: &DecodingHintDictionary, ) -> Result { - let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER); let maxI = self.image.getHeight(); let maxJ = self.image.getWidth(); @@ -136,7 +135,9 @@ impl FinderPatternFinder { // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added - i += rowSkip as i32 - stateCount[2] as i32 - iSkip as i32; + i += rowSkip as i32 + - stateCount[2] as i32 + - iSkip as i32; // i += rowSkip - stateCount[2] - iSkip ; j = maxJ - 1; } @@ -144,7 +145,7 @@ impl FinderPatternFinder { } else { FinderPatternFinder::doShiftCounts2(&mut stateCount); currentState = 3; - j+=1; + j += 1; continue; } // Clear state to start looking again @@ -164,7 +165,7 @@ impl FinderPatternFinder { stateCount[currentState] += 1; } } - j+=1; + j += 1; } if FinderPatternFinder::foundPatternCross(&stateCount) { let confirmed = self.handlePossibleCenter(&stateCount, i as u32, maxJ); @@ -379,7 +380,10 @@ impl FinderPatternFinder { if i < 0 { return f32::NAN; } - while i >= 0 && !self.image.get(centerJ, i as u32) && self.crossCheckStateCount[1] <= maxCount { + while i >= 0 + && !self.image.get(centerJ, i as u32) + && self.crossCheckStateCount[1] <= maxCount + { self.crossCheckStateCount[1] += 1; i -= 1; } @@ -387,7 +391,10 @@ impl FinderPatternFinder { if i < 0 || self.crossCheckStateCount[1] > maxCount { return f32::NAN; } - while i >= 0 && self.image.get(centerJ, i as u32) && self.crossCheckStateCount[0] <= maxCount { + while i >= 0 + && self.image.get(centerJ, i as u32) + && self.crossCheckStateCount[0] <= maxCount + { self.crossCheckStateCount[0] += 1; i -= 1; } @@ -404,14 +411,20 @@ impl FinderPatternFinder { if i == maxI { return f32::NAN; } - while i < maxI && !self.image.get(centerJ, i as u32) && self.crossCheckStateCount[3] < maxCount { + while i < maxI + && !self.image.get(centerJ, i as u32) + && self.crossCheckStateCount[3] < maxCount + { self.crossCheckStateCount[3] += 1; i += 1; } if i == maxI || self.crossCheckStateCount[3] >= maxCount { return f32::NAN; } - while i < maxI && self.image.get(centerJ, i as u32) && self.crossCheckStateCount[4] < maxCount { + while i < maxI + && self.image.get(centerJ, i as u32) + && self.crossCheckStateCount[4] < maxCount + { self.crossCheckStateCount[4] += 1; i += 1; } @@ -426,7 +439,9 @@ impl FinderPatternFinder { + self.crossCheckStateCount[2] + self.crossCheckStateCount[3] + self.crossCheckStateCount[4]; - if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) >= 2 * originalStateCountTotal as i64 { + if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) + >= 2 * originalStateCountTotal as i64 + { return f32::NAN; } @@ -462,14 +477,20 @@ impl FinderPatternFinder { if j < 0 { return f32::NAN; } - while j >= 0 && !self.image.get(j as u32, centerI) && self.crossCheckStateCount[1] <= maxCount { + while j >= 0 + && !self.image.get(j as u32, centerI) + && self.crossCheckStateCount[1] <= maxCount + { self.crossCheckStateCount[1] += 1; j -= 1; } if j < 0 || self.crossCheckStateCount[1] > maxCount { return f32::NAN; } - while j >= 0 && self.image.get(j as u32 as u32, centerI) && self.crossCheckStateCount[0] <= maxCount { + while j >= 0 + && self.image.get(j as u32 as u32, centerI) + && self.crossCheckStateCount[0] <= maxCount + { self.crossCheckStateCount[0] += 1; j -= 1; } @@ -485,14 +506,20 @@ impl FinderPatternFinder { if j == maxJ as i32 { return f32::NAN; } - while j < maxJ as i32 && !self.image.get(j as u32, centerI) && self.crossCheckStateCount[3] < maxCount { + while j < maxJ as i32 + && !self.image.get(j as u32, centerI) + && self.crossCheckStateCount[3] < maxCount + { self.crossCheckStateCount[3] += 1; j += 1; } if j == (maxJ as i32) || self.crossCheckStateCount[3] >= maxCount { return f32::NAN; } - while j < (maxJ as i32) && self.image.get(j as u32, centerI) && self.crossCheckStateCount[4] < maxCount { + while j < (maxJ as i32) + && self.image.get(j as u32, centerI) + && self.crossCheckStateCount[4] < maxCount + { self.crossCheckStateCount[4] += 1; j += 1; } @@ -507,7 +534,9 @@ impl FinderPatternFinder { + self.crossCheckStateCount[2] + self.crossCheckStateCount[3] + self.crossCheckStateCount[4]; - if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) >= originalStateCountTotal as i64 { + if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) + >= originalStateCountTotal as i64 + { return f32::NAN; } @@ -559,7 +588,8 @@ impl FinderPatternFinder { let stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; let mut centerJ = Self::centerFromEnd(stateCount, j); - let centerI = self.crossCheckVertical(i, centerJ.floor() as u32, stateCount[2], stateCountTotal); + let centerI = + self.crossCheckVertical(i, centerJ.floor() as u32, stateCount[2], stateCountTotal); if !centerI.is_nan() { // Re-cross check centerJ = self.crossCheckHorizontal( @@ -568,7 +598,9 @@ impl FinderPatternFinder { stateCount[2], stateCountTotal, ); - if !centerJ.is_nan() && self.crossCheckDiagonal(centerI.floor() as u32, centerJ.floor() as u32) { + if !centerJ.is_nan() + && self.crossCheckDiagonal(centerI.floor() as u32, centerJ.floor() as u32) + { let estimatedModuleSize = stateCountTotal as f32 / 7.0; let mut found = false; for index in 0..self.possibleCenters.len() { diff --git a/src/qrcode/detector/mod.rs b/src/qrcode/detector/mod.rs index 822363f..f0eb510 100644 --- a/src/qrcode/detector/mod.rs +++ b/src/qrcode/detector/mod.rs @@ -1,18 +1,18 @@ -mod finder_pattern_info; -mod finder_pattern; mod alignment_pattern; mod alignment_pattern_finder; -mod finder_pattern_finder; mod detector; +mod finder_pattern; +mod finder_pattern_finder; +mod finder_pattern_info; mod qrcode_detector_result; -pub use finder_pattern_info::*; -pub use finder_pattern::*; pub use alignment_pattern::*; pub use alignment_pattern_finder::*; -pub use finder_pattern_finder::*; pub use detector::*; +pub use finder_pattern::*; +pub use finder_pattern_finder::*; +pub use finder_pattern_info::*; pub use qrcode_detector_result::*; #[cfg(test)] -mod DetectorTest; \ No newline at end of file +mod DetectorTest; diff --git a/src/qrcode/detector/qrcode_detector_result.rs b/src/qrcode/detector/qrcode_detector_result.rs index 902a533..1252a06 100644 --- a/src/qrcode/detector/qrcode_detector_result.rs +++ b/src/qrcode/detector/qrcode_detector_result.rs @@ -1,6 +1,6 @@ use crate::{ common::{BitMatrix, DetectorRXingResult}, - RXingResultPoint, + RXingResultPoint, }; pub struct QRCodeDetectorResult { diff --git a/src/qrcode/encoder/EncoderTestCase.rs b/src/qrcode/encoder/EncoderTestCase.rs index d297ee7..95b3faa 100644 --- a/src/qrcode/encoder/EncoderTestCase.rs +++ b/src/qrcode/encoder/EncoderTestCase.rs @@ -415,7 +415,8 @@ fn testAppendLengthInfo() { Version::getVersionForNumber(1).unwrap(), Mode::NUMERIC, &mut bits, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ........ .X", bits.to_string()); // 10 bits. let mut bits = BitArray::new(); encoder::appendLengthInfo( @@ -423,7 +424,8 @@ fn testAppendLengthInfo() { Version::getVersionForNumber(10).unwrap(), Mode::ALPHANUMERIC, &mut bits, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ........ .X.", bits.to_string()); // 11 bits. let mut bits = BitArray::new(); encoder::appendLengthInfo( @@ -431,7 +433,8 @@ fn testAppendLengthInfo() { Version::getVersionForNumber(27).unwrap(), Mode::BYTE, &mut bits, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ........ XXXXXXXX", bits.to_string()); // 16 bits. let mut bits = BitArray::new(); encoder::appendLengthInfo( @@ -439,7 +442,8 @@ fn testAppendLengthInfo() { Version::getVersionForNumber(40).unwrap(), Mode::KANJI, &mut bits, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ..X..... ....", bits.to_string()); // 12 bits. } @@ -453,7 +457,8 @@ fn testAppendBytes() { Mode::NUMERIC, &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ...X", bits.to_string()); // Should use appendAlphanumericBytes. // A = 10 = 0xa = 001010 in 6 bits @@ -463,7 +468,8 @@ fn testAppendBytes() { Mode::ALPHANUMERIC, &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" ..X.X.", bits.to_string()); // Lower letters such as 'a' cannot be encoded in MODE_ALPHANUMERIC. //try { @@ -488,7 +494,8 @@ fn testAppendBytes() { Mode::BYTE, &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" .XX....X .XX...X. .XX...XX", bits.to_string()); // Anything can be encoded in QRCode.MODE_8BIT_BYTE. encoder::appendBytes( @@ -496,7 +503,8 @@ fn testAppendBytes() { Mode::BYTE, &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING, - ).expect("ok"); + ) + .expect("ok"); // Should use appendKanjiBytes. // 0x93, 0x5f let mut bits = BitArray::new(); @@ -505,7 +513,8 @@ fn testAppendBytes() { Mode::KANJI, &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING, - ).expect("ok"); + ) + .expect("ok"); assert_eq!(" .XX.XX.. XXXXX", bits.to_string()); } @@ -540,80 +549,45 @@ fn testTerminateBits() { #[test] fn testGetNumDataBytesAndNumECBytesForBlockID() { - // Version 1-H. - let (numDataBytes,numEcBytes) = encoder::getNumDataBytesAndNumECBytesForBlockID( - 26, - 9, - 1, - 0, - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(26, 9, 1, 0).expect("ok"); assert_eq!(9, numDataBytes); assert_eq!(17, numEcBytes); // Version 3-H. 2 blocks. - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 70, - 26, - 2, - 0, - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 0).expect("ok"); assert_eq!(13, numDataBytes); assert_eq!(22, numEcBytes); - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 70, - 26, - 2, - 1, - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 1).expect("ok"); assert_eq!(13, numDataBytes); assert_eq!(22, numEcBytes); // Version 7-H. (4 + 1) blocks. - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 196, - 66, - 5, - 0, - - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 0).expect("ok"); assert_eq!(13, numDataBytes); assert_eq!(26, numEcBytes); - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 196, - 66, - 5, - 4, - - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 4).expect("ok"); assert_eq!(14, numDataBytes); assert_eq!(26, numEcBytes); // Version 40-H. (20 + 61) blocks. - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 3706, - 1276, - 81, - 0, - ).expect("ok"); + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 0).expect("ok"); assert_eq!(15, numDataBytes); assert_eq!(30, numEcBytes); - - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 3706, - 1276, - 81, - 20, - ).expect("ok"); + + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 20).expect("ok"); assert_eq!(16, numDataBytes); assert_eq!(30, numEcBytes); - - let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID( - 3706, - 1276, - 81, - 80, - ).expect("ok"); + + let (numDataBytes, numEcBytes) = + encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 80).expect("ok"); assert_eq!(16, numDataBytes); assert_eq!(30, numEcBytes); } @@ -738,7 +712,8 @@ fn testAppendAlphanumericBytes() { fn testAppend8BitBytes() { // 0x61, 0x62, 0x63 let mut bits = BitArray::new(); - encoder::append8BitBytes("abc", &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING).expect("append"); + encoder::append8BitBytes("abc", &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING) + .expect("append"); assert_eq!(" .XX....X .XX...X. .XX...XX", bits.to_string()); // Empty. let mut bits = BitArray::new(); diff --git a/src/qrcode/encoder/MatrixUtilTestCase.rs b/src/qrcode/encoder/MatrixUtilTestCase.rs index 57b7bf9..19ec85c 100644 --- a/src/qrcode/encoder/MatrixUtilTestCase.rs +++ b/src/qrcode/encoder/MatrixUtilTestCase.rs @@ -254,7 +254,8 @@ fn testBuildMatrix() { Version::getVersionForNumber(1).expect("version"), // Version 1 3, // Mask pattern 3 &mut matrix, - ).expect("append"); + ) + .expect("append"); let expected = r" 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1 diff --git a/src/qrcode/encoder/QRCodeTestCase.rs b/src/qrcode/encoder/QRCodeTestCase.rs index 90dc953..4223437 100644 --- a/src/qrcode/encoder/QRCodeTestCase.rs +++ b/src/qrcode/encoder/QRCodeTestCase.rs @@ -14,20 +14,21 @@ * limitations under the License. */ -use crate::qrcode::{decoder::{Mode, ErrorCorrectionLevel, Version}, encoder::ByteMatrix}; +use crate::qrcode::{ + decoder::{ErrorCorrectionLevel, Mode, Version}, + encoder::ByteMatrix, +}; use super::QRCode; - /** * @author satorux@google.com (Satoru Takabayashi) - creator * @author mysen@google.com (Chris Mysen) - ported from C++ */ - #[test] - fn test() { - let mut qrCode = QRCode::new(); +fn test() { + let mut qrCode = QRCode::new(); // First, test simple setters and getters. // We use numbers of version 7-H. @@ -42,43 +43,43 @@ use super::QRCode; assert_eq!(3, qrCode.getMaskPattern()); // Prepare the matrix. - let mut matrix = ByteMatrix::new(45, 45); + let mut matrix = ByteMatrix::new(45, 45); // Just set bogus zero/one values. for y in 0..45 { - // for (int y = 0; y < 45; ++y) { - for x in 0..45 { - // for (int x = 0; x < 45; ++x) { - matrix.set(x, y, ((y + x) % 2) as u8); - } + // for (int y = 0; y < 45; ++y) { + for x in 0..45 { + // for (int x = 0; x < 45; ++x) { + matrix.set(x, y, ((y + x) % 2) as u8); + } } // Set the matrix. qrCode.setMatrix(matrix.clone()); assert_eq!(&matrix, qrCode.getMatrix().as_ref().unwrap()); - } +} - #[test] - fn testToString1() { - let qrCode = QRCode::new(); +#[test] +fn testToString1() { + let qrCode = QRCode::new(); let expected = "<<\n mode: null\n ecLevel: null\n version: null\n maskPattern: -1\n matrix: null\n>>\n"; - assert_eq!(expected, qrCode.to_string()); - } + assert_eq!(expected, qrCode.to_string()); +} - #[test] - fn testToString2() { - let mut qrCode = QRCode::new(); +#[test] +fn testToString2() { + let mut qrCode = QRCode::new(); qrCode.setMode(Mode::BYTE); qrCode.setECLevel(ErrorCorrectionLevel::H); qrCode.setVersion(Version::getVersionForNumber(1).expect("predefined value must exist")); qrCode.setMaskPattern(3); - let mut matrix = ByteMatrix::new(21, 21); + let mut matrix = ByteMatrix::new(21, 21); for y in 0..21 { - // for (int y = 0; y < 21; ++y) { - for x in 0..21 { - // for (int x = 0; x < 21; ++x) { - matrix.set(x, y, ((y + x) % 2) as u8); - } + // for (int y = 0; y < 21; ++y) { + for x in 0..21 { + // for (int x = 0; x < 21; ++x) { + matrix.set(x, y, ((y + x) % 2) as u8); + } } qrCode.setMatrix(matrix); let expected = "<<\n \ @@ -110,13 +111,12 @@ use super::QRCode; 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0\n\ >>\n"; assert_eq!(expected, qrCode.to_string()); - } +} - #[test] - fn testIsValidMaskPattern() { +#[test] +fn testIsValidMaskPattern() { assert!(!QRCode::isValidMaskPattern(-1)); assert!(QRCode::isValidMaskPattern(0)); assert!(QRCode::isValidMaskPattern(7)); assert!(!QRCode::isValidMaskPattern(8)); - } - +} diff --git a/src/qrcode/encoder/encoder.rs b/src/qrcode/encoder/encoder.rs index b688130..8b42cc4 100644 --- a/src/qrcode/encoder/encoder.rs +++ b/src/qrcode/encoder/encoder.rs @@ -43,7 +43,7 @@ use unicode_segmentation::UnicodeSegmentation; use crate::{ common::{ reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonEncoder}, - BitArray, CharacterSetECI, + BitArray, CharacterSetECI, }, qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef}, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Exceptions, @@ -155,9 +155,11 @@ pub fn encode_with_hints( let encoding = if encoding.is_some() { encoding.unwrap() } else { - if let Ok(_encs) = DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict){ + if let Ok(_encs) = + DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict) + { DEFAULT_BYTE_MODE_ENCODING - }else { + } else { has_encoding_hint = true; encoding::all::UTF_8 } @@ -302,8 +304,12 @@ fn recommendVersion( // Hard part: need to know version to know how many bits length takes. But need to know how many // bits it takes to know version. First we take a guess at version by assuming version will be // the minimum, 1: - let provisional_bits_needed = - calculateBitsNeeded(mode, header_bits, data_bits, Version::getVersionForNumber(1)?); + let provisional_bits_needed = calculateBitsNeeded( + mode, + header_bits, + data_bits, + Version::getVersionForNumber(1)?, + ); let provisional_version = chooseVersion(provisional_bits_needed, ec_level)?; // Use that guess to calculate the right version. I am still not sure this works in 100% of cases. diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index febbf8f..e047f78 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -48,10 +48,10 @@ pub fn applyMaskPenaltyRule2(matrix: &ByteMatrix) -> u32 { let array = matrix.getArray(); let width = matrix.getWidth(); let height = matrix.getHeight(); - for y in 0..(height -1) as usize { + for y in 0..(height - 1) as usize { // for (int y = 0; y < height - 1; y++) { let arrayY = &array[y]; - for x in 0..(width -1) as usize { + for x in 0..(width - 1) as usize { // for (int x = 0; x < width - 1; x++) { let value = arrayY[x]; if value == arrayY[x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1] { @@ -154,7 +154,8 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 { } } let numTotalCells = matrix.getHeight() * matrix.getWidth(); - let fivePercentVariances = (numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells; + let fivePercentVariances = + (numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells; return fivePercentVariances * N4; } diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index 6cca0f8..4074890 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -24,7 +24,7 @@ use crate::{ Exceptions, }; -use unicode_segmentation::{ UnicodeSegmentation}; +use unicode_segmentation::UnicodeSegmentation; use super::encoder; @@ -834,14 +834,15 @@ impl RXingResultList { } let first = list.get(0); // prepend or insert a FNC1_FIRST_POSITION after the ECI (if any) - if first.is_some() && first.as_ref().unwrap().mode != Mode::ECI {//&& containsECI { + if first.is_some() && first.as_ref().unwrap().mode != Mode::ECI { + //&& containsECI { list.insert( if first.as_ref().unwrap().mode != Mode::ECI { //first list.len() } else { //second - list.len()-1 + list.len() - 1 }, RXingResultNode::new( Mode::FNC1_FIRST_POSITION, diff --git a/src/qrcode/encoder/mod.rs b/src/qrcode/encoder/mod.rs index bc52f77..ba5ae87 100644 --- a/src/qrcode/encoder/mod.rs +++ b/src/qrcode/encoder/mod.rs @@ -1,23 +1,23 @@ -mod qr_code; -mod byte_matrix; mod block_pair; +mod byte_matrix; +pub mod encoder; pub mod mask_util; pub mod matrix_util; mod minimal_encoder; -pub mod encoder; +mod qr_code; -pub use qr_code::*; -pub use byte_matrix::*; pub use block_pair::*; +pub use byte_matrix::*; pub use minimal_encoder::*; +pub use qr_code::*; -#[cfg(test)] -mod QRCodeTestCase; #[cfg(test)] mod BitVectorTestCase; #[cfg(test)] +mod EncoderTestCase; +#[cfg(test)] mod MaskUtilTestCase; #[cfg(test)] mod MatrixUtilTestCase; #[cfg(test)] -mod EncoderTestCase; \ No newline at end of file +mod QRCodeTestCase; diff --git a/src/qrcode/encoder/qr_code.rs b/src/qrcode/encoder/qr_code.rs index 00835c2..63ec2e5 100644 --- a/src/qrcode/encoder/qr_code.rs +++ b/src/qrcode/encoder/qr_code.rs @@ -16,131 +16,124 @@ use std::fmt; -use crate::qrcode::decoder::{Mode, ErrorCorrectionLevel, Version, VersionRef}; +use crate::qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef}; use super::ByteMatrix; - /** * @author satorux@google.com (Satoru Takabayashi) - creator * @author dswitkin@google.com (Daniel Switkin) - ported from C++ */ #[derive(Debug, Clone)] pub struct QRCode { - - // public static final int NUM_MASK_PATTERNS = 8; - - mode:Option, - ecLevel:Option, - version:Option, - maskPattern:i32, - matrix:Option, - + // public static final int NUM_MASK_PATTERNS = 8; + mode: Option, + ecLevel: Option, + version: Option, + maskPattern: i32, + matrix: Option, } impl QRCode { - pub const NUM_MASK_PATTERNS : i32 = 8; + pub const NUM_MASK_PATTERNS: i32 = 8; - pub fn new()->Self { - Self { - mode: None, - ecLevel: None, - version: None, - maskPattern: -1, - matrix: None, + pub fn new() -> Self { + Self { + mode: None, + ecLevel: None, + version: None, + maskPattern: -1, + matrix: None, + } } - } - /** - * @return the mode. Not relevant if {@link com.google.zxing.EncodeHintType#QR_COMPACT} is selected. - */ - pub fn getMode(&self) -> &Option{ - &self.mode - } + /** + * @return the mode. Not relevant if {@link com.google.zxing.EncodeHintType#QR_COMPACT} is selected. + */ + pub fn getMode(&self) -> &Option { + &self.mode + } - pub fn getECLevel(&self) -> &Option{ - &self.ecLevel - } + pub fn getECLevel(&self) -> &Option { + &self.ecLevel + } - pub fn getVersion(&self) -> &Option<&'static Version>{ - &self.version - } + pub fn getVersion(&self) -> &Option<&'static Version> { + &self.version + } - pub fn getMaskPattern(&self) -> i32{ - self.maskPattern - } + pub fn getMaskPattern(&self) -> i32 { + self.maskPattern + } - pub fn getMatrix(&self) ->&Option{ - &self.matrix - } + pub fn getMatrix(&self) -> &Option { + &self.matrix + } - + pub fn setMode(&mut self, value: Mode) { + self.mode = Some(value); + } - pub fn setMode(&mut self, value:Mode) { - self.mode = Some(value); - } + pub fn setECLevel(&mut self, value: ErrorCorrectionLevel) { + self.ecLevel = Some(value); + } - pub fn setECLevel(&mut self, value:ErrorCorrectionLevel) { - self.ecLevel = Some(value); - } + pub fn setVersion(&mut self, version: &'static Version) { + self.version = Some(version); + } - pub fn setVersion(&mut self, version:&'static Version) { - self.version = Some(version); - } + pub fn setMaskPattern(&mut self, value: i32) { + self.maskPattern = value; + } - pub fn setMaskPattern(&mut self, value:i32) { - self.maskPattern = value; - } - - pub fn setMatrix(&mut self, value:ByteMatrix) { - self.matrix = Some(value); - } - - // Check if "mask_pattern" is valid. - pub fn isValidMaskPattern( maskPattern:i32) -> bool{ - maskPattern >= 0 && maskPattern < Self::NUM_MASK_PATTERNS - } + pub fn setMatrix(&mut self, value: ByteMatrix) { + self.matrix = Some(value); + } + // Check if "mask_pattern" is valid. + pub fn isValidMaskPattern(maskPattern: i32) -> bool { + maskPattern >= 0 && maskPattern < Self::NUM_MASK_PATTERNS + } } impl fmt::Display for QRCode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut result = String::with_capacity(200); - result.push_str("<<\n"); - result.push_str(" mode: "); - if self.mode.is_some() { - result.push_str(&format!("{:?}",self.mode.as_ref().unwrap())); - }else { - result.push_str("null"); - } - // result.push_str(&format!("{:?}", self.mode)); - result.push_str("\n ecLevel: "); - if self.ecLevel.is_some() { - result.push_str(&format!("{:?}",self.ecLevel.as_ref().unwrap())); - }else { - result.push_str("null"); - } - // result.push_str(&format!("{:?}", self.ecLevel)); - result.push_str("\n version: "); - if self.version.is_some() { - result.push_str(&format!("{}",self.version.as_ref().unwrap())); - }else { - result.push_str("null"); - } - result.push_str("\n maskPattern: "); - result.push_str(&format!("{}",self.maskPattern)); - if self.matrix.is_none() { - result.push_str("\n matrix: null\n"); - } else { - result.push_str("\n matrix:\n"); - if self.matrix.is_some() { - result.push_str(&format!("{}",self.matrix.as_ref().unwrap())); - }else { - result.push_str("null"); + let mut result = String::with_capacity(200); + result.push_str("<<\n"); + result.push_str(" mode: "); + if self.mode.is_some() { + result.push_str(&format!("{:?}", self.mode.as_ref().unwrap())); + } else { + result.push_str("null"); } - } - result.push_str(">>\n"); - - write!(f, "{}", result) + // result.push_str(&format!("{:?}", self.mode)); + result.push_str("\n ecLevel: "); + if self.ecLevel.is_some() { + result.push_str(&format!("{:?}", self.ecLevel.as_ref().unwrap())); + } else { + result.push_str("null"); + } + // result.push_str(&format!("{:?}", self.ecLevel)); + result.push_str("\n version: "); + if self.version.is_some() { + result.push_str(&format!("{}", self.version.as_ref().unwrap())); + } else { + result.push_str("null"); + } + result.push_str("\n maskPattern: "); + result.push_str(&format!("{}", self.maskPattern)); + if self.matrix.is_none() { + result.push_str("\n matrix: null\n"); + } else { + result.push_str("\n matrix:\n"); + if self.matrix.is_some() { + result.push_str(&format!("{}", self.matrix.as_ref().unwrap())); + } else { + result.push_str("null"); + } + } + result.push_str(">>\n"); + + write!(f, "{}", result) } -} \ No newline at end of file +} diff --git a/src/qrcode/mod.rs b/src/qrcode/mod.rs index 90ea2ca..c41b97f 100644 --- a/src/qrcode/mod.rs +++ b/src/qrcode/mod.rs @@ -1,5 +1,5 @@ -pub mod detector; pub mod decoder; +pub mod detector; pub mod encoder; mod qr_code_reader; @@ -9,4 +9,4 @@ mod qr_code_writer; pub use qr_code_writer::*; #[cfg(test)] -mod QRCodeWriterTestCase; \ No newline at end of file +mod QRCodeWriterTestCase; diff --git a/src/qrcode/qr_code_reader.rs b/src/qrcode/qr_code_reader.rs index 8c3ece3..0035bc3 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use crate::{ common::{BitMatrix, DecoderRXingResult, DetectorRXingResult}, BarcodeFormat, DecodeHintType, Exceptions, RXingResult, RXingResultMetadataType, - RXingResultMetadataValue, RXingResultPoint, Reader, + RXingResultMetadataValue, RXingResultPoint, Reader, }; use super::{ @@ -155,7 +155,7 @@ impl QRCodeReader { let moduleSize = Self::moduleSize(&leftTopBlack, image)?; let mut top = leftTopBlack[1] as i32; - let bottom = rightBottomBlack[1] as i32; + let bottom = rightBottomBlack[1] as i32; let mut left = leftTopBlack[0] as i32; let mut right = rightBottomBlack[0] as i32; @@ -193,7 +193,9 @@ 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 as i32 + + ((matrixWidth as i32 - 1) as f32 * moduleSize as f32) as i32 + - right as i32; if nudgedTooFarRight > 0 { if nudgedTooFarRight > nudge as i32 { // Neither way fits; abort diff --git a/src/reader.rs b/src/reader.rs index 544f600..bc015e4 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -17,7 +16,7 @@ //package com.google.zxing; -use crate::{BinaryBitmap, RXingResult, Exceptions, DecodingHintDictionary}; +use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult}; /** * Implementations of this interface can decode an image of a barcode in some format into @@ -68,4 +67,4 @@ pub trait Reader { * for reuse. */ fn reset(&self); -} \ No newline at end of file +} diff --git a/src/result_point.rs b/src/result_point.rs index 4261eff..256a6e5 100644 --- a/src/result_point.rs +++ b/src/result_point.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -23,4 +22,4 @@ pub trait ResultPoint { fn getX(&self) -> f32; fn getY(&self) -> f32; fn into_rxing_result_point(self) -> RXingResultPoint; -} \ No newline at end of file +} diff --git a/src/result_point_utils.rs b/src/result_point_utils.rs index c0bf936..0b0a0b1 100644 --- a/src/result_point_utils.rs +++ b/src/result_point_utils.rs @@ -1,89 +1,89 @@ use crate::{common::detector::MathUtils, ResultPoint}; - /** - * Orders an array of three RXingResultPoints in an order [A,B,C] such that AB is less than AC - * and BC is less than AC, and the angle between BC and BA is less than 180 degrees. - * - * @param patterns array of three {@code RXingResultPoint} to order - */ - pub fn orderBestPatterns(patterns: &mut [T; 3]) { - // Find distances between pattern centers - let zeroOneDistance = MathUtils::distance_float( - patterns[0].getX(), - patterns[0].getY(), - patterns[1].getX(), - patterns[1].getY(), - ); - let oneTwoDistance = MathUtils::distance_float( - patterns[1].getX(), - patterns[1].getY(), - patterns[2].getX(), - patterns[2].getY(), - ); - let zeroTwoDistance = MathUtils::distance_float( - patterns[0].getX(), - patterns[0].getY(), - patterns[2].getX(), - patterns[2].getY(), - ); +/** + * Orders an array of three RXingResultPoints in an order [A,B,C] such that AB is less than AC + * and BC is less than AC, and the angle between BC and BA is less than 180 degrees. + * + * @param patterns array of three {@code RXingResultPoint} to order + */ +pub fn orderBestPatterns(patterns: &mut [T; 3]) { + // Find distances between pattern centers + let zeroOneDistance = MathUtils::distance_float( + patterns[0].getX(), + patterns[0].getY(), + patterns[1].getX(), + patterns[1].getY(), + ); + let oneTwoDistance = MathUtils::distance_float( + patterns[1].getX(), + patterns[1].getY(), + patterns[2].getX(), + patterns[2].getY(), + ); + let zeroTwoDistance = MathUtils::distance_float( + patterns[0].getX(), + patterns[0].getY(), + patterns[2].getX(), + patterns[2].getY(), + ); - let mut pointA; //: &RXingResultPoint; - let pointB; //: &RXingResultPoint; - let mut pointC; //: &RXingResultPoint; - // Assume one closest to other two is B; A and C will just be guesses at first - if oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance { - pointB = patterns[0]; - pointA = patterns[1]; - pointC = patterns[2]; - } else if zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance { - pointB = patterns[1]; - pointA = patterns[0]; - pointC = patterns[2]; - } else { - pointB = patterns[2]; - pointA = patterns[0]; - pointC = patterns[1]; - } - - // Use cross product to figure out whether A and C are correct or flipped. - // This asks whether BC x BA has a positive z component, which is the arrangement - // we want for A, B, C. If it's negative, then we've got it flipped around and - // should swap A and C. - if crossProductZ(pointA, pointB, pointC) < 0.0f32 { - let temp = pointA; - pointA = pointC; - pointC = temp; - } - - let pa = pointA; - let pb = pointB; - let pc = pointC; - - patterns[0] = pa; - patterns[1] = pb; - patterns[2] = pc; + let mut pointA; //: &RXingResultPoint; + let pointB; //: &RXingResultPoint; + let mut pointC; //: &RXingResultPoint; + // Assume one closest to other two is B; A and C will just be guesses at first + if oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance { + pointB = patterns[0]; + pointA = patterns[1]; + pointC = patterns[2]; + } else if zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance { + pointB = patterns[1]; + pointA = patterns[0]; + pointC = patterns[2]; + } else { + pointB = patterns[2]; + pointA = patterns[0]; + pointC = patterns[1]; } - /** - * @param pattern1 first pattern - * @param pattern2 second pattern - * @return distance between two points - */ - pub fn distance(pattern1: &T, pattern2: &T) -> f32 { - return MathUtils::distance_float( - pattern1.getX(), - pattern1.getY(), - pattern2.getX(), - pattern2.getY(), - ); + // Use cross product to figure out whether A and C are correct or flipped. + // This asks whether BC x BA has a positive z component, which is the arrangement + // we want for A, B, C. If it's negative, then we've got it flipped around and + // should swap A and C. + if crossProductZ(pointA, pointB, pointC) < 0.0f32 { + let temp = pointA; + pointA = pointC; + pointC = temp; } - /** - * Returns the z component of the cross product between vectors BC and BA. - */ - 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)); - } \ No newline at end of file + let pa = pointA; + let pb = pointB; + let pc = pointC; + + patterns[0] = pa; + patterns[1] = pb; + patterns[2] = pc; +} + +/** + * @param pattern1 first pattern + * @param pattern2 second pattern + * @return distance between two points + */ +pub fn distance(pattern1: &T, pattern2: &T) -> f32 { + return MathUtils::distance_float( + pattern1.getX(), + pattern1.getY(), + pattern2.getX(), + pattern2.getY(), + ); +} + +/** + * Returns the z component of the cross product between vectors BC and BA. + */ +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)); +} diff --git a/src/rgb_luminance_source.rs b/src/rgb_luminance_source.rs index 5efe4e2..4f8ec20 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -1,4 +1,3 @@ - /* * Copyright 2009 ZXing authors * @@ -204,4 +203,4 @@ impl RGBLuminanceSource { invert: false, }) } -} \ No newline at end of file +} diff --git a/src/rxing_result.rs b/src/rxing_result.rs index b3701dd..16e6e61 100644 --- a/src/rxing_result.rs +++ b/src/rxing_result.rs @@ -1,4 +1,3 @@ - /* * Copyright 2007 ZXing authors * @@ -20,9 +19,13 @@ //import java.util.EnumMap; //import java.util.Map; -use std::{fmt, collections::HashMap, time::{SystemTime, UNIX_EPOCH}}; +use std::{ + collections::HashMap, + fmt, + time::{SystemTime, UNIX_EPOCH}, +}; -use crate::{RXingResultMetadataValue, RXingResultMetadataType, BarcodeFormat, RXingResultPoint}; +use crate::{BarcodeFormat, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint}; /** *

Encapsulates the result of decoding a barcode within an image.

@@ -177,4 +180,4 @@ impl fmt::Display for RXingResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.text) } -} \ No newline at end of file +} diff --git a/src/rxing_result_metadata.rs b/src/rxing_result_metadata.rs index d27d474..6d7dc7b 100644 --- a/src/rxing_result_metadata.rs +++ b/src/rxing_result_metadata.rs @@ -1,4 +1,3 @@ - /* * Copyright 2008 ZXing authors * @@ -201,4 +200,4 @@ pub enum RXingResultMetadataValue { * when prepending to the barcode content. */ SymbologyIdentifier(String), -} \ No newline at end of file +} diff --git a/src/rxing_result_point.rs b/src/rxing_result_point.rs index 2483d24..439f670 100644 --- a/src/rxing_result_point.rs +++ b/src/rxing_result_point.rs @@ -3,7 +3,6 @@ use std::fmt; use crate::ResultPoint; use std::hash::Hash; - /** *

Encapsulates a point of interest in an image containing a barcode. Typically, this * would be the location of a finder pattern or the corner of the barcode, for example.

@@ -13,7 +12,7 @@ use std::hash::Hash; #[derive(Debug, Clone, Copy)] pub struct RXingResultPoint { pub(crate) x: f32, - pub(crate)y: f32, + pub(crate) y: f32, } impl Hash for RXingResultPoint { fn hash(&self, state: &mut H) { @@ -51,4 +50,4 @@ impl fmt::Display for RXingResultPoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({},{})", self.x, self.y) } -} \ No newline at end of file +} diff --git a/src/writer.rs b/src/writer.rs index e2cc058..f07064d 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -1,4 +1,3 @@ - /* * Copyright 2008 ZXing authors * @@ -17,7 +16,7 @@ //package com.google.zxing; -use crate::{BarcodeFormat, common::BitMatrix, Exceptions, EncodingHintDictionary}; +use crate::{common::BitMatrix, BarcodeFormat, EncodingHintDictionary, Exceptions}; /** * The base class for all objects which encode/generate a barcode image. @@ -60,4 +59,4 @@ pub trait Writer { height: i32, hints: &EncodingHintDictionary, ) -> Result; -} \ No newline at end of file +} diff --git a/tests/common/abstract_black_box_test_case.rs b/tests/common/abstract_black_box_test_case.rs index 15e6af2..2c721e2 100644 --- a/tests/common/abstract_black_box_test_case.rs +++ b/tests/common/abstract_black_box_test_case.rs @@ -27,13 +27,11 @@ use rxing::{ use super::TestRXingResult; - - /** * @author Sean Owen * @author dswitkin@google.com (Daniel Switkin) */ -pub struct AbstractBlackBoxTestCase { +pub struct AbstractBlackBoxTestCase { test_base: Box, barcode_reader: T, expected_format: BarcodeFormat, @@ -41,8 +39,7 @@ pub struct AbstractBlackBoxTestCase { hints: HashMap, } -impl AbstractBlackBoxTestCase { - +impl AbstractBlackBoxTestCase { pub fn build_test_base(test_base_path_suffix: &str) -> Box { // A little workaround to prevent aggravation in my IDE let test_base = Path::new(test_base_path_suffix); @@ -125,7 +122,7 @@ impl AbstractBlackBoxTestCase { // .map(|r| r.into_boxed_path()) .collect::>(); - paths.sort(); + paths.sort(); paths } @@ -236,10 +233,10 @@ impl AbstractBlackBoxTestCase { let bitmap = BinaryBitmap::new(Box::new(HybridBinarizer::new(Box::new(source)))); // if file_base_name == "15" { - // let mut f = File::create("test_file_output.txt").unwrap(); - // write!(f,"{}", bitmap.getBlackMatrix().unwrap()); - // drop(f); - // Self::rotate_image(&image, rotation).save("test_image.png").unwrap(); + // let mut f = File::create("test_file_output.txt").unwrap(); + // write!(f,"{}", bitmap.getBlackMatrix().unwrap()); + // drop(f); + // Self::rotate_image(&image, rotation).save("test_image.png").unwrap(); // } if let Ok(decoded) = @@ -326,8 +323,8 @@ impl AbstractBlackBoxTestCase { total_must_pass += test_rxing_result.get_must_pass_count() + test_rxing_result.get_try_harder_count(); total_misread += misread_counts[x] + try_harder_misread_counts[x]; - total_max_misread += - test_rxing_result.get_max_misreads() + test_rxing_result.get_max_try_harder_misreads(); + total_max_misread += test_rxing_result.get_max_misreads() + + test_rxing_result.get_max_try_harder_misreads(); } let total_tests = image_files.len() * test_count * 2; @@ -390,7 +387,8 @@ impl AbstractBlackBoxTestCase { label ); assert!( - try_harder_misread_counts[x] <= test_rxing_result.get_max_try_harder_misreads() as usize, + try_harder_misread_counts[x] + <= test_rxing_result.get_max_try_harder_misreads() as usize, "Try harder, {}", label ); @@ -425,7 +423,8 @@ impl AbstractBlackBoxTestCase { DecodeHintType::PURE_BARCODE, DecodeHintValue::PureBarcode(true), ); - let mut result = if let Ok(res) = self.barcode_reader.decode_with_hints(source, &pure_hints) { + let mut result = if let Ok(res) = self.barcode_reader.decode_with_hints(source, &pure_hints) + { Some(res) } else { None diff --git a/tests/common/mod.rs b/tests/common/mod.rs index c57a95b..06f48dd 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,5 +1,5 @@ -mod test_result; mod abstract_black_box_test_case; +mod test_result; +pub use abstract_black_box_test_case::*; pub use test_result::*; -pub use abstract_black_box_test_case::*; \ No newline at end of file