diff --git a/.gitignore b/.gitignore index f451242..80e14dc 100644 --- a/.gitignore +++ b/.gitignore @@ -17,4 +17,6 @@ Cargo.lock .DS_Store +.idea + dbgfle* \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 844fb51..76e45e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ num = "0.4.0" svg = {version = "0.13", optional = true} resvg = {version = "0.28.0", optional = true, default-features=false} serde = { version = "1.0", features = ["derive", "rc"], optional = true } +thiserror = "1.0.38" [dev-dependencies] java-properties = "1.4.1" diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index 76e392c..e33c1b3 100644 --- a/src/aztec/aztec_reader.rs +++ b/src/aztec/aztec_reader.rs @@ -61,7 +61,7 @@ impl Reader for AztecReader { } else if let Ok(det) = detector.detect(true) { det } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; let points = detectorRXingResult.getPoints(); diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index fb36ae0..7eb7118 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -60,7 +60,7 @@ impl Writer for AztecWriter { if cset_name.to_lowercase() != "iso-8859-1" { charset = Some( encoding::label::encoding_from_whatwg_label(cset_name) - .ok_or(Exceptions::illegalArgument)?, + .ok_or(Exceptions::ILLEGAL_ARGUMENT)?, ); } } @@ -96,7 +96,7 @@ fn encode( layers: i32, ) -> Result { if format != BarcodeFormat::AZTEC { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "can only encode AZTEC, but got {format:?}" ))); } diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index 52b217b..c3ddafe 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -162,13 +162,13 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { result.push_str( &encdr .decode(&decoded_bytes, encoding::DecoderTrap::Strict) - .map_err(|a| Exceptions::illegalStateWith(a))?, + .map_err(|a| Exceptions::illegal_state_with(a))?, ); decoded_bytes.clear(); match n { 0 => result.push(29 as char), // translate FNC1 as ASCII 29 - 7 => return Err(Exceptions::formatWith("FLG(7) is reserved and illegal")), // FLG(7) is reserved and illegal + 7 => return Err(Exceptions::format_with("FLG(7) is reserved and illegal")), // FLG(7) is reserved and illegal _ => { // ECI is decimal integer encoded as 1-6 codes in DIGIT mode let mut eci = 0; @@ -180,7 +180,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { let next_digit = read_code(corrected_bits, index, 4); index += 4; if !(2..=11).contains(&next_digit) { - return Err(Exceptions::formatWith("Not a decimal digit")); + return Err(Exceptions::format_with("Not a decimal digit")); // Not a decimal digit } eci = eci * 10 + (next_digit - 2); @@ -188,7 +188,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { } let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); if charset_eci.is_err() { - return Err(Exceptions::formatWith("Charset must exist")); + return Err(Exceptions::format_with("Charset must exist")); } encdr = CharacterSetECI::getCharset(&charset_eci?); } @@ -201,8 +201,8 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { // That's including when that mode is a shift. // Our test case dlusbs.png for issue #642 exercises that. latch_table = shift_table; // Latch the current mode, so as to return to Upper after U/S B/S - shift_table = getTable(str.chars().nth(5).ok_or(Exceptions::indexOutOfBounds)?); - if str.chars().nth(6).ok_or(Exceptions::indexOutOfBounds)? == 'L' { + shift_table = getTable(str.chars().nth(5).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?); + if str.chars().nth(6).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == 'L' { latch_table = shift_table; } } else { @@ -223,7 +223,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) { result.push_str(&str); } else { - return Err(Exceptions::illegalStateWith("bad encoding")); + return Err(Exceptions::illegal_state_with("bad encoding")); } // result.push_str(decodedBytes.toString(encoding.name())); //} catch (UnsupportedEncodingException uee) { @@ -275,7 +275,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str> { Table::Mixed => Ok(MIXED_TABLE[code as usize]), Table::Digit => Ok(DIGIT_TABLE[code as usize]), Table::Punct => Ok(PUNCT_TABLE[code as usize]), - _ => Err(Exceptions::illegalStateWith("Bad table")), + _ => Err(Exceptions::illegal_state_with("Bad table")), } // switch (table) { // case UPPER: @@ -336,7 +336,7 @@ fn correct_bits( let num_data_codewords = ddata.getNbDatablocks(); let num_codewords = rawbits.len() / codeword_size; if num_codewords < num_data_codewords as usize { - return Err(Exceptions::formatWith(format!( + return Err(Exceptions::format_with(format!( "numCodewords {num_codewords}< numDataCodewords{num_data_codewords}" ))); } @@ -369,7 +369,7 @@ fn correct_bits( // for (int i = 0; i < numDataCodewords; i++) { // let data_word = data_words[i]; if data_word == &0 || data_word == &mask { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); //throw FormatException.getFormatInstance(); } else if data_word == &1 || data_word == &(mask - 1) { stuffed_bits += 1; diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index 4cbae88..4f49111 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -124,7 +124,7 @@ impl<'a> Detector<'_> { || !self.is_valid(bulls_eye_corners[2]) || !self.is_valid(bulls_eye_corners[3]) { - return Err(Exceptions::notFoundWith("no valid points")); + return Err(Exceptions::not_found_with("no valid points")); } let length = 2 * self.nb_center_layers; // Get the bits around the bull's eye @@ -205,7 +205,7 @@ impl<'a> Detector<'_> { return Ok(shift); } } - Err(Exceptions::notFoundWith("rotation failure")) + Err(Exceptions::not_found_with("rotation failure")) } /** @@ -314,7 +314,7 @@ impl<'a> Detector<'_> { } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } self.compact = self.nb_center_layers == 5; diff --git a/src/aztec/encoder/aztec_encoder.rs b/src/aztec/encoder/aztec_encoder.rs index e8b8544..84f9827 100644 --- a/src/aztec/encoder/aztec_encoder.rs +++ b/src/aztec/encoder/aztec_encoder.rs @@ -53,7 +53,7 @@ pub const WORD_SIZE: [u32; 33] = [ pub fn encode_simple(data: &str) -> Result { let Ok(bytes) = encoding::all::ISO_8859_1 .encode(data, encoding::EncoderTrap::Replace) else { - return Err(Exceptions::illegalArgumentWith(format!("'{data}' cannot be encoded as ISO_8859_1"))); + return Err(Exceptions::illegal_argument_with(format!("'{data}' cannot be encoded as ISO_8859_1"))); }; encode_bytes_simple(&bytes) } @@ -71,7 +71,7 @@ pub fn encode(data: &str, minECCPercent: u32, userSpecifiedLayers: i32) -> Resul if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) { encode_bytes(&bytes, minECCPercent, userSpecifiedLayers) } else { - Err(Exceptions::illegalArgumentWith(format!( + Err(Exceptions::illegal_argument_with(format!( "'{data}' cannot be encoded as ISO_8859_1" ))) } @@ -98,7 +98,7 @@ pub fn encode_with_charset( if let Ok(bytes) = charset.encode(data, encoding::EncoderTrap::Strict) { encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset) } else { - Err(Exceptions::illegalArgumentWith(format!( + Err(Exceptions::illegal_argument_with(format!( "'{data}' cannot be encoded as ISO_8859_1" ))) } @@ -174,7 +174,7 @@ pub fn encode_bytes_with_charset( MAX_NB_BITS }) { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Illegal value {user_specified_layers} for layers" ))); } @@ -183,13 +183,13 @@ pub fn encode_bytes_with_charset( let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size); stuffed_bits = stuffBits(&bits, word_size as usize)?; if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Data to large for user specified layer", )); } if compact && stuffed_bits.getSize() as u32 > word_size * 64 { // Compact format only allows 64 data words, though C4 can hold more words than that - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Data to large for user specified layer", )); } @@ -203,7 +203,7 @@ pub fn encode_bytes_with_charset( loop { // for (int i = 0; ; i++) { if i > MAX_NB_BITS { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Data too large for an Aztec code", )); } @@ -474,7 +474,7 @@ fn getGF(wordSize: usize) -> Result { 8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)), 10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)), 12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)), - _ => Err(Exceptions::illegalArgumentWith(format!( + _ => Err(Exceptions::illegal_argument_with(format!( "Unsupported word size {wordSize}" ))), } diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index 3c4dde2..148aead 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -248,7 +248,7 @@ impl HighLevelEncoder { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "No ECI code for character set", )); } diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index 62a99f5..e90f3ef 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -83,7 +83,7 @@ impl State { token.add(0, 3); // 0: FNC1 } else */ if eci > 999999 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "ECI code must be between 0 and 999999", )); // throw new IllegalArgumentException("ECI code must be between 0 and 999999"); @@ -91,7 +91,7 @@ impl State { let Ok(eci_digits) = encoding::all::ISO_8859_1 .encode(&format!("{eci}"), encoding::EncoderTrap::Strict) else { - return Err(Exceptions::illegalArgument) + return Err(Exceptions::ILLEGAL_ARGUMENT) }; // let eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1); token.add(eci_digits.len() as i32, 3); // 1-6: number of ECI digits diff --git a/src/aztec/encoder/token.rs b/src/aztec/encoder/token.rs index 671ecca..92271ad 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -34,7 +34,7 @@ impl TokenType { match self { TokenType::Simple(a) => a.appendTo(bit_array, text), TokenType::BinaryShift(a) => a.appendTo(bit_array, text), - TokenType::Empty => Err(Exceptions::illegalStateWith( + TokenType::Empty => Err(Exceptions::illegal_state_with( "cannot appendTo on Empty final item", )), } diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index dcb6e76..40e98ea 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -121,17 +121,17 @@ impl AddressBookParsedRXingResult { geo: Vec, ) -> Result { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Phone numbers and types lengths differ", )); } if emails.len() != email_types.len() && !email_types.is_empty() { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Emails and types lengths differ", )); } if addresses.len() != address_types.len() && !address_types.is_empty() { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Addresses and types lengths differ", )); } diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index ece40fd..928022c 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -167,7 +167,7 @@ impl CalendarParsedRXingResult { */ fn parseDate(when: String) -> Result { if !DATE_TIME.is_match(&when) { - return Err(Exceptions::parseWith(when)); + return Err(Exceptions::parse_with(when)); } if when.len() == 8 { // Show only year/month/day @@ -178,14 +178,14 @@ impl CalendarParsedRXingResult { // http://code.google.com/p/android/issues/detail?id=8330 return match Utc.datetime_from_str(&format!("{}T000000Z", &when,), date_format_string) { Ok(dtm) => Ok(dtm.timestamp()), - Err(e) => Err(Exceptions::parseWith(e.to_string())), + Err(e) => Err(Exceptions::parse_with(e.to_string())), }; } // The when string can be local time, or UTC if it ends with a Z - if when.len() == 16 && when.chars().nth(15).ok_or(Exceptions::indexOutOfBounds)? == 'Z' { + if when.len() == 16 && when.chars().nth(15).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == 'Z' { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") { Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()), - Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))), + Err(e) => Err(Exceptions::parse_with(format!("couldn't parse string: {e}"))), }; } // Try once more, with weird tz formatting @@ -195,14 +195,14 @@ impl CalendarParsedRXingResult { let tz_parsed: Tz = match tz_part.parse() { Ok(time_zone) => time_zone, Err(e) => { - return Err(Exceptions::parseWith(format!( + return Err(Exceptions::parse_with(format!( "couldn't parse timezone '{tz_part}': {e}" ))) } }; return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") { Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()), - Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))), + Err(e) => Err(Exceptions::parse_with(format!("couldn't parse string: {e}"))), }; } @@ -210,7 +210,7 @@ impl CalendarParsedRXingResult { if when.len() == 15 { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") { Ok(dtm) => Ok(dtm.timestamp()), - Err(e) => Err(Exceptions::parseWith(format!( + Err(e) => Err(Exceptions::parse_with(format!( "couldn't parse local time: {e}" ))), }; @@ -249,7 +249,7 @@ impl CalendarParsedRXingResult { let z = parseable .as_str() .parse::() - .map_err(|e| Exceptions::parseWith(e.to_string()))?; + .map_err(|e| Exceptions::parse_with(e.to_string()))?; durationMS += unit * z; } } @@ -274,7 +274,7 @@ impl CalendarParsedRXingResult { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { Ok(dtm.timestamp()) } else { - Err(Exceptions::parseWith(format!( + Err(Exceptions::parse_with(format!( "Couldn't parse {dateTimeString}" ))) } diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index 8da188f..32f9356 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -300,7 +300,7 @@ pub fn urlDecode(encoded: &str) -> Result { if let Ok(decoded) = decode(encoded) { Ok(decoded.to_string()) } else { - Err(Exceptions::illegalStateWith("UnsupportedEncodingException")) + Err(Exceptions::illegal_state_with("UnsupportedEncodingException")) } } diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 6c25925..5fa1fb7 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -72,9 +72,9 @@ fn check_checksum(vin: &str) -> Result { let mut sum = 0; for i in 0..vin.len() { sum += vin_position_weight(i + 1)? as u32 - * vin_char_value(vin.chars().nth(i).ok_or(Exceptions::illegalArgument)?)?; + * vin_char_value(vin.chars().nth(i).ok_or(Exceptions::ILLEGAL_ARGUMENT)?)?; } - let check_to_char = vin.chars().nth(8).ok_or(Exceptions::illegalArgument)?; + let check_to_char = vin.chars().nth(8).ok_or(Exceptions::ILLEGAL_ARGUMENT)?; let expected_check_char = check_char((sum % 11) as u8)?; Ok(check_to_char == expected_check_char) } @@ -85,7 +85,7 @@ fn vin_char_value(c: char) -> Result { 'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1), 'S'..='Z' => Ok((c as u8 as u32 - b'S' as u32) + 2), '0'..='9' => Ok(c as u8 as u32 - b'0' as u32), - _ => Err(Exceptions::illegalArgumentWith("vin char out of range")), + _ => Err(Exceptions::illegal_argument_with("vin char out of range")), } } @@ -95,7 +95,7 @@ fn vin_position_weight(position: usize) -> Result { 8 => Ok(10), 9 => Ok(0), 10..=17 => Ok(19 - position), - _ => Err(Exceptions::illegalArgumentWith( + _ => Err(Exceptions::illegal_argument_with( "vin position weight out of bounds", )), } @@ -105,7 +105,7 @@ fn check_char(remainder: u8) -> Result { match remainder { 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), - _ => Err(Exceptions::illegalArgumentWith("remainder too high")), + _ => Err(Exceptions::illegal_argument_with("remainder too high")), } } @@ -118,7 +118,7 @@ fn model_year(c: char) -> Result { 'V'..='Y' => Ok((c as u8 as u32 - b'V' as u32) + 1997), '1'..='9' => Ok((c as u8 as u32 - b'1' as u32) + 2001), 'A'..='D' => Ok((c as u8 as u32 - b'A' as u32) + 2010), - _ => Err(Exceptions::illegalArgumentWith( + _ => Err(Exceptions::illegal_argument_with( "model year argument out of range", )), } diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 471c4a8..cd6fabc 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -169,7 +169,7 @@ impl BitArray { pub fn setRange(&mut self, start: usize, end: usize) -> Result<()> { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } if end == start { return Ok(()); @@ -212,7 +212,7 @@ impl BitArray { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } if end == start { return Ok(true); // empty range matches @@ -254,7 +254,7 @@ impl BitArray { */ pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<()> { if num_bits > 32 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "num bits must be between 0 and 32", )); } @@ -287,7 +287,7 @@ impl BitArray { pub fn xor(&mut self, other: &BitArray) -> Result<()> { if self.size != other.size { - return Err(Exceptions::illegalArgumentWith("Sizes don't match")); + return Err(Exceptions::illegal_argument_with("Sizes don't match")); } for i in 0..self.bits.len() { //for (int i = 0; i < bits.length; i++) { diff --git a/src/common/bit_matrix.rs b/src/common/bit_matrix.rs index 7f1e7a4..8c9a4d5 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -66,7 +66,7 @@ impl BitMatrix { */ pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Both dimensions must be greater than 0", )); } @@ -138,12 +138,12 @@ impl BitMatrix { if string_representation .chars() .nth(pos) - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? == '\n' || string_representation .chars() .nth(pos) - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? == '\r' { if bitsPos > rowStartPos { @@ -152,7 +152,7 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgumentWith("row lengths do not match")); + return Err(Exceptions::illegal_argument_with("row lengths do not match")); } rowStartPos = bitsPos; nRows += 1; @@ -167,7 +167,7 @@ impl BitMatrix { bits[bitsPos] = false; bitsPos += 1; } else { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "illegal character encountered: {}", string_representation[pos..].to_owned() ))); @@ -181,7 +181,7 @@ impl BitMatrix { // first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgumentWith("row lengths do not match")); + return Err(Exceptions::illegal_argument_with("row lengths do not match")); } nRows += 1; } @@ -308,7 +308,7 @@ impl BitMatrix { pub fn xor(&mut self, mask: &BitMatrix) -> Result<()> { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "input matrix dimensions do not match", )); } @@ -354,14 +354,14 @@ impl BitMatrix { // )); // } if height < 1 || width < 1 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "height and width must be at least 1", )); } let right = left + width; let bottom = top + height; if bottom > self.height || right > self.width { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "the region must fit inside the matrix", )); } @@ -435,7 +435,7 @@ impl BitMatrix { self.rotate180(); Ok(()) } - _ => Err(Exceptions::illegalArgumentWith( + _ => Err(Exceptions::illegal_argument_with( "degrees must be a multiple of 0, 90, 180, or 270", )), } diff --git a/src/common/bit_source.rs b/src/common/bit_source.rs index ae97e48..7e10f4e 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -71,7 +71,7 @@ impl BitSource { */ pub fn readBits(&mut self, numBits: usize) -> Result { if !(1..=32).contains(&numBits) || numBits > self.available() { - return Err(Exceptions::illegalArgumentWith(numBits.to_string())); + return Err(Exceptions::illegal_argument_with(numBits.to_string())); } let mut result: u32 = 0; diff --git a/src/common/character_set_eci.rs b/src/common/character_set_eci.rs index 0d08479..61b607a 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -245,7 +245,7 @@ impl CharacterSetECI { 28 => Ok(CharacterSetECI::Big5), 29 => Ok(CharacterSetECI::GB18030), 30 => Ok(CharacterSetECI::EUC_KR), - _ => Err(Exceptions::notFoundWith("Bad ECI Value")), + _ => Err(Exceptions::not_found_with("Bad ECI Value")), } } diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index 96886f7..55e9d4b 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -68,7 +68,7 @@ impl GridSampler for DefaultGridSampler { transform: &PerspectiveTransform, ) -> Result { if dimensionX == 0 || dimensionY == 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut bits = BitMatrix::new(dimensionX, dimensionY)?; let mut points = vec![0.0; 2 * dimensionX as usize]; @@ -99,7 +99,7 @@ impl GridSampler for DefaultGridSampler { // } if image .try_get(points[x] as u32, points[x + 1] as u32) - .ok_or(Exceptions::notFoundWith( + .ok_or(Exceptions::not_found_with( "index out of bounds, see documentation in file for explanation", ))? { diff --git a/src/common/detector/monochrome_rectangle_detector.rs b/src/common/detector/monochrome_rectangle_detector.rs index c7dfc86..bf9f2ef 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -203,13 +203,13 @@ impl<'a> MonochromeRectangleDetector<'_> { } } } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } lastRange_z = range; y += deltaY; x += deltaX } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index bb53065..d705387 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -78,7 +78,7 @@ impl<'a> WhiteRectangleDetector<'_> { || downInit >= image.getHeight() as i32 || rightInit >= image.getWidth() as i32 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(WhiteRectangleDetector { @@ -224,7 +224,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if z.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut t: Option = None; @@ -242,7 +242,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if t.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut x: Option = None; @@ -260,7 +260,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if x.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut y: Option = None; @@ -278,12 +278,12 @@ impl<'a> WhiteRectangleDetector<'_> { } if y.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(self.center_edges(y.unwrap(), z.unwrap(), x.unwrap(), t.unwrap())) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index 82f2091..1292ef5 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -234,7 +234,7 @@ impl GlobalHistogramBinarizer { // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if secondPeak - firstPeak <= numBuckets / 16 { - return Err(Exceptions::notFoundWith( + return Err(Exceptions::not_found_with( "secondPeak - firstPeak <= numBuckets / 16 ", )); } diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index f5cee06..6477f1f 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -146,7 +146,7 @@ pub trait GridSampler { let x = points[offset] as i32; let y = points[offset + 1] as i32; if x < -1 || x > width as i32 || y < -1 || y > height as i32 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } nudged = false; if x == -1 { @@ -173,7 +173,7 @@ pub trait GridSampler { let x = points[offset as usize] as i32; let y = points[offset as usize + 1] as i32; if x < -1 || x > width as i32 || y < -1 || y > height as i32 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } nudged = false; if x == -1 { diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index 881b18f..b6b9cc1 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -68,10 +68,10 @@ impl ECIInput for MinimalECIInput { */ fn charAt(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBoundsWith(index.to_string())); + return Err(Exceptions::index_out_of_bounds_with(index.to_string())); } if self.isECI(index as u32)? { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "value at {index} is not a character but an ECI" ))); } @@ -104,13 +104,13 @@ impl ECIInput for MinimalECIInput { */ fn subSequence(&self, start: usize, end: usize) -> Result> { if start > end || end > self.length() { - return Err(Exceptions::indexOutOfBounds); + return Err(Exceptions::INDEX_OUT_OF_BOUNDS); } let mut result = String::new(); for i in start..end { // for (int i = start; i < end; i++) { if self.isECI(i as u32)? { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "value at {i} is not a character but an ECI" ))); } @@ -132,7 +132,7 @@ impl ECIInput for MinimalECIInput { */ fn isECI(&self, index: u32) -> Result { if index >= self.length() as u32 { - return Err(Exceptions::indexOutOfBounds); + return Err(Exceptions::INDEX_OUT_OF_BOUNDS); } Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) } @@ -157,10 +157,10 @@ impl ECIInput for MinimalECIInput { */ fn getECIValue(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBounds); + return Err(Exceptions::INDEX_OUT_OF_BOUNDS); } if !self.isECI(index as u32)? { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "value at {index} is not an ECI but a character" ))); } @@ -249,7 +249,7 @@ impl MinimalECIInput { */ pub fn isFNC1(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBounds); + return Err(Exceptions::INDEX_OUT_OF_BOUNDS); } Ok(self.bytes[index] == 1000) } diff --git a/src/common/otsu_level_binarizer.rs b/src/common/otsu_level_binarizer.rs index 2fbe692..bcd5921 100644 --- a/src/common/otsu_level_binarizer.rs +++ b/src/common/otsu_level_binarizer.rs @@ -20,7 +20,7 @@ impl OtsuLevelBinarizer { fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result { let image_buffer = { let Some(buff) : Option,Vec>> = ImageBuffer::from_vec(source.getWidth() as u32, source.getHeight() as u32, source.getMatrix()) else { - return Err(Exceptions::illegalArgument) + return Err(Exceptions::ILLEGAL_ARGUMENT) }; buff }; diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index a7e0628..d512a2e 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -134,7 +134,7 @@ impl GenericGF { */ pub fn log(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } // let pos: usize = a.try_into().unwrap(); Ok(self.logTable[a as usize]) @@ -145,7 +145,7 @@ impl GenericGF { */ pub fn inverse(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::arithmetic); + return Err(Exceptions::ARITHMETIC); } let log_t_loc: usize = a as usize; let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize; diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index 0c6ee12..ad6a3c5 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -50,7 +50,7 @@ impl GenericGFPoly { */ pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { if coefficients.is_empty() { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "coefficients cannot be empty", )); } @@ -141,7 +141,7 @@ impl GenericGFPoly { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "GenericGFPolys do not have same GenericGF field", )); } @@ -178,7 +178,7 @@ impl GenericGFPoly { pub fn multiply(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "GenericGFPolys do not have same GenericGF field", )); } @@ -246,12 +246,12 @@ impl GenericGFPoly { pub fn divide(&self, other: &GenericGFPoly) -> Result<(GenericGFPoly, GenericGFPoly)> { if self.field != other.field { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "GenericGFPolys do not have same GenericGF field", )); } if other.isZero() { - return Err(Exceptions::illegalArgumentWith("Divide by 0")); + return Err(Exceptions::illegal_argument_with("Divide by 0")); } let mut quotient = self.getZero(); @@ -260,7 +260,7 @@ impl GenericGFPoly { let denominator_leading_term = other.getCoefficient(other.getDegree()); let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) { Ok(val) => val, - Err(_issue) => return Err(Exceptions::illegalArgumentWith("arithmetic issue")), + Err(_issue) => return Err(Exceptions::illegal_argument_with("arithmetic issue")), }; while remainder.getDegree() >= other.getDegree() && !remainder.isZero() { diff --git a/src/common/reedsolomon/reedsolomon_decoder.rs b/src/common/reedsolomon/reedsolomon_decoder.rs index 50a0c5e..ccc056f 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -78,7 +78,7 @@ impl ReedSolomonDecoder { return Ok(0); } let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else { - return Err(Exceptions::reedSolomon); + return Err(Exceptions::REED_SOLOMON); }; let sigmaOmega = self.runEuclideanAlgorithm( &GenericGF::buildMonomial(self.field, twoS as usize, 1), @@ -93,11 +93,11 @@ impl ReedSolomonDecoder { //for (int i = 0; i < errorLocations.length; i++) { let log_value = self.field.log(errorLocations[i] as i32)?; if log_value > received.len() as i32 - 1 { - return Err(Exceptions::reedSolomonWith("Bad error location")); + return Err(Exceptions::reed_solomon_with("Bad error location")); } let position: isize = received.len() as isize - 1 - log_value as isize; if position < 0 { - return Err(Exceptions::reedSolomonWith("Bad error location")); + return Err(Exceptions::reed_solomon_with("Bad error location")); } received[position as usize] = GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); @@ -135,7 +135,7 @@ impl ReedSolomonDecoder { // Divide rLastLast by rLast, with quotient in q and remainder in r if rLast.isZero() { // Oops, Euclidean algorithm already terminated? - return Err(Exceptions::reedSolomonWith("r_{i-1} was zero")); + return Err(Exceptions::reed_solomon_with("r_{i-1} was zero")); } r = rLastLast; let mut q = r.getZero(); @@ -153,7 +153,7 @@ impl ReedSolomonDecoder { t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?; if r.getDegree() >= rLast.getDegree() { - return Err(Exceptions::reedSolomonWith(format!( + return Err(Exceptions::reed_solomon_with(format!( "Division algorithm failed to reduce polynomial? r: {r}, rLast: {rLast}" ))); } @@ -161,12 +161,12 @@ impl ReedSolomonDecoder { let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::reedSolomonWith("sigmaTilde(0) was zero")); + return Err(Exceptions::reed_solomon_with("sigmaTilde(0) was zero")); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, - Err(_err) => return Err(Exceptions::reedSolomonWith("ArithmetricException")), + Err(_err) => return Err(Exceptions::reed_solomon_with("ArithmetricException")), }; let sigma = t.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse); @@ -194,7 +194,7 @@ impl ReedSolomonDecoder { } } if e != numErrors { - return Err(Exceptions::reedSolomonWith( + return Err(Exceptions::reed_solomon_with( "Error locator degree does not match number of roots", )); } diff --git a/src/common/reedsolomon/reedsolomon_encoder.rs b/src/common/reedsolomon/reedsolomon_encoder.rs index 1b54556..bcc027e 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -74,11 +74,11 @@ impl ReedSolomonEncoder { pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<()> { if ec_bytes == 0 { - return Err(Exceptions::illegalArgumentWith("No error correction bytes")); + return Err(Exceptions::illegal_argument_with("No error correction bytes")); } let data_bytes = to_encode.len() - ec_bytes; if data_bytes == 0 { - return Err(Exceptions::illegalArgumentWith("No data bytes provided")); + return Err(Exceptions::illegal_argument_with("No data bytes provided")); } let fld = self.field; let generator = self.buildGenerator(ec_bytes); @@ -87,7 +87,7 @@ impl ReedSolomonEncoder { //System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); let mut info = GenericGFPoly::new(fld, &info_coefficients)?; info = info.multiply_by_monomial(ec_bytes, 1)?; - let remainder = &info.divide(generator.ok_or(Exceptions::reedSolomon)?)?.1; + let remainder = &info.divide(generator.ok_or(Exceptions::REED_SOLOMON)?)?.1; let coefficients = remainder.getCoefficients(); let num_zero_coefficients = ec_bytes - coefficients.len(); for i in 0..num_zero_coefficients { diff --git a/src/datamatrix/data_matrix_reader.rs b/src/datamatrix/data_matrix_reader.rs index ae16eed..4c1f845 100644 --- a/src/datamatrix/data_matrix_reader.rs +++ b/src/datamatrix/data_matrix_reader.rs @@ -102,7 +102,7 @@ impl Reader for DataMatrixReader { DECODER.decode(&bits)? } } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; // decoderRXingResult = DECODER.decode(detectorRXingResult.getBits())?; @@ -178,10 +178,10 @@ impl DataMatrixReader { */ fn extractPureBits(&self, image: &BitMatrix) -> Result { let Some(leftTopBlack) = image.getTopLeftOnBit() else { - return Err(Exceptions::notFound) + return Err(Exceptions::NOT_FOUND) }; let Some(rightBottomBlack) = image.getBottomRightOnBit()else { - return Err(Exceptions::notFound) + return Err(Exceptions::NOT_FOUND) }; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -194,7 +194,7 @@ impl DataMatrixReader { let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32; let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32; if matrixWidth <= 0 || matrixHeight <= 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); // throw NotFoundException.getNotFoundInstance(); } @@ -231,12 +231,12 @@ impl DataMatrixReader { x += 1; } if x == width { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let moduleSize = x - leftTopBlack[0]; if moduleSize == 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(moduleSize) diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index c060f95..cafffb9 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -61,17 +61,17 @@ impl Writer for DataMatrixWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgumentWith("Found empty contents")); + return Err(Exceptions::illegal_argument_with("Found empty contents")); } if format != &BarcodeFormat::DATA_MATRIX { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Can only encode DATA_MATRIX, but got {format:?}" ))); } if width < 0 || height < 0 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested dimensions can't be negative: {width}x{height}" ))); } @@ -122,7 +122,7 @@ impl Writer for DataMatrixWriter { if hasEncodingHint { let Some(EncodeHintValue::CharacterSet(char_set_name)) = hints.get(&EncodeHintType::CHARACTER_SET) else { - return Err(Exceptions::illegalArgumentWith("charset does not exist")) + return Err(Exceptions::illegal_argument_with("charset does not exist")) }; charset = encoding::label::encoding_from_whatwg_label(char_set_name); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); @@ -156,7 +156,7 @@ impl Writer for DataMatrixWriter { let symbol_lookup = SymbolInfoLookup::new(); let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else { - return Err(Exceptions::notFoundWith("symbol info is bad")) + return Err(Exceptions::not_found_with("symbol info is bad")) }; //2. step: ECC generation diff --git a/src/datamatrix/decoder/bit_matrix_parser.rs b/src/datamatrix/decoder/bit_matrix_parser.rs index f38845f..9988e60 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -37,7 +37,7 @@ impl BitMatrixParser { pub fn new(bitMatrix: &BitMatrix) -> Result { let dimension = bitMatrix.getHeight(); if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let version = Self::readVersion(bitMatrix)?; @@ -181,7 +181,7 @@ impl BitMatrixParser { } if resultOffset != self.version.getTotalCodewords() as usize { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } Ok(result) @@ -456,7 +456,7 @@ impl BitMatrixParser { let symbolSizeColumns = version.getSymbolSizeColumns(); if bitMatrix.getHeight() != symbolSizeRows { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Dimension of bitMatrix must match the version size", )); } diff --git a/src/datamatrix/decoder/data_block.rs b/src/datamatrix/decoder/data_block.rs index 2f3ea05..6fdc9b1 100644 --- a/src/datamatrix/decoder/data_block.rs +++ b/src/datamatrix/decoder/data_block.rs @@ -139,7 +139,7 @@ impl DataBlock { } if rawCodewordsOffset != rawCodewords.len() { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } Ok(result) diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index 455e313..4488cfc 100644 --- a/src/datamatrix/decoder/decoded_bit_stream_parser.rs +++ b/src/datamatrix/decoder/decoded_bit_stream_parser.rs @@ -158,7 +158,7 @@ pub fn decode(bytes: &[u8], is_flipped: bool) -> Result { isECIencoded = true; // ECI detection only, atm continue decoding as ASCII mode = Mode::ASCII_ENCODE; } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } if !(mode != Mode::PAD_ENCODE && bits.available() > 0) { @@ -225,14 +225,14 @@ fn decodeAsciiSegment( loop { let mut oneByte = bits.readBits(8)?; match oneByte { - 0 => return Err(Exceptions::format), + 0 => return Err(Exceptions::FORMAT), 1..=128 => { // ASCII data (ASCII value + 1) if upperShift { oneByte += 128; //upperShift = false; } - result.append_char(char::from_u32(oneByte - 1).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(oneByte - 1).ok_or(Exceptions::PARSE)?); return Ok(Mode::ASCII_ENCODE); } 129 => return Ok(Mode::PAD_ENCODE), // Pad @@ -278,7 +278,7 @@ fn decodeAsciiSegment( if !firstCodeword // Must be first ISO 16022:2006 5.6.1 { - return Err(Exceptions::formatWith( + return Err(Exceptions::format_with( "structured append tag must be first code word", )); } @@ -331,7 +331,7 @@ fn decodeAsciiSegment( // Not to be used in ASCII encodation // but work around encoders that end with 254, latch back to ASCII if oneByte != 254 || bits.available() != 0 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } } @@ -385,22 +385,22 @@ fn decodeC40Segment( let c40char = C40_BASIC_SET_CHARS[cValue as usize]; if upperShift { result.append_char( - char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?, + char::from_u32(c40char as u32 + 128).ok_or(Exceptions::PARSE)?, ); upperShift = false; } else { result.append_char(c40char); } } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } 1 => { if upperShift { - result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::PARSE)?); upperShift = false; } else { - result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::PARSE)?); } shift = 0; } @@ -409,7 +409,7 @@ fn decodeC40Segment( let c40char = C40_SHIFT2_SET_CHARS[cValue as usize]; if upperShift { result.append_char( - char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?, + char::from_u32(c40char as u32 + 128).ok_or(Exceptions::PARSE)?, ); upperShift = false; } else { @@ -428,22 +428,22 @@ fn decodeC40Segment( upperShift = true } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } shift = 0; } 3 => { if upperShift { - result.append_char(char::from_u32(cValue + 224).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 224).ok_or(Exceptions::PARSE)?); upperShift = false; } else { - result.append_char(char::from_u32(cValue + 96).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 96).ok_or(Exceptions::PARSE)?); } shift = 0; } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } if bits.available() == 0 { @@ -492,22 +492,22 @@ fn decodeTextSegment( let textChar = TEXT_BASIC_SET_CHARS[cValue as usize]; if upperShift { result.append_char( - char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::PARSE)?, ); upperShift = false; } else { result.append_char(textChar); } } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } 1 => { if upperShift { - result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::PARSE)?); upperShift = false; } else { - result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::PARSE)?); } shift = 0; } @@ -518,7 +518,7 @@ fn decodeTextSegment( let textChar = TEXT_SHIFT2_SET_CHARS[cValue as usize]; if upperShift { result.append_char( - char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::PARSE)?, ); upperShift = false; } else { @@ -537,7 +537,7 @@ fn decodeTextSegment( upperShift = true } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } shift = 0; @@ -547,7 +547,7 @@ fn decodeTextSegment( let textChar = TEXT_SHIFT3_SET_CHARS[cValue as usize]; if upperShift { result.append_char( - char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::PARSE)?, ); upperShift = false; } else { @@ -555,11 +555,11 @@ fn decodeTextSegment( } shift = 0; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } if bits.available() == 0 { @@ -622,12 +622,12 @@ fn decodeAnsiX12Segment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> _ => { if cValue < 14 { // 0 - 9 - result.append_char(char::from_u32(cValue + 44).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 44).ok_or(Exceptions::PARSE)?); } else if cValue < 40 { // A - Z - result.append_char(char::from_u32(cValue + 51).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(cValue + 51).ok_or(Exceptions::PARSE)?); } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } } @@ -679,7 +679,7 @@ fn decodeEdifactSegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> // no 1 in the leading (6th) bit edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value } - result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::PARSE)?); } if bits.available() == 0 { @@ -724,7 +724,7 @@ fn decodeBase256Segment( // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if bits.available() < 8 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; codewordPosition += 1; @@ -732,7 +732,7 @@ fn decodeBase256Segment( result.append_string( &encoding::all::ISO_8859_1 .decode(&bytes, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parseWith(e))?, + .map_err(|e| Exceptions::parse_with(e))?, ); byteSegments.push(bytes); diff --git a/src/datamatrix/decoder/version.rs b/src/datamatrix/decoder/version.rs index 72e983e..4879e21 100644 --- a/src/datamatrix/decoder/version.rs +++ b/src/datamatrix/decoder/version.rs @@ -103,7 +103,7 @@ impl Version { */ pub fn getVersionForDimensions(numRows: u32, numColumns: u32) -> Result<&'static Version> { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } for version in VERSIONS.iter() { @@ -112,7 +112,7 @@ impl Version { } } - Err(Exceptions::format) + Err(Exceptions::FORMAT) } /** diff --git a/src/datamatrix/detector/datamatrix_detector.rs b/src/datamatrix/detector/datamatrix_detector.rs index bf7dcd8..d6be4fa 100644 --- a/src/datamatrix/detector/datamatrix_detector.rs +++ b/src/datamatrix/detector/datamatrix_detector.rs @@ -55,7 +55,7 @@ impl<'a> Detector<'_> { if let Some(point) = self.correctTopRight(&points) { points[3] = point; } else { - return Err(Exceptions::notFoundWith("point 4 unfound")); + return Err(Exceptions::not_found_with("point 4 unfound")); } // points[3] = self.correctTopRight(&points); // if points[3] == null { diff --git a/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs b/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs index 885a98a..432161d 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs @@ -247,7 +247,7 @@ fn Scan( )); } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } pub fn detect( @@ -351,6 +351,6 @@ pub fn detect( } // #ifndef __cpp_impl_coroutine - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) // #endif } diff --git a/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs b/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs index 0f0c375..d6e8d9e 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs @@ -76,7 +76,7 @@ impl RegressionLine for DMRegressionLine { fn add(&mut self, p: Point) -> Result<()> { if self.direction_inward == Point::default() { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } self.points.push(p); if self.points.len() == 1 { @@ -237,7 +237,7 @@ impl DMRegressionLine { pub fn modules(&mut self, beg: Point, end: Point) -> Result { if self.points.len() <= 3 { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } // re-evaluate and filter out all points too far away. required for the gapSizes calculation. @@ -263,12 +263,12 @@ impl DMRegressionLine { self.points .last() .copied() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? - self .points .first() .copied() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, )) as f64; // calculate the width of 2 modules (first black pixel to first black pixel) @@ -295,7 +295,7 @@ impl DMRegressionLine { self.points .last() .copied() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ), ) as f64, ); diff --git a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs index f709e1a..a1c6743 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs @@ -203,7 +203,7 @@ impl<'a> EdgeTracer<'_> { if self.whiteAt(pEdge) { // if we are not making any progress, we still have another endless loop bug if self.p == pEdge.centered() { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } self.p = pEdge.centered(); @@ -274,7 +274,7 @@ impl<'a> EdgeTracer<'_> { .points() .first() .as_ref() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { return Ok(false); } @@ -304,9 +304,9 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::indexOutOfBounds)?) + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } if !line.points().is_empty() && &&self.p @@ -314,7 +314,7 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? { return Ok(false); } @@ -358,7 +358,7 @@ impl<'a> EdgeTracer<'_> { line.points() .last() .copied() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ), ) < 1.0 { @@ -376,7 +376,7 @@ impl<'a> EdgeTracer<'_> { .points() .last() .copied() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) }; line.add(self.p)?; @@ -393,7 +393,7 @@ impl<'a> EdgeTracer<'_> { .points() .first() .copied() - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { return Ok(false); } diff --git a/src/datamatrix/detector/zxing_cpp_detector/util.rs b/src/datamatrix/detector/zxing_cpp_detector/util.rs index 28380cb..c2c4180 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/util.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/util.rs @@ -24,7 +24,7 @@ pub fn float_max(a: T, b: T) -> T { #[inline(always)] pub fn intersect(l1: &DMRegressionLine, l2: &DMRegressionLine) -> Result { if !(l1.isValid() && l2.isValid()) { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } let d = l1.a * l2.b - l1.b * l2.a; let x = (l1.c * l2.b - l1.b * l2.c) / d; diff --git a/src/datamatrix/encoder/ascii_encoder.rs b/src/datamatrix/encoder/ascii_encoder.rs index df14f13..474d612 100644 --- a/src/datamatrix/encoder/ascii_encoder.rs +++ b/src/datamatrix/encoder/ascii_encoder.rs @@ -32,12 +32,12 @@ impl Encoder for ASCIIEncoder { .getMessage() .chars() .nth(context.pos as usize) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, context .getMessage() .chars() .nth(context.pos as usize + 1) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, )? as u8); context.pos += 2; } else { @@ -74,7 +74,7 @@ impl Encoder for ASCIIEncoder { } _ => { - return Err(Exceptions::illegalStateWith(format!( + return Err(Exceptions::illegal_state_with(format!( "Illegal mode: {newMode}" ))); } @@ -105,7 +105,7 @@ impl ASCIIEncoder { let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); Ok((num + 130) as char) } else { - Err(Exceptions::illegalArgumentWith(format!( + Err(Exceptions::illegal_argument_with(format!( "not digits: {digit1}{digit2}" ))) } diff --git a/src/datamatrix/encoder/base256_encoder.rs b/src/datamatrix/encoder/base256_encoder.rs index 326e9cd..3cf0560 100644 --- a/src/datamatrix/encoder/base256_encoder.rs +++ b/src/datamatrix/encoder/base256_encoder.rs @@ -54,7 +54,7 @@ impl Encoder for Base256Encoder { context.updateSymbolInfoWithLength(currentSize); let mustPad = (context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() - currentSize as u32) > 0; @@ -63,26 +63,26 @@ impl Encoder for Base256Encoder { buffer.replace_range( 0..1, &char::from_u32(dataCount as u32) - .ok_or(Exceptions::parse)? + .ok_or(Exceptions::PARSE)? .to_string(), ); } else if dataCount <= 1555 { buffer.replace_range( 0..1, &char::from_u32((dataCount as u32 / 250) + 249) - .ok_or(Exceptions::parse)? + .ok_or(Exceptions::PARSE)? .to_string(), ); let (ci_pos, _) = buffer .char_indices() .nth(1) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; buffer.insert( ci_pos, - char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::indexOutOfBounds)?, + char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ); } else { - return Err(Exceptions::illegalStateWith(format!( + return Err(Exceptions::illegal_state_with(format!( "Message length not in valid ranges: {dataCount}" ))); } @@ -92,10 +92,10 @@ impl Encoder for Base256Encoder { // for (int i = 0, c = buffer.length(); i < c; i++) { context.writeCodeword( Self::randomize255State( - buffer.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?, + buffer.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, context.getCodewordCount() as u32 + 1, ) - .ok_or(Exceptions::parse)? as u8, + .ok_or(Exceptions::PARSE)? as u8, ); } Ok(()) diff --git a/src/datamatrix/encoder/c40_encoder.rs b/src/datamatrix/encoder/c40_encoder.rs index 7ee5a97..55c5e78 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -66,7 +66,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() as usize - curCodewordCount; @@ -141,7 +141,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() as usize - curCodewordCount; let rest = buffer.chars().count() % 3; @@ -184,7 +184,7 @@ impl C40Encoder { buffer: &mut String, ) -> Result<()> { context.writeCodewords( - &Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?, + &Self::encodeToCodewords(buffer).ok_or(Exceptions::FORMAT)?, ); buffer.replace_range(0..3, ""); // buffer.delete(0, 3); @@ -205,7 +205,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() as usize - curCodewordCount; @@ -234,7 +234,7 @@ impl C40Encoder { context.writeCodeword(C40_UNLATCH); } } else { - return Err(Exceptions::illegalStateWith( + return Err(Exceptions::illegal_state_with( "Unexpected case. Please report!", )); } diff --git a/src/datamatrix/encoder/default_placement.rs b/src/datamatrix/encoder/default_placement.rs index fbdaacb..c49c208 100644 --- a/src/datamatrix/encoder/default_placement.rs +++ b/src/datamatrix/encoder/default_placement.rs @@ -165,7 +165,7 @@ impl DefaultPlacement { .codewords .chars() .nth(pos) - .ok_or(Exceptions::indexOutOfBounds)? as u32; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32; v &= 1 << (8 - bit); self.setBit(col as usize, row as usize, v != 0); diff --git a/src/datamatrix/encoder/edifact_encoder.rs b/src/datamatrix/encoder/edifact_encoder.rs index 603c6c8..d7bd8f4 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -77,7 +77,7 @@ impl EdifactEncoder { context.updateSymbolInfo(); let mut available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() - context.getCodewordCount() as u32; let remaining = context.getRemainingCharacters(); @@ -86,7 +86,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + 1); available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() - context.getCodewordCount() as u32; } @@ -96,7 +96,7 @@ impl EdifactEncoder { } if count > 4 { - return Err(Exceptions::illegalStateWith("Count must not exceed 4")); + return Err(Exceptions::illegal_state_with("Count must not exceed 4")); } let restChars = count - 1; let encoded = Self::encodeToCodewords(buffer)?; @@ -107,7 +107,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + restChars); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() - context.getCodewordCount() as u32; if available >= 3 { @@ -148,23 +148,23 @@ impl EdifactEncoder { fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { - return Err(Exceptions::illegalStateWith( + return Err(Exceptions::illegal_state_with( "StringBuilder must not be empty", )); } - let c1 = sb.chars().next().ok_or(Exceptions::indexOutOfBounds)?; + let c1 = sb.chars().next().ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let c2 = if len >= 2 { - sb.chars().nth(1).ok_or(Exceptions::indexOutOfBounds)? + sb.chars().nth(1).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? } else { 0 as char }; let c3 = if len >= 3 { - sb.chars().nth(2).ok_or(Exceptions::indexOutOfBounds)? + sb.chars().nth(2).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? } else { 0 as char }; let c4 = if len >= 4 { - sb.chars().nth(3).ok_or(Exceptions::indexOutOfBounds)? + sb.chars().nth(3).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? } else { 0 as char }; @@ -174,12 +174,12 @@ impl EdifactEncoder { let cw2 = (v >> 8) & 255; let cw3 = v & 255; let mut res = String::with_capacity(3); - res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBounds)?); + res.push(char::from_u32(cw1).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?); if len >= 2 { - res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBounds)?); + res.push(char::from_u32(cw2).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?); } if len >= 3 { - res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBounds)?); + res.push(char::from_u32(cw3).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?); } Ok(res) diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index bb49293..51fd9a3 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -64,10 +64,10 @@ impl<'a> EncoderContext<'_> { ISO_8859_1_ENCODER .decode(&encoded_bytes, encoding::DecoderTrap::Strict) .map_err(|e| { - Exceptions::parseWith(format!("round trip decode should always work: {e}")) + Exceptions::parse_with(format!("round trip decode should always work: {e}")) })? } else { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Message contains characters outside ISO-8859-1 encoding.", )); }; diff --git a/src/datamatrix/encoder/error_correction.rs b/src/datamatrix/encoder/error_correction.rs index 10d18ea..7ee3b69 100644 --- a/src/datamatrix/encoder/error_correction.rs +++ b/src/datamatrix/encoder/error_correction.rs @@ -155,7 +155,7 @@ const ALOG: [u32; 255] = { */ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "The number of codewords does not match the selected symbol", )); } @@ -186,7 +186,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result codewords .chars() .nth(d) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ); d += blockCount; @@ -199,12 +199,12 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result let (char_index, replace_char) = sb .char_indices() .nth(symbolInfo.getDataCapacity() as usize + e) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; sb.replace_range( char_index..(replace_char.len_utf8()), &ecc.chars() .nth(pos) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_string(), ); // sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos)); @@ -229,7 +229,7 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result { } } if table < 0 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Illegal number of error correction codewords specified: {numECWords}" ))); } @@ -245,21 +245,21 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result { ^ codewords .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? as usize; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize; for k in (1..numECWords).rev() { // for (int k = numECWords - 1; k > 0; k--) { if m != 0 && poly[k] != 0 { ecc[k] = char::from_u32( ecc[k - 1] as u32 ^ ALOG[(LOG[m] + LOG[poly[k] as usize]) as usize % 255], ) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else { ecc[k] = ecc[k - 1]; } } if m != 0 && poly[0] != 0 { ecc[0] = char::from_u32(ALOG[(LOG[m] + LOG[poly[0] as usize]) as usize % 255]) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else { ecc[0] = 0 as char; } diff --git a/src/datamatrix/encoder/high_level_encoder.rs b/src/datamatrix/encoder/high_level_encoder.rs index a25ac82..ace5b68 100644 --- a/src/datamatrix/encoder/high_level_encoder.rs +++ b/src/datamatrix/encoder/high_level_encoder.rs @@ -222,14 +222,14 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( if forceC40 { c40Encoder.encodeMaximalC40(&mut context)?; - encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?; + encodingMode = context.getNewEncoding().ok_or(Exceptions::ILLEGAL_STATE)?; context.resetEncoderSignal(); } while context.hasMoreCharacters() { encoders[encodingMode].encode(&mut context)?; if context.getNewEncoding().is_some() { - encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?; + encodingMode = context.getNewEncoding().ok_or(Exceptions::ILLEGAL_STATE)?; context.resetEncoderSignal(); } } @@ -237,7 +237,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( context.updateSymbolInfo(); let capacity = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity(); if len < capacity as usize && encodingMode != ASCII_ENCODATION @@ -608,7 +608,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 { pub fn illegalCharacter(c: char) -> Result<()> { // let hex = Integer.toHexString(c); // hex = "0000".substring(0, 4 - hex.length()) + hex; - Err(Exceptions::illegalArgumentWith(format!( + Err(Exceptions::illegal_argument_with(format!( "Illegal character: {c} (0x{c})" ))) } diff --git a/src/datamatrix/encoder/minimal_encoder.rs b/src/datamatrix/encoder/minimal_encoder.rs index 248a670..d248f02 100755 --- a/src/datamatrix/encoder/minimal_encoder.rs +++ b/src/datamatrix/encoder/minimal_encoder.rs @@ -218,7 +218,7 @@ fn addEdge(edges: &mut [Vec>>], edge: Rc) -> Result<()> { if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() || edges[vertexIndex][edge.getEndMode()?.ordinal()] .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .cachedTotalSize > edge.cachedTotalSize { @@ -635,7 +635,7 @@ fn encodeMinimally(input: Rc) -> Result { } if minimalJ < 0 { - return Err(Exceptions::illegalStateWith(format!( + return Err(Exceptions::illegal_state_with(format!( "Internal error: failed to encode \"{input}\"" ))); } @@ -669,7 +669,7 @@ impl Edge { previous: Option>, ) -> Result { if fromPosition + characterLength > input.length() as u32 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let mut size = if let Some(previous) = previous.clone() { @@ -1276,7 +1276,7 @@ impl RXingResult { let solution = if let Some(edge) = solution { edge } else { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); }; let input = solution.input.clone(); let mut size = 0; diff --git a/src/datamatrix/encoder/symbol_info.rs b/src/datamatrix/encoder/symbol_info.rs index 1975385..eb129fc 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -129,7 +129,7 @@ impl SymbolInfo { 2 | 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::illegalStateWith( + _ => Err(Exceptions::illegal_state_with( "Cannot handle this number of data regions", )), } @@ -141,7 +141,7 @@ impl SymbolInfo { 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::illegalStateWith( + _ => Err(Exceptions::illegal_state_with( "Cannot handle this number of data regions", )), } @@ -311,7 +311,7 @@ impl<'a> SymbolInfoLookup<'a> { } } if fail { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Can't find a symbol arrangement that matches the message. Data codewords: {dataCodewords}" ))); } diff --git a/src/datamatrix/encoder/x12_encoder.rs b/src/datamatrix/encoder/x12_encoder.rs index 174c81a..1c12a31 100644 --- a/src/datamatrix/encoder/x12_encoder.rs +++ b/src/datamatrix/encoder/x12_encoder.rs @@ -82,7 +82,7 @@ impl X12Encoder { context.updateSymbolInfo(); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getDataCapacity() - context.getCodewordCount() as u32; let count = buffer.chars().count(); diff --git a/src/exceptions.rs b/src/exceptions.rs index e33197a..8a908ec 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -1,144 +1,104 @@ -use std::{error::Error, fmt}; - #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; +use thiserror::Error; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, PartialEq, Eq)] +#[derive(Error, Debug, PartialEq, Eq)] pub enum Exceptions { - IllegalArgumentException(Option), - UnsupportedOperationException(Option), - IllegalStateException(Option), - ArithmeticException(Option), - NotFoundException(Option), - FormatException(Option), - ChecksumException(Option), - ReaderException(Option), - WriterException(Option), - ReedSolomonException(Option), - IndexOutOfBoundsException(Option), - RuntimeException(Option), - ParseException(Option), + #[error("IllegalArgumentException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + IllegalArgumentException(String), + #[error("UnsupportedOperationException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + UnsupportedOperationException(String), + #[error("IllegalStateException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + IllegalStateException(String), + #[error("ArithmeticException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + ArithmeticException(String), + #[error("NotFoundException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + NotFoundException(String), + #[error("FormatException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + FormatException(String), + #[error("ChecksumException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + ChecksumException(String), + #[error("ReaderException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + ReaderException(String), + #[error("WriterException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + WriterException(String), + #[error("ReedSolomonException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + ReedSolomonException(String), + #[error("IndexOutOfBoundsException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + IndexOutOfBoundsException(String), + #[error("RuntimeException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + RuntimeException(String), + #[error("ParseException{}", if .0.is_empty() { String::new() } else { format!(" - {}", .0) })] + ParseException(String), + #[error("ReaderDecodeException")] ReaderDecodeException(), } #[allow(non_upper_case_globals)] impl Exceptions { - pub const illegalArgument: Self = Self::IllegalArgumentException(None); - pub fn illegalArgumentWith>(x: I) -> Self { - Self::IllegalArgumentException(Some(x.into())) + pub const ILLEGAL_ARGUMENT: Self = Self::IllegalArgumentException(String::new()); + pub fn illegal_argument_with>(x: I) -> Self { + Self::IllegalArgumentException(x.into()) } - pub const unsupportedOperation: Self = Self::UnsupportedOperationException(None); - pub fn unsupportedOperationWith>(x: I) -> Self { - Self::UnsupportedOperationException(Some(x.into())) + pub const UNSUPPORTED_OPERATION: Self = Self::UnsupportedOperationException(String::new()); + pub fn unsupported_operation_with>(x: I) -> Self { + Self::UnsupportedOperationException(x.into()) } - pub const illegalState: Self = Self::IllegalStateException(None); - pub fn illegalStateWith>(x: I) -> Self { - Self::IllegalStateException(Some(x.into())) + pub const ILLEGAL_STATE: Self = Self::IllegalStateException(String::new()); + pub fn illegal_state_with>(x: I) -> Self { + Self::IllegalStateException(x.into()) } - pub const arithmetic: Self = Self::ArithmeticException(None); - pub fn arithmeticWith>(x: I) -> Self { - Self::ArithmeticException(Some(x.into())) + pub const ARITHMETIC: Self = Self::ArithmeticException(String::new()); + pub fn arithmetic_with>(x: I) -> Self { + Self::ArithmeticException(x.into()) } - pub const notFound: Self = Self::NotFoundException(None); - pub fn notFoundWith>(x: I) -> Self { - Self::NotFoundException(Some(x.into())) + pub const NOT_FOUND: Self = Self::NotFoundException(String::new()); + pub fn not_found_with>(x: I) -> Self { + Self::NotFoundException(x.into()) } - pub const format: Self = Self::FormatException(None); - pub fn formatWith>(x: I) -> Self { - Self::FormatException(Some(x.into())) + pub const FORMAT: Self = Self::FormatException(String::new()); + pub fn format_with>(x: I) -> Self { + Self::FormatException(x.into()) } - pub const checksum: Self = Self::ChecksumException(None); - pub fn checksumWith>(x: I) -> Self { - Self::ChecksumException(Some(x.into())) + pub const CHECKSUM: Self = Self::ChecksumException(String::new()); + pub fn checksum_with>(x: I) -> Self { + Self::ChecksumException(x.into()) } - pub const reader: Self = Self::ReaderException(None); - pub fn readerWith>(x: I) -> Self { - Self::ReaderException(Some(x.into())) + pub const READER: Self = Self::ReaderException(String::new()); + pub fn reader_with>(x: I) -> Self { + Self::ReaderException(x.into()) } - pub const writer: Self = Self::WriterException(None); - pub fn writerWith>(x: I) -> Self { - Self::WriterException(Some(x.into())) + pub const WRITER: Self = Self::WriterException(String::new()); + pub fn writer_with>(x: I) -> Self { + Self::WriterException(x.into()) } - pub const reedSolomon: Self = Self::ReedSolomonException(None); - pub fn reedSolomonWith>(x: I) -> Self { - Self::ReedSolomonException(Some(x.into())) + pub const REED_SOLOMON: Self = Self::ReedSolomonException(String::new()); + pub fn reed_solomon_with>(x: I) -> Self { + Self::ReedSolomonException(x.into()) } - pub const indexOutOfBounds: Self = Self::IndexOutOfBoundsException(None); - pub fn indexOutOfBoundsWith>(x: I) -> Self { - Self::IndexOutOfBoundsException(Some(x.into())) + pub const INDEX_OUT_OF_BOUNDS: Self = Self::IndexOutOfBoundsException(String::new()); + pub fn index_out_of_bounds_with>(x: I) -> Self { + Self::IndexOutOfBoundsException(x.into()) } - pub const runtime: Self = Self::RuntimeException(None); - pub fn runtimeWith>(x: I) -> Self { - Self::RuntimeException(Some(x.into())) + pub const RUNTIME: Self = Self::RuntimeException(String::new()); + pub fn runtime_with>(x: I) -> Self { + Self::RuntimeException(x.into()) } - pub const parse: Self = Self::ParseException(None); - pub fn parseWith>(x: I) -> Self { - Self::ParseException(Some(x.into())) + pub const PARSE: Self = Self::ParseException(String::new()); + pub fn parse_with>(x: I) -> Self { + Self::ParseException(x.into()) } } - -impl fmt::Display for Exceptions { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Exceptions::IllegalArgumentException(Some(a)) => { - write!(f, "IllegalArgumentException - {a}") - } - - Exceptions::UnsupportedOperationException(Some(a)) => { - write!(f, "UnsupportedOperationException - {a}") - } - - Exceptions::IllegalStateException(Some(a)) => { - write!(f, "IllegalStateException - {a}") - } - Exceptions::ArithmeticException(Some(a)) => write!(f, "ArithmeticException - {a}"), - Exceptions::NotFoundException(Some(a)) => write!(f, "NotFoundException - {a}"), - Exceptions::FormatException(Some(a)) => write!(f, "FormatException - {a}"), - Exceptions::ChecksumException(Some(a)) => write!(f, "ChecksumException - {a}"), - Exceptions::ReaderException(Some(a)) => write!(f, "ReaderException - {a}"), - Exceptions::WriterException(Some(a)) => write!(f, "WriterException - {a}"), - Exceptions::ReedSolomonException(Some(a)) => write!(f, "ReedSolomonException - {a}"), - Exceptions::IndexOutOfBoundsException(Some(a)) => { - write!(f, "IndexOutOfBoundsException - {a}") - } - - Exceptions::RuntimeException(Some(a)) => write!(f, "RuntimeException - {a}"), - Exceptions::ParseException(Some(a)) => write!(f, "ParseException - {a}"), - - Exceptions::IllegalArgumentException(None) => write!(f, "IllegalArgumentException"), - - Exceptions::UnsupportedOperationException(None) => { - write!(f, "UnsupportedOperationException") - } - Exceptions::IllegalStateException(None) => write!(f, "IllegalStateException"), - Exceptions::ArithmeticException(None) => write!(f, "ArithmeticException"), - Exceptions::NotFoundException(None) => write!(f, "NotFoundException"), - Exceptions::FormatException(None) => write!(f, "FormatException"), - Exceptions::ChecksumException(None) => write!(f, "ChecksumException"), - Exceptions::ReaderException(None) => write!(f, "ReaderException"), - Exceptions::WriterException(None) => write!(f, "WriterException"), - Exceptions::ReedSolomonException(None) => write!(f, "ReedSolomonException"), - Exceptions::IndexOutOfBoundsException(None) => write!(f, "IndexOutOfBoundsException"), - - Exceptions::RuntimeException(None) => write!(f, "RuntimeException"), - Exceptions::ParseException(None) => write!(f, "ParseException"), - - Exceptions::ReaderDecodeException() => write!(f, "ReaderDecodeException"), - } - } -} - -impl Error for Exceptions {} diff --git a/src/helpers.rs b/src/helpers.rs index 8cc2ab7..5e6cc50 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -32,16 +32,16 @@ pub fn detect_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgumentWith("file does not exist")); + return Err(Exceptions::illegal_argument_with("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgumentWith("file cannot be opened")); + return Err(Exceptions::illegal_argument_with("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgumentWith("file cannot be read")); + return Err(Exceptions::illegal_argument_with("file cannot be read")); } let mut multi_format_reader = MultiFormatReader::default(); @@ -81,16 +81,16 @@ pub fn detect_multiple_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgumentWith("file does not exist")); + return Err(Exceptions::illegal_argument_with("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgumentWith("file cannot be opened")); + return Err(Exceptions::illegal_argument_with("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgumentWith("file cannot be read")); + return Err(Exceptions::illegal_argument_with("file cannot be read")); } let multi_format_reader = MultiFormatReader::default(); @@ -120,7 +120,7 @@ pub fn detect_in_file_with_hints( hints: &mut DecodingHintDictionary, ) -> Result { let Ok(img) = image::open(file_name) else { - return Err(Exceptions::illegalArgumentWith(format!("file '{file_name}' not found or cannot be opened"))); + return Err(Exceptions::illegal_argument_with(format!("file '{file_name}' not found or cannot be opened"))); }; let mut multi_format_reader = MultiFormatReader::default(); @@ -154,7 +154,7 @@ pub fn detect_multiple_in_file_with_hints( hints: &mut DecodingHintDictionary, ) -> Result> { let img = image::open(file_name).map_err(|e| { - Exceptions::RuntimeException(Some(format!("couldn't read {file_name}: {e}"))) + Exceptions::runtime_with(format!("couldn't read {file_name}: {e}")) })?; let multi_format_reader = MultiFormatReader::default(); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); @@ -238,7 +238,7 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { let image: image::DynamicImage = bit_matrix.into(); match image.save(file_name) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::illegalArgumentWith(format!( + Err(err) => Err(Exceptions::illegal_argument_with(format!( "could not save file '{file_name}': {err}" ))), } @@ -250,7 +250,7 @@ pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { match svg::save(file_name, &svg) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::illegalArgumentWith(format!( + Err(err) => Err(Exceptions::illegal_argument_with(format!( "could not save file '{}': {}", file_name, err ))), @@ -285,7 +285,7 @@ pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { Ok(()) }() { Ok(_) => Ok(()), - Err(_) => Err(Exceptions::illegalArgumentWith(format!( + Err(_) => Err(Exceptions::illegal_argument_with(format!( "could not write to '{file_name}'" ))), } diff --git a/src/luma_luma_source.rs b/src/luma_luma_source.rs index d326734..1d25521 100644 --- a/src/luma_luma_source.rs +++ b/src/luma_luma_source.rs @@ -96,9 +96,9 @@ impl LuminanceSource for Luma8LuminanceSource { } fn rotateCounterClockwise45(&self) -> Result> { - Err(crate::Exceptions::UnsupportedOperationException(Some( - "This luminance source does not support rotation by 45 degrees.".to_owned(), - ))) + Err(crate::Exceptions::unsupported_operation_with( + "This luminance source does not support rotation by 45 degrees.", + )) } } diff --git a/src/luminance_source.rs b/src/luminance_source.rs index 581c86a..022c4ed 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -92,9 +92,9 @@ pub trait LuminanceSource { _width: usize, _height: usize, ) -> Result> { - Err(Exceptions::UnsupportedOperationException(Some( - "This luminance source does not support cropping.".to_owned(), - ))) + Err(Exceptions::unsupported_operation_with( + "This luminance source does not support cropping.", + )) } /** @@ -119,9 +119,9 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise(&self) -> Result> { - Err(Exceptions::UnsupportedOperationException(Some( - "This luminance source does not support rotation by 90 degrees.".to_owned(), - ))) + Err(Exceptions::unsupported_operation_with( + "This luminance source does not support rotation by 90 degrees.", + )) } /** @@ -131,9 +131,9 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise45(&self) -> Result> { - Err(Exceptions::UnsupportedOperationException(Some( - "This luminance source does not support rotation by 45 degrees.".to_owned(), - ))) + Err(Exceptions::unsupported_operation_with( + "This luminance source does not support rotation by 45 degrees.", + )) } #[inline(always)] diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index 14c1d18..e88584f 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -89,7 +89,7 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result { let pc = getPostCode2(bytes); let ps2Length = getPostCode2Length(bytes) as usize; if ps2Length > 10 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } // NumberFormat df = new DecimalFormat("0000000000".substring(0, ps2Length)); // postcode = df.format(pc); diff --git a/src/maxicode/decoder/maxicode_decoder.rs b/src/maxicode/decoder/maxicode_decoder.rs index 95bbf41..231bbed 100644 --- a/src/maxicode/decoder/maxicode_decoder.rs +++ b/src/maxicode/decoder/maxicode_decoder.rs @@ -70,7 +70,7 @@ pub fn decode_with_hints( correctErrors(&mut codewords, 20, 68, 56, ODD)?; datawords = vec![0u8; 78]; } - _ => return Err(Exceptions::notFound), + _ => return Err(Exceptions::NOT_FOUND), } datawords[0..10].clone_from_slice(&codewords[0..10]); diff --git a/src/maxicode/detector.rs b/src/maxicode/detector.rs index d0bfc0d..2b777b7 100644 --- a/src/maxicode/detector.rs +++ b/src/maxicode/detector.rs @@ -316,7 +316,7 @@ impl Circle<'_> { pub fn detect(image: &BitMatrix, try_harder: bool) -> Result { // find concentric circles let Some( mut circles) = find_concentric_circles(image) else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; // we should have an idea where the center is at this point, @@ -339,7 +339,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result Result Result Result<([(f32, f32); 4] #[cfg(feature = "experimental_features")] if is_ellipse { // we don't deal with ellipses yet - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut final_rotation = 0.0; @@ -1049,7 +1049,7 @@ fn compare_circle(a: &Circle, b: &Circle) -> std::cmp::Ordering { pub fn read_bits(image: &BitMatrix) -> Result { let enclosingRectangle = image .getEnclosingRectangle() - .ok_or(Exceptions::NotFoundException(None))?; + .ok_or(Exceptions::NOT_FOUND)?; let left = enclosingRectangle[0]; let top = enclosingRectangle[1]; diff --git a/src/maxicode/maxi_code_reader.rs b/src/maxicode/maxi_code_reader.rs index d024110..7b331ba 100644 --- a/src/maxicode/maxi_code_reader.rs +++ b/src/maxicode/maxi_code_reader.rs @@ -123,10 +123,10 @@ impl MaxiCodeReader { fn extractPureBits(image: &BitMatrix) -> Result { let enclosingRectangleOption = image.getEnclosingRectangle(); if enclosingRectangleOption.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } - let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFound)?; + let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::NOT_FOUND)?; let left = enclosingRectangle[0]; let top = enclosingRectangle[1]; diff --git a/src/multi/generic_multiple_barcode_reader.rs b/src/multi/generic_multiple_barcode_reader.rs index a9b2910..ddd6b81 100644 --- a/src/multi/generic_multiple_barcode_reader.rs +++ b/src/multi/generic_multiple_barcode_reader.rs @@ -56,7 +56,7 @@ impl MultipleBarcodeReader for GenericMultipleBarcodeReader { let mut results = Vec::new(); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); if results.is_empty() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(results) } diff --git a/src/multi/qrcode/detector/multi_detector.rs b/src/multi/qrcode/detector/multi_detector.rs index 26eb4f5..4f19cd4 100644 --- a/src/multi/qrcode/detector/multi_detector.rs +++ b/src/multi/qrcode/detector/multi_detector.rs @@ -50,7 +50,7 @@ impl<'a> MultiDetector<'_> { let infos = finder.findMulti(hints)?; if infos.is_empty() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut result = Vec::new(); diff --git a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs index 8065bac..0efe06e 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -92,7 +92,7 @@ impl<'a> MultiFinderPatternFinder<'_> { if size < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::notFoundWith( + return Err(Exceptions::not_found_with( "Couldn't find enough finder patterns", )); } @@ -212,7 +212,7 @@ impl<'a> MultiFinderPatternFinder<'_> { if !results.is_empty() { Ok(results) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/multi/qrcode/qr_code_multi_reader.rs b/src/multi/qrcode/qr_code_multi_reader.rs index 4b8b259..3500138 100644 --- a/src/multi/qrcode/qr_code_multi_reader.rs +++ b/src/multi/qrcode/qr_code_multi_reader.rs @@ -111,7 +111,7 @@ impl MultipleBarcodeReader for QRCodeMultiReader { // ignore and continue continue; } else { - return Err(output.err().unwrap_or(Exceptions::notFound)); + return Err(output.err().unwrap_or(Exceptions::NOT_FOUND)); } } diff --git a/src/multi_format_reader.rs b/src/multi_format_reader.rs index 23cd8d9..14b7951 100644 --- a/src/multi_format_reader.rs +++ b/src/multi_format_reader.rs @@ -187,6 +187,6 @@ impl MultiFormatReader { } } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/multi_format_writer.rs b/src/multi_format_writer.rs index fecf30e..d0f164a 100644 --- a/src/multi_format_writer.rs +++ b/src/multi_format_writer.rs @@ -72,7 +72,7 @@ impl Writer for MultiFormatWriter { BarcodeFormat::DATA_MATRIX => Box::::default(), BarcodeFormat::AZTEC => Box::::default(), _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "No encoder available for format {format:?}" ))) } diff --git a/src/oned/coda_bar_reader.rs b/src/oned/coda_bar_reader.rs index c16a0d1..1bcd852 100644 --- a/src/oned/coda_bar_reader.rs +++ b/src/oned/coda_bar_reader.rs @@ -65,13 +65,13 @@ impl OneDReader for CodaBarReader { loop { let charOffset = self.toNarrowWidePattern(nextStart); if charOffset == -1 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Hack: We store the position in the alphabet table into a // StringBuilder, so that we can access the decoded patterns in // validatePattern. We'll translate to the actual characters later. self.decodeRowRXingResult - .push(char::from_u32(charOffset as u32).ok_or(Exceptions::parse)?); + .push(char::from_u32(charOffset as u32).ok_or(Exceptions::PARSE)?); nextStart += 8; // Stop as soon as we see the end character. if self.decodeRowRXingResult.chars().count() > 1 @@ -99,7 +99,7 @@ impl OneDReader for CodaBarReader { // otherwise this is probably a false positive. The exception is if we are // at the end of the row. (I.e. the barcode barely fits.) if nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } self.validatePattern(startOffset)?; @@ -113,7 +113,7 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? as usize] + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize] .to_string(), ); } @@ -122,23 +122,23 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .next() - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let endchar = self .decodeRowRXingResult .chars() .nth(self.decodeRowRXingResult.chars().count() - 1) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // remove stop/start characters character and check if a long enough string is contained if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize { // Almost surely a false positive ( start + stop + at least 1 character) - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if !matches!( @@ -242,7 +242,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize]; for j in (0_usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -281,7 +281,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize]; for j in (0usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -289,7 +289,7 @@ impl CodaBarReader { let category = (j & 1) + ((pattern as usize) & 1) * 2; let size = self.counters[(pos + j)]; if (size as f32) < mins[category] || (size as f32) > maxes[category] { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } pattern >>= 1; } @@ -310,7 +310,7 @@ impl CodaBarReader { let mut i = row.getNextUnset(0); let end = row.getSize(); if i >= end { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut isWhite = true; let mut count = 0; @@ -362,7 +362,7 @@ impl CodaBarReader { i += 2; } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } pub fn arrayContains(array: &[char], key: char) -> bool { diff --git a/src/oned/coda_bar_writer.rs b/src/oned/coda_bar_writer.rs index a57a4a9..5e08701 100644 --- a/src/oned/coda_bar_writer.rs +++ b/src/oned/coda_bar_writer.rs @@ -44,12 +44,12 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let firstChar = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_ascii_uppercase(); let lastChar = contents .chars() .nth(contents.chars().count() - 1) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_ascii_uppercase(); let startsNormal = CodaBarReader::arrayContains(&START_END_CHARS, firstChar); let endsNormal = CodaBarReader::arrayContains(&START_END_CHARS, lastChar); @@ -57,7 +57,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar); if startsNormal { if !endsNormal { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Invalid start/end guards: {contents}" ))); } @@ -65,7 +65,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { contents.to_owned() } else if startsAlt { if !endsAlt { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Invalid start/end guards: {contents}" ))); } @@ -74,7 +74,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { } else { // Doesn't start with a guard if endsNormal || endsAlt { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Invalid start/end guards: {contents}" ))); } @@ -94,7 +94,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { ) { resultLength += 10; } else { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Cannot encode : '{ch}'" ))); } @@ -109,7 +109,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let mut c = contents .chars() .nth(index) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_ascii_uppercase(); if index == 0 || index == contents.chars().count() - 1 { // The start/end chars are not in the CodaBarReader.ALPHABET. diff --git a/src/oned/code_128_reader.rs b/src/oned/code_128_reader.rs index ed6d8b8..bbf46e2 100644 --- a/src/oned/code_128_reader.rs +++ b/src/oned/code_128_reader.rs @@ -53,7 +53,7 @@ impl OneDReader for Code128Reader { CODE_START_A => CODE_CODE_A, CODE_START_B => CODE_CODE_B, CODE_START_C => CODE_CODE_C, - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), }; let mut done = false; @@ -103,7 +103,7 @@ impl OneDReader for Code128Reader { // Take care of illegal start codes match code { - CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::format), + CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::FORMAT), _ => {} } @@ -297,21 +297,21 @@ impl OneDReader for Code128Reader { row.getSize().min(nextStart + (nextStart - lastStart) / 2), false, )? { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier as usize * lastCode as usize; // lastCode is the checksum then: if (checksumTotal % 103) as u8 != lastCode { - return Err(Exceptions::checksum); + return Err(Exceptions::CHECKSUM); } // Need to pull out the check digits from string let resultLength = result.chars().count(); if resultLength == 0 { // false positive - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Only bother if the result had at least one character, and if the checksum digit happened to @@ -332,7 +332,7 @@ impl OneDReader for Code128Reader { let rawCodesSize = rawCodes.len(); let mut rawBytes = vec![0u8; rawCodesSize]; for (i, rawByte) in rawBytes.iter_mut().enumerate().take(rawCodesSize) { - *rawByte = *rawCodes.get(i).ok_or(Exceptions::indexOutOfBounds)?; + *rawByte = *rawCodes.get(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } let mut resultObject = RXingResult::new( &result, @@ -406,7 +406,7 @@ impl Code128Reader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn decodeCode(&self, row: &BitArray, counters: &mut [u32; 6], rowOffset: usize) -> Result { @@ -426,7 +426,7 @@ impl Code128Reader { if bestMatch >= 0 { Ok(bestMatch as u8) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } } diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index d6ff6d8..ce6ae5e 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -100,7 +100,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { let length = contents.chars().count(); // Check length if !(1..=80).contains(&length) { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Contents length should be between 1 and 80 characters, but got {length}" ))); } @@ -108,13 +108,13 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { // Check for forced code set hint. let mut forcedCodeSet = -1_i32; if hints.contains_key(&EncodeHintType::FORCE_CODE_SET) { - let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) = hints.get(&EncodeHintType::FORCE_CODE_SET) else { return Err(Exceptions::illegalState) }; + let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) = hints.get(&EncodeHintType::FORCE_CODE_SET) else { return Err(Exceptions::ILLEGAL_STATE) }; match codeSetHint.as_str() { "A" => forcedCodeSet = CODE_CODE_A as i32, "B" => forcedCodeSet = CODE_CODE_B as i32, "C" => forcedCodeSet = CODE_CODE_C as i32, _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Unsupported code set hint: {codeSetHint}" ))) } @@ -135,7 +135,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { if c > 127 { // no full Latin-1 character set available at the moment // shift and manual code change are not supported - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Bad character in input: ASCII value={c}" ))); } @@ -150,7 +150,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { // allows no ascii above 95 (no lower caps, no special symbols) { if c > 95 && c <= 127 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Bad character in input for forced code set A: ASCII value={c}" ))); } @@ -159,7 +159,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { // allows no ascii below 32 (terminal symbols) { if c <= 32 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Bad character in input for forced code set B: ASCII value={c}" ))); } @@ -173,7 +173,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { || ch == ESCAPE_FNC_3 || ch == ESCAPE_FNC_4 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Bad character in input for forced code set C: ASCII value={c}" ))); } @@ -196,7 +196,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { while position < length { //Select code to use let newCodeSet = if forcedCodeSet == -1 { - chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalState)? + chooseCode(contents, position, codeSet).ok_or(Exceptions::ILLEGAL_STATE)? } else { forcedCodeSet as usize // THIS IS RISKY }; @@ -209,7 +209,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { match contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? { ESCAPE_FNC_1 => patternIndex = CODE_FNC_1 as isize, ESCAPE_FNC_2 => patternIndex = CODE_FNC_2 as isize, @@ -229,7 +229,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as isize - ' ' as isize; if patternIndex < 0 { @@ -241,7 +241,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as isize - ' ' as isize } @@ -249,7 +249,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { // CODE_CODE_C if position + 1 == length { // this is the last character, but the encoding is C, which always encodes two characers - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Bad number of characters for digit only encoding.", )); } @@ -260,7 +260,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { .map(|(_u, c)| c) .collect(); patternIndex = s.parse::().map_err(|e| { - Exceptions::parseWith(format!("issue parsing {s}: {e}")) + Exceptions::parse_with(format!("issue parsing {s}: {e}")) })?; position += 1; } // Also incremented below @@ -536,7 +536,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; if contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == ESCAPE_FNC_1 { addPattern( @@ -556,7 +556,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; addPattern( &mut patterns, s.parse::().map_err(|e| { - Exceptions::parseWith(format!("unable to parse {s} {e}")) + Exceptions::parse_with(format!("unable to parse {s} {e}")) })?, &mut checkSum, &mut checkWeight, @@ -572,7 +572,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; let mut patternIndex = match contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? { ESCAPE_FNC_1 => CODE_FNC_1 as isize, ESCAPE_FNC_2 => CODE_FNC_2 as isize, @@ -590,7 +590,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? as isize + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as isize - ' ' as isize } }; @@ -681,7 +681,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; minPath: &mut Vec>, ) -> Result { if position >= contents.chars().count() { - return Err(Exceptions::illegalState); + return Err(Exceptions::ILLEGAL_STATE); } let mCost = memoizedCost[charset.ordinal()][position]; if mCost > 0 { @@ -762,7 +762,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } } if minCost == u32::MAX { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Bad character in input: ASCII value={}", contents.chars().nth(position).unwrap_or('x') ))); diff --git a/src/oned/code_39_reader.rs b/src/oned/code_39_reader.rs index 92ec57b..1096704 100644 --- a/src/oned/code_39_reader.rs +++ b/src/oned/code_39_reader.rs @@ -60,7 +60,7 @@ impl OneDReader for Code39Reader { one_d_reader::recordPattern(row, nextStart, &mut counters)?; let pattern = Self::toNarrowWidePattern(&counters); if pattern < 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -85,7 +85,7 @@ impl OneDReader for Code39Reader { // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if nextStart != end && (whiteSpaceAfterEnd * 2) < lastPatternSize as usize { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if self.usingCheckDigit { @@ -96,7 +96,7 @@ impl OneDReader for Code39Reader { self.decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { total += pos; } @@ -105,20 +105,20 @@ impl OneDReader for Code39Reader { .decodeRowRXingResult .chars() .nth(max) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? != Self::ALPHABET_STRING .chars() .nth(total % 43) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } self.decodeRowRXingResult.truncate(max); } if self.decodeRowRXingResult.chars().count() == 0 { // false positive - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let resultString = if self.extendedMode { @@ -246,7 +246,7 @@ impl Code39Reader { isWhite = !isWhite; } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions @@ -306,13 +306,13 @@ impl Code39Reader { return Self::ALPHABET_STRING .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds); + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS); } } if pattern == Self::ASTERISK_ENCODING { return Ok('*'); } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn decodeExtended(encoded: &str) -> Result { @@ -322,46 +322,46 @@ impl Code39Reader { while i < length { // for i in 0..length { // for (int i = 0; i < length; i++) { - let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; + let c = encoded.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; if c == '+' || c == '$' || c == '%' || c == '/' { let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let mut decodedChar = '\0'; match c { '+' => { // +A to +Z map to a to z if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 + 32) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } '$' => { // $A to $Z map to control codes SH to SB if ('A'..='Z').contains(&next) { decodedChar = char::from_u32(next as u32 - 64) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } '%' => { // %A to %E map to control codes ESC to US if ('A'..='E').contains(&next) { decodedChar = char::from_u32(next as u32 - 38) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else if ('F'..='J').contains(&next) { decodedChar = char::from_u32(next as u32 - 11) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else if ('K'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 + 16) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else if ('P'..='T').contains(&next) { decodedChar = char::from_u32(next as u32 + 43) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else if next == 'U' { decodedChar = 0 as char; } else if next == 'V' { @@ -371,18 +371,18 @@ impl Code39Reader { } else if next == 'X' || next == 'Y' || next == 'Z' { decodedChar = 127 as char; } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } '/' => { // /A to /O map to ! to , and /Z maps to : if ('A'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 - 32) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } _ => {} diff --git a/src/oned/code_39_writer.rs b/src/oned/code_39_writer.rs index 9e98ff5..e6cfd1b 100644 --- a/src/oned/code_39_writer.rs +++ b/src/oned/code_39_writer.rs @@ -34,7 +34,7 @@ impl OneDimensionalCodeWriter for Code39Writer { let mut contents = contents.to_owned(); let mut length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested contents should be less than 80 digits long, but got {length}" ))); } @@ -48,14 +48,14 @@ impl OneDimensionalCodeWriter for Code39Writer { contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) .is_none() { contents = Self::tryToConvertToExtendedMode(&contents)?; length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgumentWith(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)"))); + return Err(Exceptions::illegal_argument_with(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)"))); } break; } @@ -71,7 +71,7 @@ impl OneDimensionalCodeWriter for Code39Writer { pos += Self::appendPattern(&mut result, pos as usize, &narrowWhite, false); //append next character to byte matrix for i in 0..length { - let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else { + let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) else { continue; }; Self::toIntArray( @@ -118,56 +118,56 @@ impl Code39Writer { extendedContent.push('$'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 1)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character < ' ' { extendedContent.push('%'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 27)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= ',' || character == '/' || character == ':' { extendedContent.push('/'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 33)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= '9' { extendedContent.push( char::from_u32('0' as u32 + (character as u32 - 48)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= '?' { extendedContent.push('%'); extendedContent.push( char::from_u32('F' as u32 + (character as u32 - 59)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= 'Z' { extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 65)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= '_' { extendedContent.push('%'); extendedContent.push( char::from_u32('K' as u32 + (character as u32 - 91)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= 'z' { extendedContent.push('+'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 97)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character as u32 <= 127 { extendedContent.push('%'); extendedContent.push( char::from_u32('P' as u32 + (character as u32 - 123)) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested content contains a non-encodable character: '{character}'" ))); } diff --git a/src/oned/code_93_reader.rs b/src/oned/code_93_reader.rs index 4961a4d..3d4216a 100644 --- a/src/oned/code_93_reader.rs +++ b/src/oned/code_93_reader.rs @@ -66,7 +66,7 @@ impl OneDReader for Code93Reader { one_d_reader::recordPattern(row, nextStart, &mut theCounters)?; let pattern = Self::toPattern(&theCounters); if pattern < 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -95,12 +95,12 @@ impl OneDReader for Code93Reader { // Should be at least one more black module if nextStart == end || !row.get(nextStart) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if self.decodeRowRXingResult.chars().count() < 2 { // false positive -- need at least 2 checksum digits - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Self::checkChecksums(&self.decodeRowRXingResult)?; @@ -194,7 +194,7 @@ impl Code93Reader { isWhite = !isWhite; } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn toPattern(counters: &[u32; 6]) -> i32 { @@ -224,7 +224,7 @@ impl Code93Reader { return Ok(Self::ALPHABET[i]); } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn decodeExtended(encoded: &str) -> Result { @@ -234,52 +234,52 @@ impl Code93Reader { while i < length { // for i in 0..length { // for (int i = 0; i < length; i++) { - let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; + let c = encoded.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; if ('a'..='d').contains(&c) { if i >= length - 1 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let mut decodedChar = '\0'; match c { 'd' => { // +A to +Z map to a to z if ('A'..='Z').contains(&next) { decodedChar = - char::from_u32(next as u32 + 32).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 + 32).ok_or(Exceptions::PARSE)?; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } 'a' => { // $A to $Z map to control codes SH to SB if ('A'..='Z').contains(&next) { decodedChar = - char::from_u32(next as u32 - 64).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 - 64).ok_or(Exceptions::PARSE)?; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } 'b' => { if ('A'..='E').contains(&next) { // %A to %E map to control codes ESC to USep decodedChar = - char::from_u32(next as u32 - 38).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 - 38).ok_or(Exceptions::PARSE)?; } else if ('F'..='J').contains(&next) { // %F to %J map to ; < = > ? decodedChar = - char::from_u32(next as u32 - 11).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 - 11).ok_or(Exceptions::PARSE)?; } else if ('K'..='O').contains(&next) { // %K to %O map to [ \ ] ^ _ decodedChar = - char::from_u32(next as u32 + 16).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 + 16).ok_or(Exceptions::PARSE)?; } else if ('P'..='T').contains(&next) { // %P to %T map to { | } ~ DEL decodedChar = - char::from_u32(next as u32 + 43).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 + 43).ok_or(Exceptions::PARSE)?; } else if next == 'U' { // %U map to NUL decodedChar = '\0'; @@ -293,18 +293,18 @@ impl Code93Reader { // %X to %Z all map to DEL (127) decodedChar = 127 as char; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } 'c' => { // /A to /O map to ! to , and /Z maps to : if ('A'..='O').contains(&next) { decodedChar = - char::from_u32(next as u32 - 32).ok_or(Exceptions::parse)?; + char::from_u32(next as u32 - 32).ok_or(Exceptions::PARSE)?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } _ => {} @@ -334,7 +334,7 @@ impl Code93Reader { for i in (0..checkPosition).rev() { total += weight * Self::ALPHABET_STRING - .find(result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) + .find(result.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) .map_or_else(|| -1_i32, |v| v as i32); weight += 1; if weight > weightMax as i32 { @@ -344,10 +344,10 @@ impl Code93Reader { if result .chars() .nth(checkPosition) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? != Self::ALPHABET[(total as usize) % 47] { - Err(Exceptions::checksum) + Err(Exceptions::CHECKSUM) } else { Ok(()) } diff --git a/src/oned/code_93_writer.rs b/src/oned/code_93_writer.rs index 740469b..2da2579 100644 --- a/src/oned/code_93_writer.rs +++ b/src/oned/code_93_writer.rs @@ -36,7 +36,7 @@ impl OneDimensionalCodeWriter for Code93Writer { let mut contents = Self::convertToExtended(contents)?; let length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgumentWith(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" ))); + return Err(Exceptions::illegal_argument_with(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" ))); } //length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar @@ -49,7 +49,7 @@ impl OneDimensionalCodeWriter for Code93Writer { for i in 0..length { // for (int i = 0; i < length; i++) { - let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else {panic!("alphabet")}; + let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) else {panic!("alphabet")}; pos += Self::appendPattern( &mut result, pos, @@ -66,7 +66,7 @@ impl OneDimensionalCodeWriter for Code93Writer { Code93Reader::ALPHABET_STRING .chars() .nth(check1) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ); let check2 = Self::computeChecksumIndex(&contents, 15); @@ -157,13 +157,13 @@ impl Code93Writer { // SOH - SUB: ($)A - ($)Z extendedContent.push('a'); extendedContent.push( - char::from_u32('A' as u32 + character as u32 - 1).ok_or(Exceptions::parse)?, + char::from_u32('A' as u32 + character as u32 - 1).ok_or(Exceptions::PARSE)?, ); } else if character as u32 <= 31 { // ESC - US: (%)A - (%)E extendedContent.push('b'); extendedContent.push( - char::from_u32('A' as u32 + character as u32 - 27).ok_or(Exceptions::parse)?, + char::from_u32('A' as u32 + character as u32 - 27).ok_or(Exceptions::PARSE)?, ); } else if character == ' ' || character == '$' || character == '%' || character == '+' { // space $ % + @@ -173,7 +173,7 @@ impl Code93Writer { extendedContent.push('c'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - '!' as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character <= '9' { extendedContent.push(character); @@ -185,7 +185,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('F' as u32 + character as u32 - ';' as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character == '@' { // @: (%)V @@ -198,7 +198,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('K' as u32 + character as u32 - '[' as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character == '`' { // `: (%)W @@ -208,17 +208,17 @@ impl Code93Writer { extendedContent.push('d'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - 'a' as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else if character as u32 <= 127 { // { - DEL: (%)P - (%)T extendedContent.push('b'); extendedContent.push( char::from_u32('P' as u32 + character as u32 - '{' as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested content contains a non-encodable character: '{character}'" ))); } diff --git a/src/oned/ean_13_reader.rs b/src/oned/ean_13_reader.rs index 1af520c..8c589bf 100644 --- a/src/oned/ean_13_reader.rs +++ b/src/oned/ean_13_reader.rs @@ -66,7 +66,7 @@ impl UPCEANReader for EAN13Reader { &upc_ean_reader::L_AND_G_PATTERNS, )?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; @@ -89,7 +89,7 @@ impl UPCEANReader for EAN13Reader { let bestMatch = self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; @@ -148,11 +148,11 @@ impl EAN13Reader { if lgPatternFound == Self::FIRST_DIGIT_ENCODINGS[d] { resultString.insert( 0, - char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parse)?, + char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::PARSE)?, ); return Ok(()); } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index 23e5d5a..3a94b21 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -46,13 +46,13 @@ impl OneDimensionalCodeWriter for EAN13Writer { } 13 => { if !reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Contents do not pass checksum", )); } } _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested contents should be 12 or 13 digits long, but got {length}" ))) } @@ -63,9 +63,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; + .ok_or(Exceptions::PARSE)? as usize; let parities = EAN13Reader::FIRST_DIGIT_ENCODINGS[firstDigit]; let mut result = [false; CODE_WIDTH]; let mut pos = 0; @@ -80,9 +80,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; + .ok_or(Exceptions::PARSE)? as usize; if (parities >> (6 - i) & 1) == 1 { digit += 10; } @@ -101,9 +101,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; + .ok_or(Exceptions::PARSE)? as usize; pos += EAN13Writer::appendPattern( &mut result, diff --git a/src/oned/ean_8_reader.rs b/src/oned/ean_8_reader.rs index 890cbcb..99a76be 100644 --- a/src/oned/ean_8_reader.rs +++ b/src/oned/ean_8_reader.rs @@ -54,7 +54,7 @@ impl UPCEANReader for EAN8Reader { let bestMatch = self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; @@ -70,7 +70,7 @@ impl UPCEANReader for EAN8Reader { let bestMatch = self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; x += 1; diff --git a/src/oned/ean_8_writer.rs b/src/oned/ean_8_writer.rs index 50d9d96..1553c2f 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -56,13 +56,13 @@ impl OneDimensionalCodeWriter for EAN8Writer { } 8 => { if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Contents do not pass checksum", )); } } _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested contents should be 7 or 8 digits long, but got {length}" ))) } @@ -81,9 +81,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::indexOutOfBounds)? as usize; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize; pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], false) as usize; } @@ -96,9 +96,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::indexOutOfBounds)? as usize; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize; pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], true) as usize; } diff --git a/src/oned/itf_reader.rs b/src/oned/itf_reader.rs index 8b36565..efe6625 100644 --- a/src/oned/itf_reader.rs +++ b/src/oned/itf_reader.rs @@ -143,7 +143,7 @@ impl OneDReader for ITFReader { lengthOK = true; } if !lengthOK { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let mut resultObject = RXingResult::new( @@ -198,9 +198,9 @@ impl ITFReader { } let mut bestMatch = self.decodeDigit(&counterBlack)?; - resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parse)?); + resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::PARSE)?); bestMatch = self.decodeDigit(&counterWhite)?; - resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parse)?); + resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::PARSE)?); payloadStart += counterDigitPair.iter().sum::() as usize; } @@ -261,7 +261,7 @@ impl ITFReader { if quietCount != 0 { // Unable to find the necessary number of quiet zone pixels. - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } else { Ok(()) } @@ -278,7 +278,7 @@ impl ITFReader { let width = row.getSize(); let endStart = row.getNextSet(0); if endStart == width { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(endStart) @@ -373,7 +373,7 @@ impl ITFReader { isWhite = !isWhite; } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** @@ -402,7 +402,7 @@ impl ITFReader { if bestMatch >= 0 { Ok(bestMatch as u32 % 10) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } } diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index a50bf25..efdd68e 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -33,12 +33,12 @@ impl OneDimensionalCodeWriter for ITFWriter { fn encode_oned(&self, contents: &str) -> Result> { let length = contents.chars().count(); if length % 2 != 0 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "The length of the input should be even", )); } if length > 80 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested contents should be less than 80 digits long, but got {length}" ))); } @@ -52,15 +52,15 @@ impl OneDimensionalCodeWriter for ITFWriter { let one = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; + .ok_or(Exceptions::PARSE)? as usize; let two = contents .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; + .ok_or(Exceptions::PARSE)? as usize; let mut encoding = [0; 10]; for j in 0..5 { encoding[2 * j] = PATTERNS[one][j]; diff --git a/src/oned/multi_format_one_d_reader.rs b/src/oned/multi_format_one_d_reader.rs index 2400e6b..9647b1a 100644 --- a/src/oned/multi_format_one_d_reader.rs +++ b/src/oned/multi_format_one_d_reader.rs @@ -47,7 +47,7 @@ impl OneDReader for MultiFormatOneDReader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } impl MultiFormatOneDReader { @@ -166,7 +166,7 @@ impl Reader for MultiFormatOneDReader { Ok(result) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/oned/multi_format_upc_ean_reader.rs b/src/oned/multi_format_upc_ean_reader.rs index 2284695..2743157 100644 --- a/src/oned/multi_format_upc_ean_reader.rs +++ b/src/oned/multi_format_upc_ean_reader.rs @@ -135,7 +135,7 @@ impl OneDReader for MultiFormatUPCEANReader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } @@ -198,7 +198,7 @@ impl Reader for MultiFormatUPCEANReader { Ok(result) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 463a9fc..a73b59e 100644 --- a/src/oned/one_d_code_writer.rs +++ b/src/oned/one_d_code_writer.rs @@ -101,7 +101,7 @@ pub trait OneDimensionalCodeWriter: Writer { */ fn checkNumeric(contents: &str) -> Result<()> { if !NUMERIC.is_match(contents) { - Err(Exceptions::illegalArgumentWith( + Err(Exceptions::illegal_argument_with( "Input should only contain digits 0-9", )) } else { @@ -164,17 +164,17 @@ impl Writer for L { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgumentWith("Found empty contents")); + return Err(Exceptions::illegal_argument_with("Found empty contents")); } if width < 0 || height < 0 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Negative size is not allowed. Input: {width}x{height}" ))); } if let Some(supportedFormats) = self.getSupportedWriteFormats() { if !supportedFormats.contains(format) { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Can only encode {supportedFormats:?}, but got {format:?}" ))); } @@ -183,7 +183,7 @@ impl Writer for L { let mut sidesMargin = self.getDefaultMargin(); if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) { sidesMargin = margin.parse::().map_err(|e| { - Exceptions::illegalArgumentWith(format!("couldnt parse {margin}: {e}")) + Exceptions::illegal_argument_with(format!("couldnt parse {margin}: {e}")) })?; } diff --git a/src/oned/one_d_reader.rs b/src/oned/one_d_reader.rs index 53880e0..7fc96dd 100644 --- a/src/oned/one_d_reader.rs +++ b/src/oned/one_d_reader.rs @@ -125,7 +125,7 @@ pub trait OneDReader: Reader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** @@ -212,7 +212,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu let end = row.getSize(); if start >= end { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut isWhite = !row.get(start); @@ -235,7 +235,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. if !(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end)) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(()) } @@ -253,7 +253,7 @@ pub fn recordPatternInReverse(row: &BitArray, start: usize, counters: &mut [u32] } } if numTransitionsLeft >= 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } recordPattern(row, start + 1, counters)?; diff --git a/src/oned/rss/abstract_rss_reader.rs b/src/oned/rss/abstract_rss_reader.rs index c172620..fe3fd1c 100644 --- a/src/oned/rss/abstract_rss_reader.rs +++ b/src/oned/rss/abstract_rss_reader.rs @@ -39,7 +39,7 @@ pub trait AbstractRSSReaderTrait: OneDReader { return Ok(value as u32); } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index e981790..dceb5fc 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -53,13 +53,13 @@ pub fn buildBitArrayFromString(data: &str) -> Result { // for (int i = 0; i < dotsAndXs.length(); ++i) { if i % 9 == 0 { // spaces - if dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)? != ' ' { - return Err(Exceptions::illegalStateWith("space expected")); + if dotsAndXs.chars().nth(i).ok_or(Exceptions::PARSE)? != ' ' { + return Err(Exceptions::illegal_state_with("space expected")); } continue; } - let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)?; + let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::PARSE)?; if currentChar == 'X' || currentChar == 'x' { binary.set(counter); } @@ -81,7 +81,7 @@ pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result { sb.push(' '); let mut i = 0; while i < 8 && current < dotsAndXs_length { - sb.push(dotsAndXs.chars().nth(current).ok_or(Exceptions::parse)?); + sb.push(dotsAndXs.chars().nth(current).ok_or(Exceptions::PARSE)?); current += 1; i += 1; diff --git a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs index dab10ac..1ee6258 100644 --- a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs +++ b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs @@ -152,7 +152,7 @@ pub fn createDecoder<'a>( _ => {} } - Err(Exceptions::illegalStateWith(format!( + Err(Exceptions::illegal_state_with(format!( "unknown decoder: {information}" ))) } diff --git a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs index 2b01ddd..6673bbf 100644 --- a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01392xDecoder<'_> {} impl AbstractExpandedDecoder for AI01392xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::notFound); + return Err(crate::Exceptions::NOT_FOUND); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs index 12d60a7..ea47e60 100644 --- a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01393xDecoder<'_> {} impl AbstractExpandedDecoder for AI01393xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::notFound); + return Err(crate::Exceptions::NOT_FOUND); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs index 5a5f95f..f18ccd3 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs @@ -57,7 +57,7 @@ impl AbstractExpandedDecoder for AI013x0x1xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE + Self::DATE_SIZE { - return Err(crate::Exceptions::notFound); + return Err(crate::Exceptions::NOT_FOUND); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs index b4cd49a..9161e12 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs @@ -53,7 +53,7 @@ impl AbstractExpandedDecoder for AI013x0xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE { - return Err(crate::Exceptions::notFound); + return Err(crate::Exceptions::NOT_FOUND); } let mut buf = String::new(); diff --git a/src/oned/rss/expanded/decoders/decoded_numeric.rs b/src/oned/rss/expanded/decoders/decoded_numeric.rs index 2ac51ba..d30dba3 100644 --- a/src/oned/rss/expanded/decoders/decoded_numeric.rs +++ b/src/oned/rss/expanded/decoders/decoded_numeric.rs @@ -52,7 +52,7 @@ impl DecodedNumeric { if /*firstDigit < 0 ||*/ firstDigit > 10 || /*secondDigit < 0 ||*/ secondDigit > 10 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } Ok(Self { diff --git a/src/oned/rss/expanded/decoders/field_parser.rs b/src/oned/rss/expanded/decoders/field_parser.rs index 5dddc14..5c64001 100644 --- a/src/oned/rss/expanded/decoders/field_parser.rs +++ b/src/oned/rss/expanded/decoders/field_parser.rs @@ -146,7 +146,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { // Processing 2-digit AIs if rawInformation.chars().count() < 2 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let lookup: String = rawInformation.chars().take(2).collect(); @@ -159,7 +159,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { } if rawInformation.chars().count() < 3 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let firstThreeDigits: String = rawInformation.chars().take(3).collect(); @@ -172,7 +172,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { } if rawInformation.chars().count() < 4 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let threeDigitPlusDigitDataLength = THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH.get(&firstThreeDigits); @@ -192,18 +192,18 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { return processFixedAI(4, ffdl.length, rawInformation); } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn processFixedAI(aiSize: usize, fieldSize: usize, rawInformation: &str) -> Result { if rawInformation.chars().count() < aiSize { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let ai: String = rawInformation.chars().take(aiSize).collect(); if rawInformation.chars().count() < aiSize + fieldSize { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let field: String = rawInformation diff --git a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs index 2db7aa5..9226796 100644 --- a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs +++ b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs @@ -198,7 +198,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if let Some(r) = result.getDecodedInformation() { Ok(r.clone()) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } @@ -344,7 +344,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if (5..15).contains(&fiveBitValue) { return Ok(DecodedChar::new( pos + 5, - char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::PARSE)?, )); } @@ -353,14 +353,14 @@ impl<'a> GeneralAppIdDecoder<'_> { if (64..90).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, - char::from_u32(sevenBitValue + 1).ok_or(Exceptions::parse)?, + char::from_u32(sevenBitValue + 1).ok_or(Exceptions::PARSE)?, )); } if (90..116).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, - char::from_u32(sevenBitValue + 7).ok_or(Exceptions::parse)?, + char::from_u32(sevenBitValue + 7).ok_or(Exceptions::PARSE)?, )); } @@ -387,7 +387,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 250 => '?', 251 => '_', 252 => ' ', - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), }; Ok(DecodedChar::new(pos + 8, c)) @@ -422,7 +422,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if (5..15).contains(&fiveBitValue) { return Ok(DecodedChar::new( pos + 5, - char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::PARSE)?, )); } @@ -431,7 +431,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if (32..58).contains(&sixBitValue) { return Ok(DecodedChar::new( pos + 6, - char::from_u32(sixBitValue + 33).ok_or(Exceptions::parse)?, + char::from_u32(sixBitValue + 33).ok_or(Exceptions::PARSE)?, )); } @@ -442,7 +442,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 61 => '.', 62 => '/', _ => { - return Err(Exceptions::illegalStateWith(format!( + return Err(Exceptions::illegal_state_with(format!( "Decoding invalid alphanumeric value: {sixBitValue}" ))) } diff --git a/src/oned/rss/expanded/rss_expanded_reader.rs b/src/oned/rss/expanded/rss_expanded_reader.rs index e31c1f2..cb928c2 100644 --- a/src/oned/rss/expanded/rss_expanded_reader.rs +++ b/src/oned/rss/expanded/rss_expanded_reader.rs @@ -224,7 +224,7 @@ impl Reader for RSSExpandedReader { Ok(result) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } } @@ -294,7 +294,7 @@ impl RSSExpandedReader { if let Ok(to_add) = to_add_res { self.pairs.push(to_add); } else if self.pairs.is_empty() { - return Err(to_add_res.err().unwrap_or(Exceptions::illegalState)); + return Err(to_add_res.err().unwrap_or(Exceptions::ILLEGAL_STATE)); } else { // exit this loop when retrieveNextPair() fails and throws done = true; @@ -326,7 +326,7 @@ impl RSSExpandedReader { // } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn checkRows(&mut self, reverse: bool) -> Option> { @@ -370,7 +370,7 @@ impl RSSExpandedReader { ) -> Result> { for i in currentRow..self.rows.len() { // for (int i = currentRow; i < rows.size(); i++) { - let row = self.rows.get(i).ok_or(Exceptions::indexOutOfBounds)?; + let row = self.rows.get(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; self.pairs.clear(); for collectedRow in &collectedRows.clone() { // for (ExpandedRow collectedRow : collectedRows) { @@ -398,7 +398,7 @@ impl RSSExpandedReader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /// Whether the pairs form a valid find pattern sequence, @@ -529,24 +529,24 @@ impl RSSExpandedReader { // Not private for unit testing pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result { let binary = bit_array_builder::buildBitArray(&pairs.to_vec()) - .ok_or(Exceptions::IllegalStateException(None))?; + .ok_or(Exceptions::ILLEGAL_STATE)?; let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?; let resultingString = decoder.parseInformation()?; let firstPoints = pairs .get(0) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getPoints(); let lastPoints = pairs .last() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getPoints(); let mut result = RXingResult::new( @@ -645,7 +645,7 @@ impl RSSExpandedReader { let leftChar = self.decodeDataCharacter( row, - pattern.as_ref().ok_or(Exceptions::notFound)?, + pattern.as_ref().ok_or(Exceptions::NOT_FOUND)?, isOddPattern, true, )?; @@ -653,16 +653,16 @@ impl RSSExpandedReader { if !previousPairs.is_empty() && previousPairs .last() - .ok_or(Exceptions::notFound)? + .ok_or(Exceptions::NOT_FOUND)? .mustBeLast() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let rightChar = self .decodeDataCharacter( row, - pattern.as_ref().ok_or(Exceptions::notFound)?, + pattern.as_ref().ok_or(Exceptions::NOT_FOUND)?, isOddPattern, false, ) @@ -692,11 +692,11 @@ impl RSSExpandedReader { } else if previousPairs.is_empty() { rowOffset = 0; } else { - let lastPair = previousPairs.last().ok_or(Exceptions::indexOutOfBounds)?; + let lastPair = previousPairs.last().ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; rowOffset = lastPair .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getStartEnd()[1] as i32; } let mut searchingEvenPair = previousPairs.len() % 2 != 0; @@ -748,7 +748,7 @@ impl RSSExpandedReader { isWhite = !isWhite; } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn reverseCounters(counters: &mut [u32]) { @@ -845,7 +845,7 @@ impl RSSExpandedReader { let expectedElementWidth: f32 = (pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) as f32 / 15.0; if (elementWidth - expectedElementWidth).abs() / expectedElementWidth > 0.3 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } for (i, counter) in counters.iter().enumerate() { @@ -854,12 +854,12 @@ impl RSSExpandedReader { let mut count = (value + 0.5) as i32; // Round if count < 1 { if value < 0.3 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } count = 1; } else if count > 8 { if value > 8.7 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } count = 8; } @@ -899,7 +899,7 @@ impl RSSExpandedReader { let checksumPortion = oddChecksumPortion + evenChecksumPortion; if (oddSum & 0x01) != 0 || !(4..=13).contains(&oddSum) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let group = ((13 - oddSum) / 2) as usize; @@ -947,12 +947,12 @@ impl RSSExpandedReader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decrementEven = true; } @@ -960,12 +960,12 @@ impl RSSExpandedReader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } incrementEven = true; } @@ -973,7 +973,7 @@ impl RSSExpandedReader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Both bad if oddSum < evenSum { @@ -984,16 +984,16 @@ impl RSSExpandedReader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } - _ => return Err(Exceptions::notFound), + _ => return Err(Exceptions::NOT_FOUND), } if incrementOdd { if decrementOdd { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -1002,7 +1002,7 @@ impl RSSExpandedReader { } if incrementEven { if decrementEven { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Self::increment(&mut self.evenCounts, &self.oddRoundingErrors); } diff --git a/src/oned/rss/rss_14_reader.rs b/src/oned/rss/rss_14_reader.rs index 289023e..056e69e 100644 --- a/src/oned/rss/rss_14_reader.rs +++ b/src/oned/rss/rss_14_reader.rs @@ -64,12 +64,12 @@ impl OneDReader for RSS14Reader { if right.getCount() > 1 && self.checkChecksum(left, right) { return self .constructRXingResult(left, right) - .ok_or(Exceptions::illegalState); + .ok_or(Exceptions::ILLEGAL_STATE); } } } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } impl Reader for RSS14Reader { @@ -123,7 +123,7 @@ impl Reader for RSS14Reader { Ok(result) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } } @@ -340,7 +340,7 @@ impl RSS14Reader { if outsideChar { if (oddSum & 0x01) != 0 || !(4..=12).contains(&oddSum) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let group = ((12 - oddSum) / 2) as usize; let oddWidest = Self::OUTSIDE_ODD_WIDEST[group]; @@ -355,7 +355,7 @@ impl RSS14Reader { )) } else { if (evenSum & 0x01) != 0 || !(4..=10).contains(&evenSum) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let group = ((10 - evenSum) / 2) as usize; let oddWidest = Self::INSIDE_ODD_WIDEST[group]; @@ -414,7 +414,7 @@ impl RSS14Reader { isWhite = !isWhite; } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } fn parseFoundFinderPattern( @@ -511,12 +511,12 @@ impl RSS14Reader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } decrementEven = true; } @@ -524,12 +524,12 @@ impl RSS14Reader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } incrementEven = true; } @@ -537,7 +537,7 @@ impl RSS14Reader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Both bad if oddSum < evenSum { @@ -548,15 +548,15 @@ impl RSS14Reader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } - _ => return Err(Exceptions::notFound), + _ => return Err(Exceptions::NOT_FOUND), } if incrementOdd { if decrementOdd { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -565,7 +565,7 @@ impl RSS14Reader { } if incrementEven { if decrementEven { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Self::increment(&mut self.evenCounts, &self.evenRoundingErrors); } diff --git a/src/oned/upc_a_reader.rs b/src/oned/upc_a_reader.rs index 2222438..db225e1 100644 --- a/src/oned/upc_a_reader.rs +++ b/src/oned/upc_a_reader.rs @@ -101,7 +101,7 @@ impl UPCAReader { Ok(upcaRXingResult) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } } diff --git a/src/oned/upc_a_writer.rs b/src/oned/upc_a_writer.rs index f414d69..cd983b0 100644 --- a/src/oned/upc_a_writer.rs +++ b/src/oned/upc_a_writer.rs @@ -48,7 +48,7 @@ impl Writer for UPCAWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::UPC_A { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Can only encode UPC-A, but got {format:?}" ))); } diff --git a/src/oned/upc_e_reader.rs b/src/oned/upc_e_reader.rs index 13b8c87..238321c 100644 --- a/src/oned/upc_e_reader.rs +++ b/src/oned/upc_e_reader.rs @@ -50,7 +50,7 @@ impl UPCEANReader for UPCEReader { while x < 6 && rowOffset < end { let bestMatch = self.decodeDigit(row, &mut counters, rowOffset, &L_AND_G_PATTERNS)?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; if bestMatch >= 10 { @@ -67,7 +67,7 @@ impl UPCEANReader for UPCEReader { fn checkChecksum(&self, s: &str) -> Result { self.checkStandardUPCEANChecksum( - &convertUPCEtoUPCA(s).ok_or(Exceptions::IllegalArgumentException(None))?, + &convertUPCEtoUPCA(s).ok_or(Exceptions::ILLEGAL_ARGUMENT)?, ) } @@ -126,15 +126,15 @@ impl UPCEReader { if lgPatternFound == Self::NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d] { resultString.insert( 0, - char::from_u32('0' as u32 + numSys as u32).ok_or(Exceptions::parse)?, + char::from_u32('0' as u32 + numSys as u32).ok_or(Exceptions::PARSE)?, ); resultString - .push(char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::PARSE)?); return Ok(()); } } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index cfad829..593e154 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -47,22 +47,22 @@ impl OneDimensionalCodeWriter for UPCEWriter { // No check digit present, calculate it and add it let check = reader.getStandardUPCEANChecksum( &upc_e_reader::convertUPCEtoUPCA(&contents) - .ok_or(Exceptions::illegalArgument)?, + .ok_or(Exceptions::ILLEGAL_ARGUMENT)?, )?; contents.push_str(&check.to_string()); } 8 => { if !reader.checkStandardUPCEANChecksum( &upc_e_reader::convertUPCEtoUPCA(&contents) - .ok_or(Exceptions::illegalArgument)?, + .ok_or(Exceptions::ILLEGAL_ARGUMENT)?, )? { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Contents do not pass checksum", )); } } _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Requested contents should be 7 or 8 digits long, but got {length}" ))) } @@ -73,11 +73,11 @@ impl OneDimensionalCodeWriter for UPCEWriter { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(0), 10); + .ok_or(Exceptions::PARSE)? as usize; //Character.digit(contents.charAt(0), 10); if firstDigit != 0 && firstDigit != 1 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Number system must be 0 or 1", )); } @@ -85,9 +85,9 @@ impl OneDimensionalCodeWriter for UPCEWriter { let checkDigit = contents .chars() .nth(7) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(7), 10); + .ok_or(Exceptions::PARSE)? as usize; //Character.digit(contents.charAt(7), 10); let parities = UPCEReader::NUMSYS_AND_CHECK_DIGIT_PATTERNS[firstDigit][checkDigit]; let mut result = [false; CODE_WIDTH]; @@ -99,9 +99,9 @@ impl OneDimensionalCodeWriter for UPCEWriter { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? .to_digit(10) - .ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(i), 10); + .ok_or(Exceptions::PARSE)? as usize; //Character.digit(contents.charAt(i), 10); if (parities >> (6 - i) & 1) == 1 { digit += 10; } diff --git a/src/oned/upc_ean_extension_2_support.rs b/src/oned/upc_ean_extension_2_support.rs index 13f7ce6..4bf5e8a 100644 --- a/src/oned/upc_ean_extension_2_support.rs +++ b/src/oned/upc_ean_extension_2_support.rs @@ -88,7 +88,7 @@ impl UPCEANExtension2Support { &upc_ean_reader::L_AND_G_PATTERNS, )?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; @@ -104,16 +104,16 @@ impl UPCEANExtension2Support { } if resultString.chars().count() != 2 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if resultString .parse::() - .map_err(|e| Exceptions::parseWith(format!("could not parse {resultString}: {e}")))? + .map_err(|e| Exceptions::parse_with(format!("could not parse {resultString}: {e}")))? % 4 != checkParity { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(rowOffset as u32) diff --git a/src/oned/upc_ean_extension_5_support.rs b/src/oned/upc_ean_extension_5_support.rs index 7748af1..ca8d51b 100644 --- a/src/oned/upc_ean_extension_5_support.rs +++ b/src/oned/upc_ean_extension_5_support.rs @@ -87,7 +87,7 @@ impl UPCEANExtension5Support { &upc_ean_reader::L_AND_G_PATTERNS, )?; resultString - .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::PARSE)?); rowOffset += counters.iter().sum::() as usize; @@ -104,14 +104,14 @@ impl UPCEANExtension5Support { } if resultString.chars().count() != 5 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let checkDigit = Self::determineCheckDigit(lgPatternFound)?; - if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgument)? + if Self::extensionChecksum(resultString).ok_or(Exceptions::ILLEGAL_ARGUMENT)? != checkDigit as u32 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(rowOffset as u32) @@ -146,7 +146,7 @@ impl UPCEANExtension5Support { return Ok(d); } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** diff --git a/src/oned/upc_ean_reader.rs b/src/oned/upc_ean_reader.rs index 021f61e..9f5a762 100644 --- a/src/oned/upc_ean_reader.rs +++ b/src/oned/upc_ean_reader.rs @@ -183,18 +183,18 @@ pub trait UPCEANReader: OneDReader { let end = endRange[1]; let quietEnd = end + (end - endRange[0]); if quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)? { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let resultString = result; // UPC/EAN should never be less than 8 chars anyway if resultString.chars().count() < 8 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } if !self.checkChecksum(&resultString)? { - return Err(Exceptions::checksum); + return Err(Exceptions::CHECKSUM); } let left = (startGuardRange[1] + startGuardRange[0]) as f32 / 2.0; @@ -241,7 +241,7 @@ pub trait UPCEANReader: OneDReader { } } if !valid { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } @@ -292,7 +292,7 @@ pub trait UPCEANReader: OneDReader { let char_in_question = s .chars() .nth(length - 1) - .ok_or(Exceptions::indexOutOfBounds)?; + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let check = char_in_question.is_ascii_digit(); let check_against = &s[..length - 1]; //s.subSequence(0, length - 1); @@ -300,7 +300,7 @@ pub trait UPCEANReader: OneDReader { Ok(calculated_checksum == if check { - char_in_question.to_digit(10).ok_or(Exceptions::parse)? + char_in_question.to_digit(10).ok_or(Exceptions::PARSE)? } else { u32::MAX }) @@ -315,10 +315,10 @@ pub trait UPCEANReader: OneDReader { let digit = (s .chars() .nth(i as usize) - .ok_or(Exceptions::indexOutOfBounds)? as i32) + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as i32) - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } sum += digit; @@ -331,10 +331,10 @@ pub trait UPCEANReader: OneDReader { let digit = (s .chars() .nth(i as usize) - .ok_or(Exceptions::indexOutOfBounds)? as i32) + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as i32) - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } sum += digit; @@ -421,7 +421,7 @@ pub trait UPCEANReader: OneDReader { } } - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** @@ -458,7 +458,7 @@ pub trait UPCEANReader: OneDReader { if bestMatch >= 0 { Ok(bestMatch as usize) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/pdf417/decoder/bounding_box.rs b/src/pdf417/decoder/bounding_box.rs index c42f713..2ce0057 100644 --- a/src/pdf417/decoder/bounding_box.rs +++ b/src/pdf417/decoder/bounding_box.rs @@ -47,7 +47,7 @@ impl BoundingBox { let leftUnspecified = topLeft.is_none() || bottomLeft.is_none(); let rightUnspecified = topRight.is_none() || bottomRight.is_none(); if leftUnspecified && rightUnspecified { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let newTopLeft; @@ -56,20 +56,20 @@ impl BoundingBox { let newBottomRight; if leftUnspecified { - newTopRight = topRight.ok_or(Exceptions::illegalState)?; - newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?; + newTopRight = topRight.ok_or(Exceptions::ILLEGAL_STATE)?; + newBottomRight = bottomRight.ok_or(Exceptions::ILLEGAL_STATE)?; newTopLeft = point(0.0, newTopRight.y); newBottomLeft = point(0.0, newBottomRight.y); } else if rightUnspecified { - newTopLeft = topLeft.ok_or(Exceptions::illegalState)?; - newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?; + newTopLeft = topLeft.ok_or(Exceptions::ILLEGAL_STATE)?; + newBottomLeft = bottomLeft.ok_or(Exceptions::ILLEGAL_STATE)?; newTopRight = point(image.getWidth() as f32 - 1.0, newTopLeft.y); newBottomRight = point(image.getWidth() as f32 - 1.0, newBottomLeft.y); } else { - newTopLeft = topLeft.ok_or(Exceptions::illegalState)?; - newTopRight = topRight.ok_or(Exceptions::illegalState)?; - newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?; - newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?; + newTopLeft = topLeft.ok_or(Exceptions::ILLEGAL_STATE)?; + newTopRight = topRight.ok_or(Exceptions::ILLEGAL_STATE)?; + newBottomLeft = bottomLeft.ok_or(Exceptions::ILLEGAL_STATE)?; + newBottomRight = bottomRight.ok_or(Exceptions::ILLEGAL_STATE)?; } Ok(BoundingBox { @@ -104,13 +104,13 @@ impl BoundingBox { rightBox: Option, ) -> Result { if leftBox.is_none() { - return Ok(rightBox.as_ref().ok_or(Exceptions::illegalState)?.clone()); + return Ok(rightBox.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?.clone()); } if rightBox.is_none() { - return Ok(leftBox.as_ref().ok_or(Exceptions::illegalState)?.clone()); + return Ok(leftBox.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?.clone()); } - let leftBox = leftBox.ok_or(Exceptions::illegalState)?; - let rightBox = rightBox.ok_or(Exceptions::illegalState)?; + let leftBox = leftBox.ok_or(Exceptions::ILLEGAL_STATE)?; + let rightBox = rightBox.ok_or(Exceptions::ILLEGAL_STATE)?; BoundingBox::new( leftBox.image, diff --git a/src/pdf417/decoder/decoded_bit_stream_parser.rs b/src/pdf417/decoder/decoded_bit_stream_parser.rs index 956bd83..75d35ad 100644 --- a/src/pdf417/decoder/decoded_bit_stream_parser.rs +++ b/src/pdf417/decoder/decoded_bit_stream_parser.rs @@ -121,7 +121,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { codeIndex = byteCompaction(code, codewords, codeIndex, &mut result)? } MODE_SHIFT_TO_BYTE_COMPACTION_MODE => { - result.append_char(char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parse)?); + result.append_char(char::from_u32(codewords[codeIndex]).ok_or(Exceptions::PARSE)?); codeIndex += 1; } NUMERIC_COMPACTION_MODE_LATCH => { @@ -147,7 +147,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { BEGIN_MACRO_PDF417_OPTIONAL_FIELD | MACRO_PDF417_TERMINATOR => // Should not see these outside a macro block { - return Err(Exceptions::format) + return Err(Exceptions::FORMAT) } _ => { // Default to text compaction. During testing numerous barcodes @@ -162,7 +162,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { result = result.build_result(); if result.is_empty() && resultMetadata.getFileId().is_empty() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let mut decoderRXingResult = DecoderRXingResult::new( @@ -184,7 +184,7 @@ pub fn decodeMacroBlock( let mut codeIndex = codeIndex; if codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0] as usize { // we must have at least two bytes left for the segment index - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS]; for seq in segmentIndexArray @@ -202,7 +202,7 @@ pub fn decodeMacroBlock( resultMetadata.setSegmentIndex(parsed_int); } else { // too large; bad input? - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } // Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec @@ -219,7 +219,7 @@ pub fn decodeMacroBlock( } if fileId.chars().count() == 0 { // at least one fileId codeword is required (Annex H.2) - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } resultMetadata.setFileId(fileId); @@ -256,7 +256,7 @@ pub fn decodeMacroBlock( codeIndex = numericCompaction(codewords, codeIndex + 1, &mut segmentCount)?; segmentCount = segmentCount.build_result(); let Ok(parsed_segment_count) = segmentCount.to_string().parse() else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); }; resultMetadata.setSegmentCount(parsed_segment_count); } @@ -265,7 +265,7 @@ pub fn decodeMacroBlock( codeIndex = numericCompaction(codewords, codeIndex + 1, &mut timestamp)?; timestamp = timestamp.build_result(); let Ok(parsed_timestamp) = timestamp.to_string().parse() else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); }; resultMetadata.setTimestamp(parsed_timestamp); } @@ -274,7 +274,7 @@ pub fn decodeMacroBlock( codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?; checksum = checksum.build_result(); let Ok(parsed_checksum ) = checksum.to_string().parse() else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); }; resultMetadata.setChecksum(parsed_checksum); } @@ -283,18 +283,18 @@ pub fn decodeMacroBlock( codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?; fileSize = fileSize.build_result(); let Ok(parsed_file_size)= fileSize.to_string().parse() else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); }; resultMetadata.setFileSize(parsed_file_size); } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } MACRO_PDF417_TERMINATOR => { codeIndex += 1; resultMetadata.setLastSegment(true); } - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } @@ -386,7 +386,7 @@ fn textCompaction( result, subMode, ) - .ok_or(Exceptions::illegalState)?; + .ok_or(Exceptions::ILLEGAL_STATE)?; result.appendECI(codewords[codeIndex])?; codeIndex += 1; textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; @@ -770,14 +770,14 @@ fn numericCompaction( fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result { let mut result = 0 .to_biguint() - .ok_or(Exceptions::ArithmeticException(None))?; + .ok_or(Exceptions::ARITHMETIC)?; for i in 0..count { result += - &EXP900[count - i - 1] * (codewords[i].to_biguint().ok_or(Exceptions::arithmetic)?); + &EXP900[count - i - 1] * (codewords[i].to_biguint().ok_or(Exceptions::ARITHMETIC)?); } let resultString = result.to_string(); if !resultString.starts_with('1') { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } Ok(resultString[1..].to_owned()) } diff --git a/src/pdf417/decoder/ec/error_correction.rs b/src/pdf417/decoder/ec/error_correction.rs index 47759ac..7c57333 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -100,7 +100,7 @@ pub fn decode(received: &mut [u32], numECCodewords: u32, erasures: &mut [u32]) - // for (int i = 0; i < errorLocations.length; i++) { let position = received.len() as isize - 1 - field.log(errorLocations[i])? as isize; if position < 0 { - return Err(Exceptions::checksumWith(file!())); + return Err(Exceptions::checksum_with(file!())); } received[position as usize] = field.subtract(received[position as usize], errorMagnitudes[i]); @@ -137,7 +137,7 @@ fn runEuclideanAlgorithm( // Divide rLastLast by rLast, with quotient in q and remainder in r if rLast.isZero() { // Oops, Euclidean algorithm already terminated? - return Err(Exceptions::checksumWith(file!())); + return Err(Exceptions::checksum_with(file!())); } r = rLastLast; let mut q = ModulusPoly::getZero(field); //field.getZero(); @@ -159,7 +159,7 @@ fn runEuclideanAlgorithm( let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::checksumWith(file!())); + return Err(Exceptions::checksum_with(file!())); } let inverse = field.inverse(sigmaTildeAtZero)?; @@ -184,7 +184,7 @@ fn findErrorLocations(errorLocator: Rc, field: &ModulusGF) -> Resul i += 1; } if e != numErrors { - return Err(Exceptions::checksumWith(file!())); + return Err(Exceptions::checksum_with(file!())); } Ok(result) } diff --git a/src/pdf417/decoder/ec/modulus_gf.rs b/src/pdf417/decoder/ec/modulus_gf.rs index ae97f3f..dd811ff 100644 --- a/src/pdf417/decoder/ec/modulus_gf.rs +++ b/src/pdf417/decoder/ec/modulus_gf.rs @@ -78,7 +78,7 @@ impl ModulusGF { pub fn log(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::arithmetic) + Err(Exceptions::ARITHMETIC) } else { Ok(self.logTable[a as usize]) } @@ -86,7 +86,7 @@ impl ModulusGF { pub fn inverse(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::arithmetic) + Err(Exceptions::ARITHMETIC) } else { Ok(self.expTable[self.modulus as usize - self.logTable[a as usize] as usize - 1]) } diff --git a/src/pdf417/decoder/ec/modulus_poly.rs b/src/pdf417/decoder/ec/modulus_poly.rs index 34957c0..0ee9457 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -34,7 +34,7 @@ pub struct ModulusPoly { impl ModulusPoly { pub fn new(field: &'static ModulusGF, coefficients: Vec) -> Result { if coefficients.is_empty() { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } let orig_coefs = coefficients.clone(); let mut coefficients = coefficients; @@ -124,7 +124,7 @@ impl ModulusPoly { pub fn add(&self, other: Rc) -> Result> { if self.field != other.field { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "ModulusPolys do not have same ModulusGF field", )); } @@ -158,7 +158,7 @@ impl ModulusPoly { pub fn subtract(&self, other: Rc) -> Result> { if self.field != other.field { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "ModulusPolys do not have same ModulusGF field", )); } @@ -170,7 +170,7 @@ impl ModulusPoly { pub fn multiply(&self, other: Rc) -> Result> { if !(self.field == other.field) { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "ModulusPolys do not have same ModulusGF field", )); } diff --git a/src/pdf417/decoder/pdf_417_scanning_decoder.rs b/src/pdf417/decoder/pdf_417_scanning_decoder.rs index 6977d8f..c526062 100644 --- a/src/pdf417/decoder/pdf_417_scanning_decoder.rs +++ b/src/pdf417/decoder/pdf_417_scanning_decoder.rs @@ -86,7 +86,7 @@ pub fn decode( } detectionRXingResult = merge(&mut leftRowIndicatorColumn, &mut rightRowIndicatorColumn)?; if detectionRXingResult.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // detectionRXingResult = detectionRXingResult; @@ -142,7 +142,7 @@ pub fn decode( // for (int imageRow = boundingBox.getMinY(); imageRow <= boundingBox.getMaxY(); imageRow++) { startColumn = getStartColumn(&detectionRXingResult, barcodeColumn, imageRow, leftToRight) - .ok_or(Exceptions::illegalState)? as i32; + .ok_or(Exceptions::ILLEGAL_STATE)? as i32; if startColumn < 0 || startColumn > boundingBox.getMaxX() as i32 { if previousStartColumn == -1 { continue; @@ -412,7 +412,7 @@ fn adjustCodewordCount( as u32; if numberOfCodewords.is_empty() { if !(1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords) { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } barcodeMatrix01.setValue(calculatedNumberOfCodewords); } else if numberOfCodewords[0] != calculatedNumberOfCodewords @@ -508,7 +508,7 @@ fn createDecoderRXingResultFromAmbiguousValues( // // // } if ambiguousIndexCount.is_empty() { - return Err(Exceptions::checksum); + return Err(Exceptions::CHECKSUM); } for i in 0..ambiguousIndexCount.len() { // for (int i = 0; i < ambiguousIndexCount.length; i++) { @@ -518,14 +518,14 @@ fn createDecoderRXingResultFromAmbiguousValues( } else { ambiguousIndexCount[i] = 0; if i == ambiguousIndexCount.len() - 1 { - return Err(Exceptions::checksum); + return Err(Exceptions::CHECKSUM); } } } tries -= 1; } - Err(Exceptions::checksum) + Err(Exceptions::CHECKSUM) } fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec> { @@ -845,7 +845,7 @@ fn decodeCodewords( erasures: &mut [u32], ) -> Result { if codewords.is_empty() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let numECCodewords = 1 << (ecLevel + 1); @@ -880,7 +880,7 @@ fn correctErrors( || numECCodewords > MAX_EC_CODEWORDS { // Too many errors or EC Codewords is corrupted - return Err(Exceptions::checksum); + return Err(Exceptions::CHECKSUM); } ec::error_correction::decode(codewords, numECCodewords, erasures) } @@ -892,21 +892,21 @@ fn verifyCodewordCount(codewords: &mut [u32], numECCodewords: u32) -> Result<()> if codewords.len() < 4 { // Codeword array size should be at least 4 allowing for // Count CW, At least one Data CW, Error Correction CW, Error Correction CW - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. let numberOfCodewords = codewords[0]; if numberOfCodewords > codewords.len() as u32 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } if numberOfCodewords == 0 { // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) if numECCodewords < codewords.len() as u32 { codewords[0] = codewords.len() as u32 - numECCodewords; } else { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } } Ok(()) diff --git a/src/pdf417/detector/pdf_417_detector.rs b/src/pdf417/detector/pdf_417_detector.rs index 1bf1935..5ae0289 100644 --- a/src/pdf417/detector/pdf_417_detector.rs +++ b/src/pdf417/detector/pdf_417_detector.rs @@ -78,7 +78,7 @@ pub fn detect_with_hints( for rotation in ROTATIONS { // for (int rotation : ROTATIONS) { let bitMatrix = applyRotation(originalMatrix, rotation)?; - let barcodeCoordinates = detect(multiple, &bitMatrix).ok_or(Exceptions::notFound)?; + let barcodeCoordinates = detect(multiple, &bitMatrix).ok_or(Exceptions::NOT_FOUND)?; if !barcodeCoordinates.is_empty() { return Ok(PDF417DetectorRXingResult::with_rotation( bitMatrix.into_owned(), diff --git a/src/pdf417/encoder/compaction.rs b/src/pdf417/encoder/compaction.rs index 8de3364..ccd9d1c 100644 --- a/src/pdf417/encoder/compaction.rs +++ b/src/pdf417/encoder/compaction.rs @@ -40,7 +40,7 @@ impl TryFrom<&String> for Compaction { _ => {} } } - Err(Exceptions::formatWith(format!( + Err(Exceptions::format_with(format!( "Compaction must be 0-3 (inclusivie). Found: {value}" ))) } diff --git a/src/pdf417/encoder/pdf_417.rs b/src/pdf417/encoder/pdf_417.rs index 2ee5dca..46b7a90 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -162,7 +162,7 @@ impl PDF417 { pattern = CODEWORD_TABLE[cluster][fullCodewords .chars() .nth(idx) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize]; Self::encodeChar(pattern, 17, logic.getCurrentRowMut()); idx += 1; @@ -223,17 +223,17 @@ impl PDF417 { //2. step: construct data codewords if sourceCodeWords + errorCorrectionCodeWords + 1 > 929 { // +1 for symbol length CW - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "Encoded message contains too many code words, message too big ({} bytes)", msg.chars().count() ))); } let n = sourceCodeWords + pad + 1; let mut sb = String::with_capacity(n as usize); - sb.push(char::from_u32(n).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(n).ok_or(Exceptions::PARSE)?); sb.push_str(&highLevel); for _i in 0..pad { - sb.push(char::from_u32(900).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(900).ok_or(Exceptions::PARSE)?); //PAD characters } let dataCodewords = sb; @@ -312,7 +312,7 @@ impl PDF417 { } } - dimension.ok_or(Exceptions::writerWith("Unable to fit message in columns")) + dimension.ok_or(Exceptions::writer_with("Unable to fit message in columns")) } /** diff --git a/src/pdf417/encoder/pdf_417_error_correction.rs b/src/pdf417/encoder/pdf_417_error_correction.rs index d3328d5..2888a26 100644 --- a/src/pdf417/encoder/pdf_417_error_correction.rs +++ b/src/pdf417/encoder/pdf_417_error_correction.rs @@ -120,7 +120,7 @@ static EC_COEFFICIENTS: Lazy<[Vec; 9]> = Lazy::new(|| { */ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { if errorCorrectionLevel > 8 { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Error correction level must be between 0 and 8!", )); } @@ -136,7 +136,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result */ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result { if n == 0 { - Err(Exceptions::illegalArgumentWith("n must be > 0")) + Err(Exceptions::illegal_argument_with("n must be > 0")) } else if n <= 40 { Ok(2) } else if n <= 160 { @@ -146,7 +146,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result { } else if n <= 863 { Ok(5) } else { - Err(Exceptions::writerWith("No recommendation possible")) + Err(Exceptions::writer_with("No recommendation possible")) } } @@ -165,7 +165,7 @@ pub fn generateErrorCorrection(dataCodewords: &str, errorCorrectionLevel: u32) - let t1 = (dataCodewords .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBounds)? as u32 + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32 + e[e.len() - 1] as u32) % 929; let mut t2; @@ -174,18 +174,18 @@ pub fn generateErrorCorrection(dataCodewords: &str, errorCorrectionLevel: u32) - while j >= 1 { t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel as usize][j]) % 929; t3 = 929 - t2; - e[j] = char::from_u32((e[j - 1] as u32 + t3) % 929).ok_or(Exceptions::parse)?; + e[j] = char::from_u32((e[j - 1] as u32 + t3) % 929).ok_or(Exceptions::PARSE)?; j -= 1; } t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel as usize][0]) % 929; t3 = 929 - t2; - e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::parse)?; + e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::PARSE)?; } let mut sb = String::with_capacity(k as usize); let mut j = k as isize - 1; while j >= 0 { if e[j as usize] as u32 != 0 { - e[j as usize] = char::from_u32(929 - e[j as usize] as u32).ok_or(Exceptions::parse)?; + e[j as usize] = char::from_u32(929 - e[j as usize] as u32).ok_or(Exceptions::PARSE)?; } sb.push(e[j as usize]); diff --git a/src/pdf417/encoder/pdf_417_high_level_encoder.rs b/src/pdf417/encoder/pdf_417_high_level_encoder.rs index 17f949f..b35144f 100644 --- a/src/pdf417/encoder/pdf_417_high_level_encoder.rs +++ b/src/pdf417/encoder/pdf_417_high_level_encoder.rs @@ -179,13 +179,13 @@ pub fn encodeHighLevel( ) -> Result { let mut encoding = encoding; if msg.is_empty() { - return Err(Exceptions::writerWith("Empty message not allowed")); + return Err(Exceptions::writer_with("Empty message not allowed")); } if encoding.is_none() && !autoECI { for ch in msg.chars() { if ch as u32 > 255 { - return Err(Exceptions::writerWith(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch))); + return Err(Exceptions::writer_with(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.", ch as u32, ch))); } } } @@ -200,10 +200,10 @@ pub fn encodeHighLevel( if encoding.is_none() { encoding = Some(DEFAULT_ENCODING); } else if DEFAULT_ENCODING.name() - != encoding.as_ref().ok_or(Exceptions::illegalState)?.name() + != encoding.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?.name() { if let Some(eci) = - CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::illegalState)?) + CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::ILLEGAL_STATE)?) { encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?; } @@ -225,7 +225,7 @@ pub fn encodeHighLevel( Compaction::BYTE => { let msgBytes = encoding .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .encode(&input.to_string(), encoding::EncoderTrap::Strict) .unwrap_or_default(); //input.to_string().getBytes(encoding); encodeBinary( @@ -237,7 +237,7 @@ pub fn encodeHighLevel( )?; } Compaction::NUMERIC => { - sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::PARSE)?); encodeNumeric(&input, p, len as u32, &mut sb)?; } _ => { @@ -252,7 +252,7 @@ pub fn encodeHighLevel( } let n = determineConsecutiveDigitCount(&input, p)?; if n >= 13 { - sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::PARSE)?); encodingMode = NUMERIC_COMPACTION; textSubMode = SUBMODE_ALPHA; //Reset after latch encodeNumeric(&input, p, n, &mut sb)?; @@ -261,7 +261,7 @@ pub fn encodeHighLevel( let t = determineConsecutiveTextCount(&input, p)?; if t >= 5 || n == len as u32 { if encodingMode != TEXT_COMPACTION { - sb.push(char::from_u32(LATCH_TO_TEXT).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(LATCH_TO_TEXT).ok_or(Exceptions::PARSE)?); encodingMode = TEXT_COMPACTION; textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch } @@ -285,7 +285,7 @@ pub fn encodeHighLevel( .collect::(); if let Ok(enc_str) = encoding .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .encode(&str, encoding::EncoderTrap::Strict) { Some(enc_str) @@ -301,7 +301,7 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, 1, TEXT_COMPACTION, &mut sb)?; } else { encodeBinary( - bytes.as_ref().ok_or(Exceptions::illegalState)?, + bytes.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?, 0, 1, TEXT_COMPACTION, @@ -314,9 +314,9 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, p + b, encodingMode, &mut sb)?; } else { encodeBinary( - bytes.as_ref().ok_or(Exceptions::illegalState)?, + bytes.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?, 0, - bytes.as_ref().ok_or(Exceptions::illegalState)?.len() as u32, + bytes.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?.len() as u32, encodingMode, &mut sb, )?; @@ -367,7 +367,7 @@ fn encodeText( if ch == ' ' { tmp.push(26 as char); //space } else { - tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::parse)?); + tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::PARSE)?); } } else if isAlphaLower(ch) { submode = SUBMODE_LOWER; @@ -381,7 +381,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } } @@ -391,11 +391,11 @@ fn encodeText( if ch == ' ' { tmp.push(26 as char); //space } else { - tmp.push(char::from_u32(ch as u32 - 97).ok_or(Exceptions::parse)?); + tmp.push(char::from_u32(ch as u32 - 97).ok_or(Exceptions::PARSE)?); } } else if isAlphaUpper(ch) { tmp.push(27 as char); //as - tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::parse)?); + tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::PARSE)?); //space cannot happen here, it is also in "Lower" } else if isMixed(ch) { submode = SUBMODE_MIXED; @@ -405,7 +405,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } } @@ -413,7 +413,7 @@ fn encodeText( SUBMODE_MIXED => { if isMixed(ch) { tmp.push( - char::from_u32(MIXED[ch as usize] as u32).ok_or(Exceptions::parse)?, + char::from_u32(MIXED[ch as usize] as u32).ok_or(Exceptions::PARSE)?, ); } else if isAlphaUpper(ch) { submode = SUBMODE_ALPHA; @@ -435,7 +435,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } } @@ -445,7 +445,7 @@ fn encodeText( if isPunctuation(ch) { tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); } else { submode = SUBMODE_ALPHA; @@ -466,16 +466,16 @@ fn encodeText( let odd = (i % 2) != 0; if odd { h = char::from_u32( - (h as u32 * 30) + tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32, + (h as u32 * 30) + tmp.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32, ) - .ok_or(Exceptions::parse)?; + .ok_or(Exceptions::PARSE)?; sb.push(h); } else { - h = tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; + h = tmp.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; } } if (len % 2) != 0 { - sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::parse)?); + sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::PARSE)?); //ps } Ok(submode) @@ -563,11 +563,11 @@ fn encodeBinary( sb: &mut String, ) -> Result<()> { if count == 1 && startmode == TEXT_COMPACTION { - sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::PARSE)?); } else if (count % 6) == 0 { - sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::PARSE)?); } else { - sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::PARSE)?); } let mut idx = startpos; @@ -581,7 +581,7 @@ fn encodeBinary( t += bytes[idx as usize + i as usize] as i64; } for ch in &mut chars { - *ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::parse)?; + *ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::PARSE)?; t /= 900; } sb.push_str(&chars.into_iter().rev().collect::()); @@ -625,13 +625,13 @@ fn encodeNumeric( ); // let mut bigint: u128 = part.parse().map_err(|_| Exceptions::parseEmpty())?; let mut bigint = num::BigUint::from_str(&part) - .map_err(|e| Exceptions::parseWith(format!("issue parsing {part}: {e}")))?; // part.parse().map_err(|_| Exceptions::parseEmpty())?; + .map_err(|e| Exceptions::parse_with(format!("issue parsing {part}: {e}")))?; // part.parse().map_err(|_| Exceptions::parseEmpty())?; loop { tmp.push( char::from_u32((&bigint % &NUM900).try_into().map_err(|e| { - Exceptions::parseWith(format!("erorr converting {bigint} to u32: {e}")) + Exceptions::parse_with(format!("erorr converting {bigint} to u32: {e}")) })?) - .ok_or(Exceptions::parse)?, + .ok_or(Exceptions::PARSE)?, ); bigint /= &NUM900; @@ -777,10 +777,10 @@ fn determineConsecutiveBinaryCount( if !can_encode { if TypeId::of::() != TypeId::of::() { - return Err(Exceptions::illegalStateWith("expected NoECIInput type")); + return Err(Exceptions::illegal_state_with("expected NoECIInput type")); } let ch = input.charAt(idx)?; - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "Non-encodable character detected: {} (Unicode: {})", ch, ch as u32 ))); @@ -793,17 +793,17 @@ fn determineConsecutiveBinaryCount( fn encodingECI(eci: i32, sb: &mut String) -> Result<()> { if (0..900).contains(&eci) { - sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::parse)?); - sb.push(char::from_u32(eci as u32).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::PARSE)?); + sb.push(char::from_u32(eci as u32).ok_or(Exceptions::PARSE)?); } else if eci < 810900 { - sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::parse)?); - sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::parse)?); - sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::PARSE)?); + sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::PARSE)?); + sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::PARSE)?); } else if eci < 811800 { - sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::parse)?); - sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::parse)?); + sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::PARSE)?); + sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::PARSE)?); } else { - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "ECI number not in valid range from 0..811799, but was {eci}" ))); } @@ -820,7 +820,7 @@ impl ECIInput for NoECIInput { self.0 .chars() .nth(index) - .ok_or(Exceptions::indexOutOfBounds) + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS) } fn subSequence(&self, start: usize, end: usize) -> Result> { diff --git a/src/pdf417/pdf_417_reader.rs b/src/pdf417/pdf_417_reader.rs index c37d833..bb954cc 100644 --- a/src/pdf417/pdf_417_reader.rs +++ b/src/pdf417/pdf_417_reader.rs @@ -54,7 +54,7 @@ impl Reader for PDF417Reader { ) -> Result { let result = Self::decode(image, hints, false)?; if result.is_empty() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok(result[0].clone()) } @@ -124,7 +124,7 @@ impl PDF417Reader { pdf417RXingResultMetadata .clone() .downcast::() - .map_err(|_| Exceptions::illegalState)?, + .map_err(|_| Exceptions::ILLEGAL_STATE)?, ); result.putMetadata(RXingResultMetadataType::PDF417_EXTRA_METADATA, data); } diff --git a/src/pdf417/pdf_417_writer.rs b/src/pdf417/pdf_417_writer.rs index 1e13b2e..10c46db 100644 --- a/src/pdf417/pdf_417_writer.rs +++ b/src/pdf417/pdf_417_writer.rs @@ -60,7 +60,7 @@ impl Writer for PDF417Writer { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::PDF_417 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Can only encode PDF_417, but got {format}" ))); } @@ -150,7 +150,7 @@ impl PDF417Writer { let mut originalScale = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getScaledMatrix(1, aspectRatio); let mut rotated = false; if (height > width) != (originalScale[0].len() < originalScale.len()) { @@ -166,16 +166,16 @@ impl PDF417Writer { let mut scaledMatrix = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .getScaledMatrix(scale, scale * aspectRatio); if rotated { scaledMatrix = Self::rotateArray(&scaledMatrix); } return Self::bitMatrixFromBitArray(&scaledMatrix, margin) - .ok_or(Exceptions::illegalState); + .ok_or(Exceptions::ILLEGAL_STATE); } - Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::illegalState) + Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::ILLEGAL_STATE) } /** diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index a3a6d4f..adeb526 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -167,7 +167,7 @@ impl PlanarYUVLuminanceSource { inverted: bool, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Crop rectangle does not fit within image data.", )); } @@ -329,7 +329,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { self.invert, ) { Ok(new) => Ok(Box::new(new)), - Err(_err) => Err(Exceptions::unsupportedOperation), + Err(_err) => Err(Exceptions::UNSUPPORTED_OPERATION), } } diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index 8ef056c..9b148ec 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -39,7 +39,7 @@ impl BitMatrixParser { pub fn new(bit_matrix: BitMatrix) -> Result { let dimension = bit_matrix.getHeight(); if dimension < 21 || (dimension & 0x03) != 1 { - Err(Exceptions::formatWith(format!( + Err(Exceptions::format_with(format!( "{dimension} < 21 || ({dimension} % 0x03) != 1" ))) } else { @@ -61,7 +61,7 @@ impl BitMatrixParser { */ pub fn readFormatInformation(&mut self) -> Result<&FormatInformation> { if self.parsedFormatInfo.is_some() { - return self.parsedFormatInfo.as_ref().ok_or(Exceptions::parse); + return self.parsedFormatInfo.as_ref().ok_or(Exceptions::PARSE); } // Read top-left format info bits @@ -92,7 +92,7 @@ impl BitMatrixParser { self.parsedFormatInfo = FormatInformation::decodeFormatInformation(formatInfoBits1, formatInfoBits2); - self.parsedFormatInfo.as_ref().ok_or(Exceptions::format) + self.parsedFormatInfo.as_ref().ok_or(Exceptions::FORMAT) } /** @@ -144,7 +144,7 @@ impl BitMatrixParser { return Ok(theParsedVersion); } } - Err(Exceptions::format) + Err(Exceptions::FORMAT) } fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 { @@ -225,7 +225,7 @@ impl BitMatrixParser { } if resultOffset != version.getTotalCodewords() as usize { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } Ok(result) } diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index d3f3026..b9b6798 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -56,7 +56,7 @@ impl DataBlock { ecLevel: ErrorCorrectionLevel, ) -> Result> { if rawCodewords.len() as u32 != version.getTotalCodewords() { - return Err(Exceptions::illegalArgument); + return Err(Exceptions::ILLEGAL_ARGUMENT); } // Figure out the number and size of data blocks used by this version and diff --git a/src/qrcode/decoder/data_mask.rs b/src/qrcode/decoder/data_mask.rs index 6d8a284..0fb9173 100755 --- a/src/qrcode/decoder/data_mask.rs +++ b/src/qrcode/decoder/data_mask.rs @@ -228,7 +228,7 @@ impl TryFrom for DataMask { 5 => Ok(DataMask::DATA_MASK_101), 6 => Ok(DataMask::DATA_MASK_110), 7 => Ok(DataMask::DATA_MASK_111), - _ => Err(Exceptions::illegalArgumentWith(format!( + _ => Err(Exceptions::illegal_argument_with(format!( "{value} is not between 0 and 7" ))), } diff --git a/src/qrcode/decoder/decoded_bit_stream_parser.rs b/src/qrcode/decoder/decoded_bit_stream_parser.rs index 1e5302e..225e0ca 100644 --- a/src/qrcode/decoder/decoded_bit_stream_parser.rs +++ b/src/qrcode/decoder/decoded_bit_stream_parser.rs @@ -78,7 +78,7 @@ pub fn decode( } Mode::STRUCTURED_APPEND => { if bits.available() < 16 { - return Err(Exceptions::formatWith(format!( + return Err(Exceptions::format_with(format!( "Mode::Structured append expected bits.available() < 16, found bits of {}", bits.available() ))); @@ -93,7 +93,7 @@ pub fn decode( let value = parseECIValue(&mut bits)?; currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value).ok(); if currentCharacterSetECI.is_none() { - return Err(Exceptions::formatWith(format!( + return Err(Exceptions::format_with(format!( "Value of {value} not valid" ))); } @@ -132,7 +132,7 @@ pub fn decode( currentCharacterSetECI, hints, )?, - _ => return Err(Exceptions::format), + _ => return Err(Exceptions::FORMAT), } } } @@ -177,7 +177,7 @@ pub fn decode( fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -> Result<()> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -204,10 +204,10 @@ fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) - } let gb_encoder = - encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalState)?; + encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::ILLEGAL_STATE)?; let encode_string = gb_encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?; + .map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); Ok(()) } @@ -221,7 +221,7 @@ fn decodeKanjiSegment( ) -> Result<()> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -250,7 +250,7 @@ fn decodeKanjiSegment( let encoder = { let _ = currentCharacterSetECI; let _ = hints; - encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::FORMAT)? }; #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -263,12 +263,12 @@ fn decodeKanjiSegment( encoding::all::ISO_8859_1 } } else { - encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::FORMAT)? }; let encode_string = encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?; + .map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); @@ -285,7 +285,7 @@ fn decodeByteSegment( ) -> Result<()> { // Don't crash trying to read more bits than we have available. if 8 * count > bits.available() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let mut readBytes = vec![0u8; count]; @@ -301,7 +301,7 @@ fn decodeByteSegment( // give a hint. { #[cfg(not(feature = "allow_forced_iso_ied_18004_compliance"))] - StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalState)? + StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::ILLEGAL_STATE)? } #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -316,14 +316,14 @@ fn decodeByteSegment( CharacterSetECI::getCharset( currentCharacterSetECI .as_ref() - .ok_or(Exceptions::illegalState)?, + .ok_or(Exceptions::ILLEGAL_STATE)?, ) }; let encode_string = if currentCharacterSetECI.is_some() && currentCharacterSetECI .as_ref() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? == &CharacterSetECI::Cp437 { { @@ -336,7 +336,7 @@ fn decodeByteSegment( encoding .decode(&readBytes, encoding::DecoderTrap::Strict) .map_err(|e| { - Exceptions::parseWith(format!("unable to decode buffer {readBytes:?}: {e}")) + Exceptions::parse_with(format!("unable to decode buffer {readBytes:?}: {e}")) })? }; @@ -348,13 +348,13 @@ fn decodeByteSegment( fn toAlphaNumericChar(value: u32) -> Result { if value as usize >= ALPHANUMERIC_CHARS.len() { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } ALPHANUMERIC_CHARS .chars() .nth(value as usize) - .ok_or(Exceptions::format) + .ok_or(Exceptions::FORMAT) } fn decodeAlphanumericSegment( @@ -368,7 +368,7 @@ fn decodeAlphanumericSegment( let mut count = count; while count > 1 { if bits.available() < 11 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let nextTwoCharsBits = bits.readBits(11)?; result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?); @@ -378,7 +378,7 @@ fn decodeAlphanumericSegment( if count == 1 { // special case: one character left if bits.available() < 6 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } result.push(toAlphaNumericChar(bits.readBits(6)?)?); } @@ -386,12 +386,12 @@ fn decodeAlphanumericSegment( if fc1InEffect { // We need to massage the result a bit if in an FNC1 mode: for i in start..result.len() { - if result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? == '%' { + if result.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == '%' { if i < result.len() - 1 && result .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)? + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == '%' { // %% is rendered as % @@ -413,11 +413,11 @@ fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize) while count >= 3 { // Each 10 bits encodes three digits if bits.available() < 10 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let threeDigitsBits = bits.readBits(10)?; if threeDigitsBits >= 1000 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } result.push(toAlphaNumericChar(threeDigitsBits / 100)?); result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?); @@ -427,22 +427,22 @@ fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize) if count == 2 { // Two digits left over to read, encoded in 7 bits if bits.available() < 7 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let twoDigitsBits = bits.readBits(7)?; if twoDigitsBits >= 100 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } result.push(toAlphaNumericChar(twoDigitsBits / 10)?); result.push(toAlphaNumericChar(twoDigitsBits % 10)?); } else if count == 1 { // One digit left over to read if bits.available() < 4 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } let digitBits = bits.readBits(4)?; if digitBits >= 10 { - return Err(Exceptions::format); + return Err(Exceptions::FORMAT); } result.push(toAlphaNumericChar(digitBits)?); } @@ -467,5 +467,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result { return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes); } - Err(Exceptions::format) + Err(Exceptions::FORMAT) } diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index a8f4d56..9b61495 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -48,7 +48,7 @@ impl ErrorCorrectionLevel { 1 => Ok(Self::L), 2 => Ok(Self::H), 3 => Ok(Self::Q), - _ => Err(Exceptions::illegalArgumentWith(format!( + _ => Err(Exceptions::illegal_argument_with(format!( "{bits} is not a valid bit selection" ))), } @@ -110,7 +110,7 @@ impl FromStr for ErrorCorrectionLevel { return number_possible.try_into(); } - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "could not parse {s} into an ec level" ))); } diff --git a/src/qrcode/decoder/mode.rs b/src/qrcode/decoder/mode.rs index 99b5f8c..ab726f1 100644 --- a/src/qrcode/decoder/mode.rs +++ b/src/qrcode/decoder/mode.rs @@ -69,7 +69,7 @@ impl Mode { { Ok(Self::HANZI) } - _ => Err(Exceptions::illegalArgumentWith(format!( + _ => Err(Exceptions::illegal_argument_with(format!( "{bits} is not valid" ))), } diff --git a/src/qrcode/decoder/qrcode_decoder.rs b/src/qrcode/decoder/qrcode_decoder.rs index 1c6aea1..5ed9131 100644 --- a/src/qrcode/decoder/qrcode_decoder.rs +++ b/src/qrcode/decoder/qrcode_decoder.rs @@ -129,7 +129,7 @@ pub fn decode_bitmatrix_with_hints( if let Some(fe) = fe { Err(fe) } else { - Err(ce.unwrap_or(Exceptions::checksum)) + Err(ce.unwrap_or(Exceptions::CHECKSUM)) } } _ => Err(er), diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index f1954c3..8ca060b 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -102,14 +102,14 @@ impl Version { */ pub fn getProvisionalVersionForDimension(dimension: u32) -> Result<&'static Version> { if dimension % 4 != 1 { - return Err(Exceptions::formatWith("dimension incorrect")); + return Err(Exceptions::format_with("dimension incorrect")); } Self::getVersionForNumber((dimension - 17) / 4) } pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version> { if !(1..=40).contains(&versionNumber) { - return Err(Exceptions::illegalArgumentWith("version out of spec")); + return Err(Exceptions::illegal_argument_with("version out of spec")); } Ok(&VERSIONS[versionNumber as usize - 1]) } @@ -137,7 +137,7 @@ impl Version { return Self::getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } /** diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index 1197f8d..5b252c7 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -164,9 +164,9 @@ impl AlignmentPatternFinder { Ok(*(self .possibleCenters .get(0) - .ok_or(Exceptions::indexOutOfBounds))?) + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS))?) } else { - Err(Exceptions::notFound) + Err(Exceptions::NOT_FOUND) } } diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 53df7d8..eeeaca4 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -695,7 +695,7 @@ impl<'a> FinderPatternFinder<'_> { let startSize = self.possibleCenters.len(); if startSize < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } self.possibleCenters @@ -712,19 +712,19 @@ impl<'a> FinderPatternFinder<'_> { for i in 0..self.possibleCenters.len() { let Some(fpi) = self.possibleCenters.get(i) else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; let minModuleSize = fpi.getEstimatedModuleSize(); for j in (i + 1)..(self.possibleCenters.len() - 1) { let Some(fpj) = self.possibleCenters.get(j) else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; let squares0 = Self::squaredDistance(fpi, fpj); for k in (j + 1)..(self.possibleCenters.len()) { let Some(fpk) = self.possibleCenters.get(k) else { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); }; let maxModuleSize = fpk.getEstimatedModuleSize(); if maxModuleSize > minModuleSize * 1.4 { @@ -776,16 +776,16 @@ impl<'a> FinderPatternFinder<'_> { } if distortion == f64::MAX { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if bestPatterns[0].is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } - let p1 = bestPatterns[0].ok_or(Exceptions::notFound)?; - let p2 = bestPatterns[1].ok_or(Exceptions::notFound)?; - let p3 = bestPatterns[2].ok_or(Exceptions::notFound)?; + let p1 = bestPatterns[0].ok_or(Exceptions::NOT_FOUND)?; + let p2 = bestPatterns[1].ok_or(Exceptions::NOT_FOUND)?; + let p3 = bestPatterns[2].ok_or(Exceptions::NOT_FOUND)?; Ok([p1, p2, p3]) } diff --git a/src/qrcode/detector/qrcode_detector.rs b/src/qrcode/detector/qrcode_detector.rs index af84bfc..1d61e57 100644 --- a/src/qrcode/detector/qrcode_detector.rs +++ b/src/qrcode/detector/qrcode_detector.rs @@ -103,7 +103,7 @@ impl<'a> Detector<'_> { let moduleSize = self.calculateModuleSize(topLeft, topRight, bottomLeft); if moduleSize < 1.0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let dimension = Self::computeDimension(topLeft, topRight, bottomLeft, moduleSize)?; let provisionalVersion = Version::getProvisionalVersionForDimension(dimension)?; @@ -145,7 +145,7 @@ impl<'a> Detector<'_> { alignmentPattern.as_ref(), dimension, ) - .ok_or(Exceptions::notFound)?; + .ok_or(Exceptions::NOT_FOUND)?; let bits = Detector::sampleGrid(self.image, &transform, dimension)?; @@ -156,7 +156,7 @@ impl<'a> Detector<'_> { ]; if alignmentPattern.is_some() { - points.push(alignmentPattern.ok_or(Exceptions::notFound)?.into()) + points.push(alignmentPattern.ok_or(Exceptions::NOT_FOUND)?.into()) } Ok(QRCodeDetectorResult::new(bits, points)) @@ -240,7 +240,7 @@ impl<'a> Detector<'_> { match dimension & 0x03 { 0 => dimension += 1, 2 => dimension -= 1, - 3 => return Err(Exceptions::notFound), + 3 => return Err(Exceptions::NOT_FOUND), _ => {} } Ok(dimension as u32) @@ -436,13 +436,13 @@ impl<'a> Detector<'_> { let alignmentAreaLeftX = 0.max(estAlignmentX as i32 - allowance as i32) as u32; let alignmentAreaRightX = (self.image.getWidth() - 1).min(estAlignmentX + allowance); if ((alignmentAreaRightX - alignmentAreaLeftX) as f32) < overallEstModuleSize * 3.0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let alignmentAreaTopY = 0.max(estAlignmentY as i32 - allowance as i32) as u32; let alignmentAreaBottomY = (self.image.getHeight() - 1).min(estAlignmentY + allowance); if alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize as u32 * 3 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } let mut alignmentFinder = AlignmentPatternFinder::new( diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index 7b0fac9..c037859 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -175,7 +175,7 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result { ((temp % 3) + ((y + x) & 0x1)) & 0x1 } _ => { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "Invalid mask pattern: {maskPattern}" ))) } diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index f5d3495..ab68171 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -274,7 +274,7 @@ pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMat } // All bits should be consumed. if bitIndex != dataBits.getSize() { - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "Not all bits consumed: {}/{}", bitIndex, dataBits.getSize() @@ -319,7 +319,7 @@ pub fn findMSBSet(value: u32) -> u32 { // operations. We don't care if coefficients are positive or negative. pub fn calculateBCHCode(value: u32, poly: u32) -> Result { if poly == 0 { - return Err(Exceptions::illegalArgumentWith("0 polynomial")); + return Err(Exceptions::illegal_argument_with("0 polynomial")); } let mut value = value; // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 @@ -343,7 +343,7 @@ pub fn makeTypeInfoBits( bits: &mut BitArray, ) -> Result<()> { if !QRCode::isValidMaskPattern(maskPattern as i32) { - return Err(Exceptions::writerWith("Invalid mask pattern")); + return Err(Exceptions::writer_with("Invalid mask pattern")); } let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern; bits.appendBits(typeInfo, 5)?; @@ -357,7 +357,7 @@ pub fn makeTypeInfoBits( if bits.getSize() != 15 { // Just in case. - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "should not happen but we got: {}", bits.getSize() ))); @@ -374,7 +374,7 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()> if bits.getSize() != 18 { // Just in case. - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "should not happen but we got: {}", bits.getSize() ))); @@ -407,7 +407,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) { // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<()> { if matrix.get(8, matrix.getHeight() - 8) == 0 { - return Err(Exceptions::writer); + return Err(Exceptions::WRITER); } matrix.set(8, matrix.getHeight() - 8, 1); Ok(()) @@ -420,7 +420,7 @@ pub fn embedHorizontalSeparationPattern( ) -> Result<()> { for x in 0..8 { if !isEmpty(matrix.get(xStart + x, yStart)) { - return Err(Exceptions::writer); + return Err(Exceptions::WRITER); } matrix.set(xStart + x, yStart, 0); } @@ -434,7 +434,7 @@ pub fn embedVerticalSeparationPattern( ) -> Result<()> { for y in 0..7 { if !isEmpty(matrix.get(xStart, yStart + y)) { - return Err(Exceptions::writer); + return Err(Exceptions::WRITER); } matrix.set(xStart, yStart + y, 0); } diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index 4a1d11c..6de4413 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -158,7 +158,7 @@ impl MinimalEncoder { Self::getVersion(Self::getVersionSize(result.getVersion()))?, &self.ecLevel, ) { - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "Data too big for version {version}" ))); } @@ -186,7 +186,7 @@ impl MinimalEncoder { } } if smallestRXingResult < 0 { - return Err(Exceptions::writerWith("Data too big for any version")); + return Err(Exceptions::writer_with("Data too big for any version")); } Ok(results[smallestRXingResult as usize].clone()) } @@ -247,7 +247,7 @@ impl MinimalEncoder { Some(Mode::ALPHANUMERIC) => Ok(1), Some(Mode::BYTE) => Ok(3), Some(Mode::KANJI) | None => Ok(0), - _ => Err(Exceptions::illegalArgumentWith(format!( + _ => Err(Exceptions::illegal_argument_with(format!( "Illegal mode {mode:?}" ))), } @@ -262,21 +262,21 @@ impl MinimalEncoder { let vertexIndex = position + edge .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::FORMAT)? .characterLength as usize; let modeEdges = &mut edges[vertexIndex][edge .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::FORMAT)? .charsetEncoderIndex]; let modeOrdinal = Self::getCompactedOrdinal(Some( - edge.as_ref().ok_or(Exceptions::FormatException(None))?.mode, + edge.as_ref().ok_or(Exceptions::FORMAT)?.mode, ))? as usize; if modeEdges[modeOrdinal].is_none() || modeEdges[modeOrdinal] .as_ref() - .ok_or(Exceptions::format)? + .ok_or(Exceptions::FORMAT)? .cachedTotalSize - > edge.as_ref().ok_or(Exceptions::format)?.cachedTotalSize + > edge.as_ref().ok_or(Exceptions::FORMAT)?.cachedTotalSize { modeEdges[modeOrdinal] = edge; } @@ -299,12 +299,12 @@ impl MinimalEncoder { .encoders .canEncode( &self.stringToEncode[from], - priorityEncoderIndex.ok_or(Exceptions::format)?, + priorityEncoderIndex.ok_or(Exceptions::FORMAT)?, ) - .ok_or(Exceptions::format)? + .ok_or(Exceptions::FORMAT)? { - start = priorityEncoderIndex.ok_or(Exceptions::format)?; - end = priorityEncoderIndex.ok_or(Exceptions::format)? + 1; + start = priorityEncoderIndex.ok_or(Exceptions::FORMAT)?; + end = priorityEncoderIndex.ok_or(Exceptions::FORMAT)? + 1; } for i in start..end { @@ -313,10 +313,10 @@ impl MinimalEncoder { .canEncode( self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, i, ) - .ok_or(Exceptions::format)? + .ok_or(Exceptions::FORMAT)? { self.addEdge( edges, @@ -332,7 +332,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writer)?, + .ok_or(Exceptions::WRITER)?, )), )?; } @@ -340,7 +340,7 @@ impl MinimalEncoder { if self.canEncode( &Mode::KANJI, - self.stringToEncode.get(from).ok_or(Exceptions::format)?, + self.stringToEncode.get(from).ok_or(Exceptions::FORMAT)?, ) { self.addEdge( edges, @@ -356,7 +356,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writer)?, + .ok_or(Exceptions::WRITER)?, )), )?; } @@ -366,7 +366,7 @@ impl MinimalEncoder { &Mode::ALPHANUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { self.addEdge( edges, @@ -378,10 +378,10 @@ impl MinimalEncoder { 0, if from + 1 >= inputLength || !self.canEncode( - &Mode::ALPHANUMERIC, - self.stringToEncode + &Mode::ALPHANUMERIC, + self.stringToEncode .get(from + 1) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { 1 @@ -393,7 +393,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writer)?, + .ok_or(Exceptions::WRITER)?, )), )?; } @@ -402,7 +402,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { self.addEdge( edges, @@ -414,19 +414,19 @@ impl MinimalEncoder { 0, if from + 1 >= inputLength || !self.canEncode( - &Mode::NUMERIC, - self.stringToEncode + &Mode::NUMERIC, + self.stringToEncode .get(from + 1) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { 1 } else if from + 2 >= inputLength || !self.canEncode( - &Mode::NUMERIC, - self.stringToEncode + &Mode::NUMERIC, + self.stringToEncode .get(from + 2) - .ok_or(Exceptions::indexOutOfBounds)?, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, ) { 2 @@ -438,7 +438,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writer)?, + .ok_or(Exceptions::WRITER)?, )), )?; } @@ -598,16 +598,16 @@ impl MinimalEncoder { version, edges[inputLength][minJ][minK] .as_ref() - .ok_or(Exceptions::writer)? + .ok_or(Exceptions::WRITER)? .clone(), self.isGS1, &self.ecLevel, self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writer)?) + .ok_or(Exceptions::WRITER)?) } else { - Err(Exceptions::writerWith(format!( + Err(Exceptions::writer_with(format!( r#"Internal error: failed to encode "{}"#, self.stringToEncode .iter() @@ -1023,7 +1023,7 @@ impl RXingResultNode { bits, self.encoders .getCharset(self.charsetEncoderIndex) - .ok_or(Exceptions::writer)?, + .ok_or(Exceptions::WRITER)?, )?; } Ok(()) diff --git a/src/qrcode/encoder/qrcode_encoder.rs b/src/qrcode/encoder/qrcode_encoder.rs index 4c9aa01..82a7dfb 100644 --- a/src/qrcode/encoder/qrcode_encoder.rs +++ b/src/qrcode/encoder/qrcode_encoder.rs @@ -101,7 +101,7 @@ pub fn encode_with_hints( if has_encoding_hint { if let Some(EncodeHintValue::CharacterSet(v)) = hints.get(&EncodeHintType::CHARACTER_SET) { encoding = - Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writer)?) + Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::WRITER)?) } } @@ -179,7 +179,7 @@ pub fn encode_with_hints( version = Version::getVersionForNumber(versionNumber)?; let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version); if !willFit(bitsNeeded, version, &ec_level) { - return Err(Exceptions::writerWith("Data too big for requested version")); + return Err(Exceptions::writer_with("Data too big for requested version")); } } else { version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?; @@ -384,7 +384,7 @@ fn chooseVersion(numInputBits: u32, ecLevel: &ErrorCorrectionLevel) -> Result Result<()> { let capacity = num_data_bytes * 8; if bits.getSize() > capacity as usize { - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "data bits cannot fit in the QR Code{capacity} > " ))); } @@ -440,7 +440,7 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<()> { bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?; } if bits.getSize() != capacity as usize { - return Err(Exceptions::writerWith("Bits size does not equal capacity")); + return Err(Exceptions::writer_with("Bits size does not equal capacity")); } Ok(()) } @@ -459,7 +459,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // numECBytesInBlock: &mut [u32], ) -> Result<(u32, u32)> { if block_id >= num_rsblocks { - return Err(Exceptions::writerWith("Block ID too large")); + return Err(Exceptions::writer_with("Block ID too large")); } // numRsBlocksInGroup2 = 196 % 5 = 1 let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks; @@ -480,18 +480,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // Sanity checks. // 26 = 26 if num_ec_bytes_in_group1 != numEcBytesInGroup2 { - return Err(Exceptions::writerWith("EC bytes mismatch")); + return Err(Exceptions::writer_with("EC bytes mismatch")); } // 5 = 4 + 1. if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 { - return Err(Exceptions::writerWith("RS blocks mismatch")); + return Err(Exceptions::writer_with("RS blocks mismatch")); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if num_total_bytes != ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) * num_rs_blocks_in_group1) + ((num_data_bytes_in_group2 + numEcBytesInGroup2) * num_rs_blocks_in_group2) { - return Err(Exceptions::writerWith("total bytes mismatch")); + return Err(Exceptions::writer_with("total bytes mismatch")); } Ok(if block_id < num_rs_blocks_in_group1 { @@ -513,7 +513,7 @@ pub fn interleaveWithECBytes( ) -> Result { // "bits" must have "getNumDataBytes" bytes of data. if bits.getSizeInBytes() as u32 != num_data_bytes { - return Err(Exceptions::writerWith( + return Err(Exceptions::writer_with( "Number of bits and data bytes does not match", )); } @@ -548,7 +548,7 @@ pub fn interleaveWithECBytes( data_bytes_offset += numDataBytesInBlock as usize; } if num_data_bytes != data_bytes_offset as u32 { - return Err(Exceptions::writerWith("Data bytes does not match offset")); + return Err(Exceptions::writer_with("Data bytes does not match offset")); } let mut result = BitArray::new(); @@ -573,7 +573,7 @@ pub fn interleaveWithECBytes( } if num_total_bytes != result.getSizeInBytes() as u32 { // Should be same. - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "Interleaving error: {} and {} differ.", num_total_bytes, result.getSizeInBytes() @@ -620,7 +620,7 @@ pub fn appendLengthInfo( ) -> Result<()> { let numBits = mode.getCharacterCountBits(version); if num_letters >= (1 << numBits) { - return Err(Exceptions::writerWith(format!( + return Err(Exceptions::writer_with(format!( "{} is bigger than {}", num_letters, ((1 << numBits) - 1) @@ -643,7 +643,7 @@ pub fn appendBytes( Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits), Mode::BYTE => append8BitBytes(content, bits, encoding), Mode::KANJI => appendKanjiBytes(content, bits), - _ => Err(Exceptions::writerWith(format!("Invalid mode: {mode:?}"))), + _ => Err(Exceptions::writer_with(format!("Invalid mode: {mode:?}"))), } } @@ -651,18 +651,18 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> { let length = content.len(); let mut i = 0; while i < length { - let num1 = content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u8 - b'0'; + let num1 = content.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8 - b'0'; if i + 2 < length { // Encode three numeric letters in ten bits. let num2 = content .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)? as u8 + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8 - b'0'; let num3 = content .chars() .nth(i + 2) - .ok_or(Exceptions::indexOutOfBounds)? as u8 + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8 - b'0'; bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?; i += 3; @@ -671,7 +671,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> { let num2 = content .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)? as u8 + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8 - b'0'; bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?; i += 2; @@ -689,19 +689,19 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()> let mut i = 0; while i < length { let code1 = - getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32); + getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32); if code1 == -1 { - return Err(Exceptions::writer); + return Err(Exceptions::WRITER); } if i + 1 < length { let code2 = getAlphanumericCode( content .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBounds)? as u32, + .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32, ); if code2 == -1 { - return Err(Exceptions::writer); + return Err(Exceptions::WRITER); } // Encode two alphanumeric letters in 11 bits. bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?; @@ -718,7 +718,7 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()> pub fn append8BitBytes(content: &str, bits: &mut BitArray, encoding: EncodingRef) -> Result<()> { let bytes = encoding .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::writerWith(format!("error {e}")))?; + .map_err(|e| Exceptions::writer_with(format!("error {e}")))?; for b in bytes { bits.appendBits(b as u32, 8)?; } @@ -730,9 +730,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> { let bytes = sjis .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::writerWith(format!("error {e}")))?; + .map_err(|e| Exceptions::writer_with(format!("error {e}")))?; if bytes.len() % 2 != 0 { - return Err(Exceptions::writerWith("Kanji byte size not even")); + return Err(Exceptions::writer_with("Kanji byte size not even")); } let max_i = bytes.len() - 1; // bytes.length must be even let mut i = 0; @@ -747,7 +747,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> { subtracted = code as i32 - 0xc140; } if subtracted == -1 { - return Err(Exceptions::writerWith("Invalid byte sequence")); + return Err(Exceptions::writer_with("Invalid byte sequence")); } let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded as u32, 13)?; diff --git a/src/qrcode/qr_code_reader.rs b/src/qrcode/qr_code_reader.rs index b268518..c123b97 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -80,7 +80,7 @@ impl Reader for QRCodeReader { // if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) { other .downcast_ref::() - .ok_or(Exceptions::illegalState)? + .ok_or(Exceptions::ILLEGAL_STATE)? .applyMirroredCorrection(&mut points); } } @@ -150,11 +150,11 @@ impl QRCodeReader { let leftTopBlack = image.getTopLeftOnBit(); let rightBottomBlack = image.getBottomRightOnBit(); if leftTopBlack.is_none() || rightBottomBlack.is_none() { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } - let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBounds)?; - let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBounds)?; + let leftTopBlack = leftTopBlack.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; + let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -165,7 +165,7 @@ impl QRCodeReader { // Sanity check! if left >= right || top >= bottom { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if bottom - top != right - left { @@ -174,17 +174,17 @@ impl QRCodeReader { right = left + (bottom - top); if right >= image.getWidth() as i32 { // Abort if that would not make sense -- off image - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } } let matrixWidth = ((right as f32 - left as f32 + 1.0) / moduleSize).round() as u32; let matrixHeight = ((bottom as f32 - top as f32 + 1.0) / moduleSize).round() as u32; if matrixWidth == 0 || matrixHeight == 0 { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } if matrixHeight != matrixWidth { // Only possibly decode square regions - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } // Push in the "border" by half the module width so that we start @@ -202,7 +202,7 @@ impl QRCodeReader { if nudgedTooFarRight > 0 { if nudgedTooFarRight > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } left -= nudgedTooFarRight; } @@ -211,7 +211,7 @@ impl QRCodeReader { if nudgedTooFarDown > 0 { if nudgedTooFarDown > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } top -= nudgedTooFarDown; } @@ -248,7 +248,7 @@ impl QRCodeReader { y += 1; } if x == width || y == height { - return Err(Exceptions::notFound); + return Err(Exceptions::NOT_FOUND); } Ok((x - leftTopBlack[0]) as f32 / 7.0) } diff --git a/src/qrcode/qr_code_writer.rs b/src/qrcode/qr_code_writer.rs index 956bc63..5c3ea2f 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -59,18 +59,18 @@ impl Writer for QRCodeWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgumentWith("found empty contents")); + return Err(Exceptions::illegal_argument_with("found empty contents")); } if format != &BarcodeFormat::QR_CODE { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "can only encode QR_CODE, but got {format:?}" ))); // throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } if width < 0 || height < 0 { - return Err(Exceptions::illegalArgumentWith(format!( + return Err(Exceptions::illegal_argument_with(format!( "requested dimensions are too small: {width}x{height}" ))); } @@ -87,7 +87,7 @@ impl Writer for QRCodeWriter { if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) { margin .parse::() - .map_err(|e| Exceptions::parseWith(format!("could not parse {margin}: {e}")))? + .map_err(|e| Exceptions::parse_with(format!("could not parse {margin}: {e}")))? } else { QUIET_ZONE_SIZE }; @@ -109,10 +109,10 @@ impl QRCodeWriter { ) -> Result { let input = code.getMatrix(); if input.is_none() { - return Err(Exceptions::illegalStateWith("matrix is empty")); + return Err(Exceptions::illegal_state_with("matrix is empty")); } - let input = input.as_ref().ok_or(Exceptions::illegalState)?; + let input = input.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?; let inputWidth = input.getWidth() as i32; let inputHeight = input.getHeight() as i32; diff --git a/src/rgb_luminance_source.rs b/src/rgb_luminance_source.rs index 5f4be37..96747fe 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -128,7 +128,7 @@ impl LuminanceSource for RGBLuminanceSource { height, ) { Ok(crop) => Ok(Box::new(crop)), - Err(_error) => Err(Exceptions::unsupportedOperation), + Err(_error) => Err(Exceptions::UNSUPPORTED_OPERATION), } } @@ -180,7 +180,7 @@ impl RGBLuminanceSource { height: usize, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::illegalArgumentWith( + return Err(Exceptions::illegal_argument_with( "Crop rectangle does not fit within image data.", )); } diff --git a/src/svg_luminance_source.rs b/src/svg_luminance_source.rs index 74762b2..ee62471 100644 --- a/src/svg_luminance_source.rs +++ b/src/svg_luminance_source.rs @@ -57,11 +57,11 @@ impl SVGLuminanceSource { pub fn new(svg_data: &[u8]) -> Result { // Load the SVG file let Ok(tree) = resvg::usvg::Tree::from_data(svg_data, &Options::default()) else { - return Err(Exceptions::formatWith(format!("could not parse svg data: {}", "err"))); + return Err(Exceptions::format_with(format!("could not parse svg data: {}", "err"))); }; let Some(mut pixmap) = resvg::tiny_skia::Pixmap::new(tree.size.width() as u32, tree.size.height() as u32) else { - return Err(Exceptions::formatWith("could not create pixmap")); + return Err(Exceptions::format_with("could not create pixmap")); }; resvg::render( @@ -72,7 +72,7 @@ impl SVGLuminanceSource { ); let Some(buffer) = RgbaImage::from_raw(tree.size.width() as u32, tree.size.height() as u32, pixmap.data().to_vec()) else { - return Err(Exceptions::formatWith("could not create image buffer")); + return Err(Exceptions::format_with("could not create image buffer")); }; // let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else {