From 3e27279dc80533a1dcd79685b59bad89fa44924a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 07:47:20 +0000 Subject: [PATCH 1/6] add exception factories --- src/exceptions.rs | 106 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/src/exceptions.rs b/src/exceptions.rs index b0c4c30..6b613d5 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -22,6 +22,112 @@ pub enum Exceptions { ReaderDecodeException(), } +impl Exceptions { + pub fn illegalArgument>(x: I) -> Self { + Self::IllegalArgumentException(Some(x.into())) + } + + pub fn illegalArgumentEmpty() -> Self { + Self::IllegalArgumentException(None) + } + + pub fn unsupportedOperation>(x: I) -> Self { + Self::UnsupportedOperationException(Some(x.into())) + } + + pub fn unsupportedOperationEmpty() -> Self { + Self::UnsupportedOperationException(None) + } + + pub fn illegalState>(x: I) -> Self { + Self::IllegalStateException(Some(x.into())) + } + + pub fn illegalStateEmpty() -> Self { + Self::IllegalStateException(None) + } + + pub fn arithmetic>(x: I) -> Self { + Self::ArithmeticException(Some(x.into())) + } + + pub fn arithmeticEmpty() -> Self { + Self::ArithmeticException(None) + } + + pub fn notFound>(x: I) -> Self { + Self::NotFoundException(Some(x.into())) + } + + pub fn notFoundEmpty() -> Self { + Self::NotFoundException(None) + } + + pub fn format>(x: I) -> Self { + Self::FormatException(Some(x.into())) + } + + pub fn formatEmpty() -> Self { + Self::FormatException(None) + } + + pub fn checksum>(x: I) -> Self { + Self::ChecksumException(Some(x.into())) + } + + pub fn checksumEmpty() -> Self { + Self::ChecksumException(None) + } + + pub fn reader>(x: I) -> Self { + Self::ReaderException(Some(x.into())) + } + + pub fn readerEmpty() -> Self { + Self::ReaderException(None) + } + + pub fn writer>(x: I) -> Self { + Self::WriterException(Some(x.into())) + } + + pub fn writerEmpty() -> Self { + Self::WriterException(None) + } + + pub fn reedSolomon>(x: I) -> Self { + Self::ReedSolomonException(Some(x.into())) + } + + pub fn reedSolomonEmpty() -> Self { + Self::ReedSolomonException(None) + } + + pub fn indexOutOfBounds>(x: I) -> Self { + Self::IndexOutOfBoundsException(Some(x.into())) + } + + pub fn indexOutOfBoundsEmpty() -> Self { + Self::IndexOutOfBoundsException(None) + } + + pub fn runtime>(x: I) -> Self { + Self::RuntimeException(Some(x.into())) + } + + pub fn runtimeEmpty() -> Self { + Self::RuntimeException(None) + } + + pub fn parse>(x: I) -> Self { + Self::ParseException(Some(x.into())) + } + + pub fn parseEmpty() -> Self { + Self::ParseException(None) + } +} + impl fmt::Display for Exceptions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { From 722ce78fd0b0fbb13a809f6ce6d2913f809161db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 10:46:13 +0000 Subject: [PATCH 2/6] refactor to use exception helper factories --- src/aztec/aztec_reader.rs | 2 +- src/aztec/aztec_writer.rs | 6 +- src/aztec/decoder.rs | 33 ++--- src/aztec/detector.rs | 10 +- src/aztec/encoder/aztec_encoder.rs | 30 ++--- src/aztec/encoder/high_level_encoder.rs | 4 +- src/aztec/encoder/state.rs | 6 +- src/aztec/encoder/token.rs | 4 +- src/client/result/AddressBookParsedResult.rs | 12 +- src/client/result/CalendarParsedResult.rs | 28 ++--- src/client/result/ResultParser.rs | 4 +- src/client/result/VINResultParser.rs | 20 ++- src/common/bit_array.rs | 12 +- src/common/bit_matrix.rs | 36 +++--- src/common/bit_source.rs | 4 +- src/common/character_set_eci.rs | 4 +- src/common/default_grid_sampler.rs | 10 +- .../detector/monochrome_rectangle_detector.rs | 4 +- .../detector/white_rectangle_detector.rs | 12 +- src/common/global_histogram_binarizer.rs | 4 +- src/common/grid_sampler.rs | 4 +- src/common/minimal_eci_input.rs | 24 ++-- src/common/otsu_level_binarizer.rs | 2 +- src/common/reedsolomon/generic_gf.rs | 4 +- src/common/reedsolomon/generic_gf_poly.rs | 26 ++-- src/common/reedsolomon/reedsolomon_decoder.rs | 32 ++--- src/common/reedsolomon/reedsolomon_encoder.rs | 10 +- src/datamatrix/data_matrix_reader.rs | 12 +- src/datamatrix/data_matrix_writer.rs | 16 +-- src/datamatrix/decoder/bit_matrix_parser.rs | 8 +- src/datamatrix/decoder/data_block.rs | 2 +- .../decoder/decoded_bit_stream_parser.rs | 69 +++++----- src/datamatrix/decoder/version.rs | 4 +- .../detector/datamatrix_detector.rs | 4 +- .../zxing_cpp_detector/cpp_new_detector.rs | 4 +- .../zxing_cpp_detector/dm_regression_line.rs | 10 +- .../zxing_cpp_detector/edge_tracer.rs | 16 +-- .../detector/zxing_cpp_detector/util.rs | 2 +- src/datamatrix/encoder/ascii_encoder.rs | 12 +- src/datamatrix/encoder/base256_encoder.rs | 18 +-- src/datamatrix/encoder/c40_encoder.rs | 14 +-- src/datamatrix/encoder/default_placement.rs | 2 +- src/datamatrix/encoder/edifact_encoder.rs | 28 ++--- src/datamatrix/encoder/encoder_context.rs | 8 +- src/datamatrix/encoder/error_correction.rs | 20 +-- src/datamatrix/encoder/high_level_encoder.rs | 10 +- src/datamatrix/encoder/minimal_encoder.rs | 10 +- src/datamatrix/encoder/symbol_info.rs | 12 +- src/datamatrix/encoder/x12_encoder.rs | 2 +- src/helpers.rs | 39 +++--- src/luma_luma_source.rs | 4 +- src/luminance_source.rs | 12 +- .../decoder/decoded_bit_stream_parser.rs | 2 +- src/maxicode/decoder/maxicode_decoder.rs | 2 +- src/maxicode/detector.rs | 12 +- src/maxicode/maxi_code_reader.rs | 5 +- src/multi/generic_multiple_barcode_reader.rs | 2 +- src/multi/qrcode/detector/multi_detector.rs | 2 +- .../detector/multi_finder_pattern_finder.rs | 6 +- src/multi/qrcode/qr_code_multi_reader.rs | 2 +- src/multi_format_reader.rs | 2 +- src/multi_format_writer.rs | 4 +- src/oned/coda_bar_reader.rs | 28 ++--- src/oned/coda_bar_writer.rs | 22 ++-- src/oned/code_128_reader.rs | 20 ++- src/oned/code_128_writer.rs | 58 +++++---- src/oned/code_39_reader.rs | 46 +++---- src/oned/code_39_writer.rs | 32 ++--- src/oned/code_93_reader.rs | 58 ++++----- src/oned/code_93_writer.rs | 24 ++-- src/oned/ean_13_reader.rs | 10 +- src/oned/ean_13_writer.rs | 20 +-- src/oned/ean_8_reader.rs | 6 +- src/oned/ean_8_writer.rs | 18 ++- src/oned/itf_reader.rs | 20 ++- src/oned/itf_writer.rs | 16 +-- src/oned/multi_format_one_d_reader.rs | 4 +- src/oned/multi_format_upc_ean_reader.rs | 4 +- src/oned/one_d_code_writer.rs | 22 ++-- src/oned/one_d_reader.rs | 8 +- src/oned/rss/abstract_rss_reader.rs | 2 +- src/oned/rss/expanded/binary_util.rs | 18 +-- .../decoders/abstract_expanded_decoder.rs | 4 +- .../expanded/decoders/ai_01392x_decoder.rs | 2 +- .../expanded/decoders/ai_01393x_decoder.rs | 2 +- .../expanded/decoders/ai_013x0x1x_decoder.rs | 2 +- .../expanded/decoders/ai_013x0x_decoder.rs | 2 +- .../rss/expanded/decoders/decoded_numeric.rs | 2 +- .../rss/expanded/decoders/field_parser.rs | 12 +- .../decoders/general_app_id_decoder.rs | 20 ++- src/oned/rss/expanded/rss_expanded_reader.rs | 66 +++++----- src/oned/rss/rss_14_reader.rs | 30 ++--- src/oned/upc_a_reader.rs | 2 +- src/oned/upc_a_writer.rs | 4 +- src/oned/upc_e_reader.rs | 11 +- src/oned/upc_e_writer.rs | 28 ++--- src/oned/upc_ean_extension_2_support.rs | 13 +- src/oned/upc_ean_extension_5_support.rs | 11 +- src/oned/upc_ean_reader.rs | 40 +++--- src/pdf417/decoder/bounding_box.rs | 26 ++-- .../decoder/decoded_bit_stream_parser.rs | 34 +++-- src/pdf417/decoder/ec/error_correction.rs | 8 +- src/pdf417/decoder/ec/modulus_gf.rs | 4 +- src/pdf417/decoder/ec/modulus_poly.rs | 14 +-- .../decoder/pdf_417_scanning_decoder.rs | 22 ++-- src/pdf417/detector/pdf_417_detector.rs | 3 +- src/pdf417/encoder/compaction.rs | 4 +- src/pdf417/encoder/pdf_417.rs | 14 +-- .../encoder/pdf_417_error_correction.rs | 23 ++-- .../encoder/pdf_417_high_level_encoder.rs | 119 ++++++++---------- src/pdf417/pdf_417_reader.rs | 4 +- src/pdf417/pdf_417_writer.rs | 13 +- src/planar_yuv_luminance_source.rs | 6 +- src/qrcode/decoder/bit_matrix_parser.rs | 12 +- src/qrcode/decoder/data_block.rs | 2 +- src/qrcode/decoder/data_mask.rs | 4 +- .../decoder/decoded_bit_stream_parser.rs | 73 +++++------ src/qrcode/decoder/error_correction_level.rs | 8 +- src/qrcode/decoder/mode.rs | 4 +- src/qrcode/decoder/qrcode_decoder.rs | 2 +- src/qrcode/decoder/version.rs | 10 +- .../detector/alignment_pattern_finder.rs | 4 +- src/qrcode/detector/finder_pattern_finder.rs | 18 +-- src/qrcode/detector/qrcode_detector.rs | 12 +- src/qrcode/encoder/mask_util.rs | 4 +- src/qrcode/encoder/matrix_util.rs | 26 ++-- src/qrcode/encoder/minimal_encoder.rs | 68 +++++----- src/qrcode/encoder/qrcode_encoder.rs | 83 +++++------- src/qrcode/qr_code_reader.rs | 23 ++-- src/qrcode/qr_code_writer.rs | 26 ++-- src/rgb_luminance_source.rs | 6 +- src/svg_luminance_source.rs | 8 +- 132 files changed, 966 insertions(+), 1132 deletions(-) diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index 043b208..7c9ef34 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; let points = detectorRXingResult.getPoints(); diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index 0994120..f376561 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -59,7 +59,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::IllegalArgumentException(None))?, + .ok_or(Exceptions::illegalArgumentEmpty())?, ); } } @@ -95,9 +95,9 @@ fn encode( layers: i32, ) -> Result { if format != BarcodeFormat::AZTEC { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "can only encode AZTEC, but got {format:?}" - )))); + ))); } let aztec = if let Some(cset) = charset { // dbg!(cset.name(), cset.whatwg_name()); diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index 98d6af5..cb10079 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -164,16 +164,16 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { result.push_str( &encdr .decode(&decoded_bytes, encoding::DecoderTrap::Strict) - .map_err(|a| Exceptions::IllegalStateException(Some(a.to_string())))?, + .map_err(|a| Exceptions::illegalState(a.to_string()))?, ); decoded_bytes.clear(); match n { 0 => result.push(29 as char), // translate FNC1 as ASCII 29 7 => { - return Err(Exceptions::FormatException(Some( + return Err(Exceptions::format( "FLG(7) is reserved and illegal".to_owned(), - ))) + )) } // FLG(7) is reserved and illegal _ => { // ECI is decimal integer encoded as 1-6 codes in DIGIT mode @@ -186,18 +186,15 @@ 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::FormatException(Some( - "Not a decimal digit".to_owned(), - ))); // Not a decimal digit + return Err(Exceptions::format("Not a decimal digit".to_owned())); + // Not a decimal digit } eci = eci * 10 + (next_digit - 2); n -= 1; } let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); if charset_eci.is_err() { - return Err(Exceptions::FormatException(Some( - "Charset must exist".to_owned(), - ))); + return Err(Exceptions::format("Charset must exist".to_owned())); } encdr = CharacterSetECI::getCharset(&charset_eci?); } @@ -213,12 +210,12 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { shift_table = getTable( str.chars() .nth(5) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ); if str .chars() .nth(6) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? == 'L' { latch_table = shift_table; @@ -241,9 +238,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::IllegalStateException(Some( - "bad encoding".to_owned(), - ))); + return Err(Exceptions::illegalState("bad encoding".to_owned())); } // result.push_str(decodedBytes.toString(encoding.name())); //} catch (UnsupportedEncodingException uee) { @@ -295,9 +290,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { Table::Mixed => Ok(MIXED_TABLE[code as usize]), Table::Digit => Ok(DIGIT_TABLE[code as usize]), Table::Punct => Ok(PUNCT_TABLE[code as usize]), - _ => Err(Exceptions::IllegalStateException(Some( - "Bad table".to_owned(), - ))), + _ => Err(Exceptions::illegalState("Bad table".to_owned())), } // switch (table) { // case UPPER: @@ -358,9 +351,9 @@ fn correct_bits( let num_data_codewords = ddata.getNbDatablocks(); let num_codewords = rawbits.len() / codeword_size; if num_codewords < num_data_codewords as usize { - return Err(Exceptions::FormatException(Some(format!( + return Err(Exceptions::format(format!( "numCodewords {num_codewords}< numDataCodewords{num_data_codewords}" - )))); + ))); } let mut offset = rawbits.len() % codeword_size; @@ -391,7 +384,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); //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 007ea5d..aaedb29 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -127,9 +127,7 @@ impl<'a> Detector<'_> { || !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[3]) { - return Err(Exceptions::NotFoundException(Some( - "no valid points".to_owned(), - ))); + return Err(Exceptions::notFound("no valid points".to_owned())); } let length = 2 * self.nb_center_layers; // Get the bits around the bull's eye @@ -210,9 +208,7 @@ impl<'a> Detector<'_> { return Ok(shift); } } - Err(Exceptions::NotFoundException(Some( - "rotation failure".to_owned(), - ))) + Err(Exceptions::notFound("rotation failure".to_owned())) } /** @@ -324,7 +320,7 @@ impl<'a> Detector<'_> { } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } self.compact = self.nb_center_layers == 5; diff --git a/src/aztec/encoder/aztec_encoder.rs b/src/aztec/encoder/aztec_encoder.rs index e63d5ba..0d55196 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::IllegalArgumentException(Some(format!("'{data}' cannot be encoded as ISO_8859_1")))); + return Err(Exceptions::illegalArgument(format!("'{data}' cannot be encoded as ISO_8859_1"))); }; encode_bytes_simple(&bytes) } @@ -75,9 +75,9 @@ pub fn encode( if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) { encode_bytes(&bytes, minECCPercent, userSpecifiedLayers) } else { - Err(Exceptions::IllegalArgumentException(Some(format!( + Err(Exceptions::illegalArgument(format!( "'{data}' cannot be encoded as ISO_8859_1" - )))) + ))) } } @@ -102,9 +102,9 @@ 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::IllegalArgumentException(Some(format!( + Err(Exceptions::illegalArgument(format!( "'{data}' cannot be encoded as ISO_8859_1" - )))) + ))) } } @@ -178,24 +178,24 @@ pub fn encode_bytes_with_charset( MAX_NB_BITS }) { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Illegal value {user_specified_layers} for layers" - )))); + ))); } total_bits_in_layer_var = total_bits_in_layer(layers, compact); word_size = WORD_SIZE[layers as usize]; let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size); stuffed_bits = stuffBits(&bits, word_size as usize)?; if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Data to large for user specified layer".to_owned(), - ))); + )); } if compact && stuffed_bits.getSize() as u32 > word_size * 64 { // Compact format only allows 64 data words, though C4 can hold more words than that - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Data to large for user specified layer".to_owned(), - ))); + )); } } else { word_size = 0; @@ -207,9 +207,9 @@ pub fn encode_bytes_with_charset( loop { // for (int i = 0; ; i++) { if i > MAX_NB_BITS { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Data too large for an Aztec code".to_owned(), - ))); + )); } compact = i <= 3; layers = if compact { i + 1 } else { i }; @@ -482,9 +482,9 @@ fn getGF(wordSize: usize) -> Result { 8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)), 10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)), 12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)), - _ => Err(Exceptions::IllegalArgumentException(Some(format!( + _ => Err(Exceptions::illegalArgument(format!( "Unsupported word size {wordSize}" - )))), + ))), } } diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index feaf12c..cb59088 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -248,9 +248,9 @@ impl HighLevelEncoder { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "No ECI code for character set".to_owned(), - ))); + )); } // if self.charset != null { // CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset); diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index de84926..9834cc7 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -80,15 +80,15 @@ impl State { token.add(0, 3); // 0: FNC1 } else */ if eci > 999999 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "ECI code must be between 0 and 999999".to_owned(), - ))); + )); // throw new IllegalArgumentException("ECI code must be between 0 and 999999"); } else { let Ok(eci_digits) = encoding::all::ISO_8859_1 .encode(&format!("{eci}"), encoding::EncoderTrap::Strict) else { - return Err(Exceptions::IllegalArgumentException(None)) + return Err(Exceptions::illegalArgumentEmpty()) }; // 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 e798774..7437b8f 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -31,9 +31,9 @@ impl TokenType { match self { TokenType::Simple(a) => a.appendTo(bit_array, text), TokenType::BinaryShift(a) => a.appendTo(bit_array, text), - TokenType::Empty => Err(Exceptions::IllegalStateException(Some(String::from( + TokenType::Empty => Err(Exceptions::illegalState(String::from( "cannot appendTo on Empty final item", - )))), + ))), } } } diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index cfcaffe..b9e9418 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -120,19 +120,19 @@ impl AddressBookParsedRXingResult { geo: Vec, ) -> Result { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Phone numbers and types lengths differ".to_owned(), - ))); + )); } if emails.len() != email_types.len() && !email_types.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Emails and types lengths differ".to_owned(), - ))); + )); } if addresses.len() != address_types.len() && !address_types.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Addresses and types lengths differ".to_owned(), - ))); + )); } Ok(Self { names, diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index 5363b52..e782a78 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -166,7 +166,7 @@ impl CalendarParsedRXingResult { */ fn parseDate(when: String) -> Result { if !DATE_TIME.is_match(&when) { - return Err(Exceptions::ParseException(Some(when))); + return Err(Exceptions::parse(when)); } if when.len() == 8 { // Show only year/month/day @@ -177,7 +177,7 @@ 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::ParseException(Some(e.to_string()))), + Err(e) => Err(Exceptions::parse(e.to_string())), }; } // The when string can be local time, or UTC if it ends with a Z @@ -185,14 +185,12 @@ impl CalendarParsedRXingResult { && when .chars() .nth(15) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? == 'Z' { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") { Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()), - Err(e) => Err(Exceptions::ParseException(Some(format!( - "couldn't parse string: {e}" - )))), + Err(e) => Err(Exceptions::parse(format!("couldn't parse string: {e}"))), }; } // Try once more, with weird tz formatting @@ -202,16 +200,14 @@ impl CalendarParsedRXingResult { let tz_parsed: Tz = match tz_part.parse() { Ok(time_zone) => time_zone, Err(e) => { - return Err(Exceptions::ParseException(Some(format!( + return Err(Exceptions::parse(format!( "couldn't parse timezone '{tz_part}': {e}" - )))) + ))) } }; return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") { Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()), - Err(e) => Err(Exceptions::ParseException(Some(format!( - "couldn't parse string: {e}" - )))), + Err(e) => Err(Exceptions::parse(format!("couldn't parse string: {e}"))), }; } @@ -219,9 +215,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::ParseException(Some(format!( - "couldn't parse local time: {e}" - )))), + Err(e) => Err(Exceptions::parse(format!("couldn't parse local time: {e}"))), }; } Self::parseDateTimeString(&when) @@ -258,7 +252,7 @@ impl CalendarParsedRXingResult { let z = parseable .as_str() .parse::() - .map_err(|e| Exceptions::ParseException(Some(e.to_string())))?; + .map_err(|e| Exceptions::parse(e.to_string()))?; durationMS += unit * z; } } @@ -283,9 +277,9 @@ impl CalendarParsedRXingResult { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { Ok(dtm.timestamp()) } else { - Err(Exceptions::ParseException(Some(format!( + Err(Exceptions::parse(format!( "Couldn't parse {dateTimeString}" - )))) + ))) } // DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH); // return format.parse(dateTimeString).getTime(); diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index 26880da..f2525c4 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -300,9 +300,9 @@ pub fn urlDecode(encoded: &str) -> Result { if let Ok(decoded) = decode(encoded) { Ok(decoded.to_string()) } else { - Err(Exceptions::IllegalStateException(Some(String::from( + Err(Exceptions::illegalState(String::from( "UnsupportedEncodingException", - )))) + ))) } } diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index f35493d..41b0757 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -74,13 +74,13 @@ fn check_checksum(vin: &str) -> Result { * vin_char_value( vin.chars() .nth(i) - .ok_or(Exceptions::IllegalArgumentException(None))?, + .ok_or(Exceptions::illegalArgumentEmpty())?, )?; } let check_to_char = vin .chars() .nth(8) - .ok_or(Exceptions::IllegalArgumentException(None))?; + .ok_or(Exceptions::illegalArgumentEmpty())?; let expected_check_char = check_char((sum % 11) as u8)?; Ok(check_to_char == expected_check_char) } @@ -91,9 +91,9 @@ 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::IllegalArgumentException(Some( + _ => Err(Exceptions::illegalArgument( "vin char out of range".to_owned(), - ))), + )), } } @@ -103,9 +103,9 @@ fn vin_position_weight(position: usize) -> Result { 8 => Ok(10), 9 => Ok(0), 10..=17 => Ok(19 - position), - _ => Err(Exceptions::IllegalArgumentException(Some( + _ => Err(Exceptions::illegalArgument( "vin position weight out of bounds".to_owned(), - ))), + )), } } @@ -113,9 +113,7 @@ fn check_char(remainder: u8) -> Result { match remainder { 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), - _ => Err(Exceptions::IllegalArgumentException(Some( - "remainder too high".to_owned(), - ))), + _ => Err(Exceptions::illegalArgument("remainder too high".to_owned())), } } @@ -128,9 +126,9 @@ 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::IllegalArgumentException(Some(String::from( + _ => Err(Exceptions::illegalArgument(String::from( "model year argument out of range", - )))), + ))), } } diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 9466a6a..1ed68ba 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -168,7 +168,7 @@ impl BitArray { pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } if end == start { return Ok(()); @@ -211,7 +211,7 @@ impl BitArray { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } if end == start { return Ok(true); // empty range matches @@ -253,9 +253,9 @@ impl BitArray { */ pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { if num_bits > 32 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "num bits must be between 0 and 32".to_owned(), - ))); + )); } if num_bits == 0 { @@ -286,9 +286,7 @@ impl BitArray { pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { if self.size != other.size { - return Err(Exceptions::IllegalArgumentException(Some( - "Sizes don't match".to_owned(), - ))); + return Err(Exceptions::illegalArgument("Sizes don't match".to_owned())); } 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 5bda954..10d70a3 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -65,9 +65,9 @@ impl BitMatrix { */ pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Both dimensions must be greater than 0".to_owned(), - ))); + )); } Ok(Self { width, @@ -137,12 +137,12 @@ impl BitMatrix { if string_representation .chars() .nth(pos) - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? == '\n' || string_representation .chars() .nth(pos) - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? == '\r' { if bitsPos > rowStartPos { @@ -151,9 +151,9 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "row lengths do not match".to_owned(), - ))); + )); } rowStartPos = bitsPos; nRows += 1; @@ -168,10 +168,10 @@ impl BitMatrix { bits[bitsPos] = false; bitsPos += 1; } else { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "illegal character encountered: {}", string_representation[pos..].to_owned() - )))); + ))); } } @@ -182,9 +182,9 @@ impl BitMatrix { // first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "row lengths do not match".to_owned(), - ))); + )); } nRows += 1; } @@ -311,9 +311,9 @@ impl BitMatrix { pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "input matrix dimensions do not match".to_owned(), - ))); + )); } // let mut rowArray = BitArray::with_size(self.width as usize); for y in 0..self.height { @@ -363,16 +363,16 @@ impl BitMatrix { // )); // } if height < 1 || width < 1 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "height and width must be at least 1".to_owned(), - ))); + )); } let right = left + width; let bottom = top + height; if bottom > self.height || right > self.width { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "the region must fit inside the matrix".to_owned(), - ))); + )); } for y in top..bottom { //for (int y = top; y < bottom; y++) { @@ -444,9 +444,9 @@ impl BitMatrix { self.rotate180(); Ok(()) } - _ => Err(Exceptions::IllegalArgumentException(Some( + _ => Err(Exceptions::illegalArgument( "degrees must be a multiple of 0, 90, 180, or 270".to_owned(), - ))), + )), } } diff --git a/src/common/bit_source.rs b/src/common/bit_source.rs index 1c64f84..b1a54a5 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -70,9 +70,7 @@ impl BitSource { */ pub fn readBits(&mut self, numBits: usize) -> Result { if !(1..=32).contains(&numBits) || numBits > self.available() { - return Err(Exceptions::IllegalArgumentException(Some( - numBits.to_string(), - ))); + return Err(Exceptions::illegalArgument(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 6276b46..97d9063 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -244,9 +244,7 @@ impl CharacterSetECI { 28 => Ok(CharacterSetECI::Big5), 29 => Ok(CharacterSetECI::GB18030), 30 => Ok(CharacterSetECI::EUC_KR), - _ => Err(Exceptions::NotFoundException(Some( - "Bad ECI Value".to_owned(), - ))), + _ => Err(Exceptions::notFound("Bad ECI Value".to_owned())), } } diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index a4013e2..3669669 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -67,7 +67,7 @@ impl GridSampler for DefaultGridSampler { transform: &PerspectiveTransform, ) -> Result { if dimensionX == 0 || dimensionY == 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut bits = BitMatrix::new(dimensionX, dimensionY)?; let mut points = vec![0.0; 2 * dimensionX as usize]; @@ -92,15 +92,15 @@ impl GridSampler for DefaultGridSampler { // for (int x = 0; x < max; x += 2) { // if points[x] as u32 >= image.getWidth() || points[x + 1] as u32 >= image.getHeight() // { - // return Err(Exceptions::NotFoundException(Some( + // return Err(Exceptions::notFound( // "index out of bounds, see documentation in file for explanation".to_owned(), - // ))); + // )); // } if image .try_get(points[x] as u32, points[x + 1] as u32) - .ok_or(Exceptions::NotFoundException(Some( + .ok_or(Exceptions::notFound( "index out of bounds, see documentation in file for explanation".to_owned(), - )))? + ))? { // Black(-ish) pixel bits.set(x as u32 / 2, y); diff --git a/src/common/detector/monochrome_rectangle_detector.rs b/src/common/detector/monochrome_rectangle_detector.rs index 640af79..fd3e43e 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -200,13 +200,13 @@ impl<'a> MonochromeRectangleDetector<'_> { } } } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } lastRange_z = range; y += deltaY; x += deltaX } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index eaef17a..8e028de 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -77,7 +77,7 @@ impl<'a> WhiteRectangleDetector<'_> { || downInit >= image.getHeight() as i32 || rightInit >= image.getWidth() as i32 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(WhiteRectangleDetector { @@ -223,7 +223,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if z.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut t: Option = None; @@ -241,7 +241,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if t.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut x: Option = None; @@ -259,7 +259,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if x.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut y: Option = None; @@ -277,12 +277,12 @@ impl<'a> WhiteRectangleDetector<'_> { } if y.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index b0839a4..9c6a6af 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -233,9 +233,9 @@ impl GlobalHistogramBinarizer { // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if secondPeak - firstPeak <= numBuckets / 16 { - return Err(Exceptions::NotFoundException(Some( + return Err(Exceptions::notFound( "secondPeak - firstPeak <= numBuckets / 16 ".to_owned(), - ))); + )); } // Find a valley between them that is low and closer to the white peak. diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index b015e59..5fac919 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -145,7 +145,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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } nudged = false; if x == -1 { @@ -172,7 +172,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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } nudged = false; if x == -1 { diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index cd21d34..b8f6c4e 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -67,14 +67,12 @@ impl ECIInput for MinimalECIInput { */ fn charAt(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(Some( - index.to_string(), - ))); + return Err(Exceptions::indexOutOfBounds(index.to_string())); } if self.isECI(index as u32)? { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "value at {index} is not a character but an ECI" - )))); + ))); } if self.isFNC1(index)? { Ok(self.fnc1 as u8 as char) @@ -105,15 +103,15 @@ impl ECIInput for MinimalECIInput { */ fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { if start > end || end > self.length() { - return Err(Exceptions::IndexOutOfBoundsException(None)); + return Err(Exceptions::indexOutOfBoundsEmpty()); } let mut result = String::new(); for i in start..end { // for (int i = start; i < end; i++) { if self.isECI(i as u32)? { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "value at {i} is not a character but an ECI" - )))); + ))); } result.push_str(&self.charAt(i)?.to_string()); } @@ -133,7 +131,7 @@ impl ECIInput for MinimalECIInput { */ fn isECI(&self, index: u32) -> Result { if index >= self.length() as u32 { - return Err(Exceptions::IndexOutOfBoundsException(None)); + return Err(Exceptions::indexOutOfBoundsEmpty()); } Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) } @@ -158,12 +156,12 @@ impl ECIInput for MinimalECIInput { */ fn getECIValue(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(None)); + return Err(Exceptions::indexOutOfBoundsEmpty()); } if !self.isECI(index as u32)? { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "value at {index} is not an ECI but a character" - )))); + ))); } Ok((self.bytes[index] as u32 - 256) as i32) } @@ -250,7 +248,7 @@ impl MinimalECIInput { */ pub fn isFNC1(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::IndexOutOfBoundsException(None)); + return Err(Exceptions::indexOutOfBoundsEmpty()); } Ok(self.bytes[index] == 1000) } diff --git a/src/common/otsu_level_binarizer.rs b/src/common/otsu_level_binarizer.rs index b6ac08c..a4f63ca 100644 --- a/src/common/otsu_level_binarizer.rs +++ b/src/common/otsu_level_binarizer.rs @@ -19,7 +19,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::IllegalArgumentException(None)) + return Err(Exceptions::illegalArgumentEmpty()) }; buff }; diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index 576c2f5..698fba5 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -133,7 +133,7 @@ impl GenericGF { */ pub fn log(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } // let pos: usize = a.try_into().unwrap(); Ok(self.logTable[a as usize]) @@ -144,7 +144,7 @@ impl GenericGF { */ pub fn inverse(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::ArithmeticException(None)); + return Err(Exceptions::arithmeticEmpty()); } 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 26041fe..43eabda 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -49,9 +49,9 @@ impl GenericGFPoly { */ pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { if coefficients.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some(String::from( + return Err(Exceptions::illegalArgument(String::from( "coefficients cannot be empty", - )))); + ))); } Ok(Self { field, @@ -140,9 +140,9 @@ impl GenericGFPoly { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "GenericGFPolys do not have same GenericGF field".to_owned(), - ))); + )); } if self.isZero() { return Ok(other.clone()); @@ -177,9 +177,9 @@ impl GenericGFPoly { pub fn multiply(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "GenericGFPolys do not have same GenericGF field".to_owned(), - ))); + )); } if self.isZero() || other.isZero() { return Ok(self.getZero()); @@ -252,14 +252,12 @@ impl GenericGFPoly { other: &GenericGFPoly, ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "GenericGFPolys do not have same GenericGF field".to_owned(), - ))); + )); } if other.isZero() { - return Err(Exceptions::IllegalArgumentException(Some( - "Divide by 0".to_owned(), - ))); + return Err(Exceptions::illegalArgument("Divide by 0".to_owned())); } let mut quotient = self.getZero(); @@ -268,11 +266,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::IllegalArgumentException(Some( - "arithmetic issue".to_owned(), - ))) - } + Err(_issue) => return Err(Exceptions::illegalArgument("arithmetic issue".to_owned())), }; while remainder.getDegree() >= other.getDegree() && !remainder.isZero() { diff --git a/src/common/reedsolomon/reedsolomon_decoder.rs b/src/common/reedsolomon/reedsolomon_decoder.rs index 6f62140..ac28f67 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -77,7 +77,7 @@ impl ReedSolomonDecoder { return Ok(0); } let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else { - return Err(Exceptions::ReedSolomonException(None)); + return Err(Exceptions::reedSolomonEmpty()); }; let sigmaOmega = self.runEuclideanAlgorithm( &GenericGF::buildMonomial(self.field, twoS as usize, 1), @@ -92,15 +92,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::ReedSolomonException(Some( - "Bad error location".to_owned(), - ))); + return Err(Exceptions::reedSolomon("Bad error location".to_owned())); } let position: isize = received.len() as isize - 1 - log_value as isize; if position < 0 { - return Err(Exceptions::ReedSolomonException(Some( - "Bad error location".to_owned(), - ))); + return Err(Exceptions::reedSolomon("Bad error location".to_owned())); } received[position as usize] = GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); @@ -138,9 +134,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::ReedSolomonException(Some( - "r_{i-1} was zero".to_owned(), - ))); + return Err(Exceptions::reedSolomon("r_{i-1} was zero".to_owned())); } r = rLastLast; let mut q = r.getZero(); @@ -158,26 +152,20 @@ impl ReedSolomonDecoder { t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?; if r.getDegree() >= rLast.getDegree() { - return Err(Exceptions::ReedSolomonException(Some(format!( + return Err(Exceptions::reedSolomon(format!( "Division algorithm failed to reduce polynomial? r: {r}, rLast: {rLast}" - )))); + ))); } } let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::ReedSolomonException(Some( - "sigmaTilde(0) was zero".to_owned(), - ))); + return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero".to_owned())); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, - Err(_err) => { - return Err(Exceptions::ReedSolomonException(Some( - "ArithmetricException".to_owned(), - ))) - } + Err(_err) => return Err(Exceptions::reedSolomon("ArithmetricException".to_owned())), }; let sigma = t.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse); @@ -205,9 +193,9 @@ impl ReedSolomonDecoder { } } if e != numErrors { - return Err(Exceptions::ReedSolomonException(Some( + return Err(Exceptions::reedSolomon( "Error locator degree does not match number of roots".to_owned(), - ))); + )); } Ok(result) } diff --git a/src/common/reedsolomon/reedsolomon_encoder.rs b/src/common/reedsolomon/reedsolomon_encoder.rs index f155a60..3695fa4 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -73,15 +73,15 @@ impl ReedSolomonEncoder { pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<(), Exceptions> { if ec_bytes == 0 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "No error correction bytes".to_owned(), - ))); + )); } let data_bytes = to_encode.len() - ec_bytes; if data_bytes == 0 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "No data bytes provided".to_owned(), - ))); + )); } let fld = self.field; let generator = self.buildGenerator(ec_bytes); @@ -91,7 +91,7 @@ impl ReedSolomonEncoder { let mut info = GenericGFPoly::new(fld, &info_coefficients)?; info = info.multiply_by_monomial(ec_bytes, 1)?; let remainder = &info - .divide(generator.ok_or(Exceptions::ReedSolomonException(None))?)? + .divide(generator.ok_or(Exceptions::reedSolomonEmpty())?)? .1; let coefficients = remainder.getCoefficients(); let num_zero_coefficients = ec_bytes - coefficients.len(); diff --git a/src/datamatrix/data_matrix_reader.rs b/src/datamatrix/data_matrix_reader.rs index 5e24893..671ea3b 100644 --- a/src/datamatrix/data_matrix_reader.rs +++ b/src/datamatrix/data_matrix_reader.rs @@ -105,7 +105,7 @@ impl Reader for DataMatrixReader { DECODER.decode(&bits)? } } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; // decoderRXingResult = DECODER.decode(detectorRXingResult.getBits())?; @@ -181,10 +181,10 @@ impl DataMatrixReader { */ fn extractPureBits(&self, image: &BitMatrix) -> Result { let Some(leftTopBlack) = image.getTopLeftOnBit() else { - return Err(Exceptions::NotFoundException(None)) + return Err(Exceptions::notFoundEmpty()) }; let Some(rightBottomBlack) = image.getBottomRightOnBit()else { - return Err(Exceptions::NotFoundException(None)) + return Err(Exceptions::notFoundEmpty()) }; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -197,7 +197,7 @@ impl DataMatrixReader { let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32; let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32; if matrixWidth <= 0 || matrixHeight <= 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); // throw NotFoundException.getNotFoundInstance(); } @@ -234,12 +234,12 @@ impl DataMatrixReader { x += 1; } if x == width { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let moduleSize = x - leftTopBlack[0]; if moduleSize == 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(moduleSize) diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index 936caba..03b67ec 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -60,21 +60,21 @@ impl Writer for DataMatrixWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Found empty contents".to_owned(), - ))); + )); } if format != &BarcodeFormat::DATA_MATRIX { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Can only encode DATA_MATRIX, but got {format:?}" - )))); + ))); } if width < 0 || height < 0 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested dimensions can't be negative: {width}x{height}" - )))); + ))); } // Try to get force shape & min / max size @@ -123,7 +123,7 @@ impl Writer for DataMatrixWriter { if hasEncodingHint { let Some(EncodeHintValue::CharacterSet(char_set_name)) = hints.get(&EncodeHintType::CHARACTER_SET) else { - return Err(Exceptions::IllegalArgumentException(Some("charset does not exist".to_owned()))) + return Err(Exceptions::illegalArgument("charset does not exist".to_owned())) }; charset = encoding::label::encoding_from_whatwg_label(char_set_name); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); @@ -157,7 +157,7 @@ impl Writer for DataMatrixWriter { let symbol_lookup = SymbolInfoLookup::new(); let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else { - return Err(Exceptions::NotFoundException(Some("symbol info is bad".to_owned()))) + return Err(Exceptions::notFound("symbol info is bad".to_owned())) }; //2. step: ECC generation diff --git a/src/datamatrix/decoder/bit_matrix_parser.rs b/src/datamatrix/decoder/bit_matrix_parser.rs index 478c935..eccd707 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -34,7 +34,7 @@ impl BitMatrixParser { pub fn new(bitMatrix: &BitMatrix) -> Result { let dimension = bitMatrix.getHeight(); if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let version = Self::readVersion(bitMatrix)?; @@ -178,7 +178,7 @@ impl BitMatrixParser { } if resultOffset != self.version.getTotalCodewords() as usize { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } Ok(result) @@ -456,9 +456,9 @@ impl BitMatrixParser { let symbolSizeColumns = version.getSymbolSizeColumns(); if bitMatrix.getHeight() != symbolSizeRows { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Dimension of bitMatrix must match the version size".to_owned(), - ))); + )); } let dataRegionSizeRows = version.getDataRegionSizeRows(); diff --git a/src/datamatrix/decoder/data_block.rs b/src/datamatrix/decoder/data_block.rs index eeed3f3..9e769d8 100644 --- a/src/datamatrix/decoder/data_block.rs +++ b/src/datamatrix/decoder/data_block.rs @@ -138,7 +138,7 @@ impl DataBlock { } if rawCodewordsOffset != rawCodewords.len() { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } Ok(result) diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index ca1b5ee..95331da 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 return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } if !(mode != Mode::PAD_ENCODE && bits.available() > 0) { @@ -225,16 +225,14 @@ fn decodeAsciiSegment( loop { let mut oneByte = bits.readBits(8)?; match oneByte { - 0 => return Err(Exceptions::FormatException(None)), + 0 => return Err(Exceptions::formatEmpty()), 1..=128 => { // ASCII data (ASCII value + 1) if upperShift { oneByte += 128; //upperShift = false; } - result.append_char( - char::from_u32(oneByte - 1).ok_or(Exceptions::ParseException(None))?, - ); + result.append_char(char::from_u32(oneByte - 1).ok_or(Exceptions::parseEmpty())?); return Ok(Mode::ASCII_ENCODE); } 129 => return Ok(Mode::PAD_ENCODE), // Pad @@ -280,9 +278,9 @@ fn decodeAsciiSegment( if !firstCodeword // Must be first ISO 16022:2006 5.6.1 { - return Err(Exceptions::FormatException(Some( + return Err(Exceptions::format( "structured append tag must be first code word".to_owned(), - ))); + )); } parse_structured_append(bits, &mut sai)?; firstFNC1Position = 5; @@ -333,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } } @@ -388,26 +386,24 @@ fn decodeC40Segment( if upperShift { result.append_char( char::from_u32(c40char as u32 + 128) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { result.append_char(c40char); } } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } 1 => { if upperShift { result.append_char( - char::from_u32(cValue + 128).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { - result.append_char( - char::from_u32(cValue).ok_or(Exceptions::ParseException(None))?, - ); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::parseEmpty())?); } shift = 0; } @@ -417,7 +413,7 @@ fn decodeC40Segment( if upperShift { result.append_char( char::from_u32(c40char as u32 + 128) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { @@ -436,7 +432,7 @@ fn decodeC40Segment( upperShift = true } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } shift = 0; @@ -444,18 +440,18 @@ fn decodeC40Segment( 3 => { if upperShift { result.append_char( - char::from_u32(cValue + 224).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 224).ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { result.append_char( - char::from_u32(cValue + 96).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 96).ok_or(Exceptions::parseEmpty())?, ); } shift = 0; } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } if bits.available() == 0 { @@ -505,26 +501,24 @@ fn decodeTextSegment( if upperShift { result.append_char( char::from_u32(textChar as u32 + 128) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { result.append_char(textChar); } } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } 1 => { if upperShift { result.append_char( - char::from_u32(cValue + 128).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { - result.append_char( - char::from_u32(cValue).ok_or(Exceptions::ParseException(None))?, - ); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::parseEmpty())?); } shift = 0; } @@ -536,7 +530,7 @@ fn decodeTextSegment( if upperShift { result.append_char( char::from_u32(textChar as u32 + 128) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { @@ -555,7 +549,7 @@ fn decodeTextSegment( upperShift = true } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } shift = 0; @@ -566,7 +560,7 @@ fn decodeTextSegment( if upperShift { result.append_char( char::from_u32(textChar as u32 + 128) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); upperShift = false; } else { @@ -574,11 +568,11 @@ fn decodeTextSegment( } shift = 0; } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } if bits.available() == 0 { @@ -645,15 +639,15 @@ fn decodeAnsiX12Segment( if cValue < 14 { // 0 - 9 result.append_char( - char::from_u32(cValue + 44).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 44).ok_or(Exceptions::parseEmpty())?, ); } else if cValue < 40 { // A - Z result.append_char( - char::from_u32(cValue + 51).ok_or(Exceptions::ParseException(None))?, + char::from_u32(cValue + 51).ok_or(Exceptions::parseEmpty())?, ); } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } } @@ -708,8 +702,7 @@ fn decodeEdifactSegment( // 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::ParseException(None))?); + result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::parseEmpty())?); } if bits.available() == 0 { @@ -746,7 +739,7 @@ fn decodeBase256Segment( // We're seeing NegativeArraySizeException errors from users. // but we shouldn't in rust because it's unsigned // if count < 0 { - // return Err(Exceptions::FormatException(None)); + // return Err(Exceptions::formatEmpty()); // } let mut bytes = vec![0u8; count as usize]; @@ -754,7 +747,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); } *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; codewordPosition += 1; @@ -762,7 +755,7 @@ fn decodeBase256Segment( result.append_string( &encoding::all::ISO_8859_1 .decode(&bytes, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::ParseException(Some(e.to_string())))?, + .map_err(|e| Exceptions::parse(e.to_string()))?, ); byteSegments.push(bytes); diff --git a/src/datamatrix/decoder/version.rs b/src/datamatrix/decoder/version.rs index 16b126c..b443bad 100644 --- a/src/datamatrix/decoder/version.rs +++ b/src/datamatrix/decoder/version.rs @@ -105,7 +105,7 @@ impl Version { numColumns: u32, ) -> Result<&'static Version, Exceptions> { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } for version in VERSIONS.iter() { @@ -114,7 +114,7 @@ impl Version { } } - Err(Exceptions::FormatException(None)) + Err(Exceptions::formatEmpty()) } /** diff --git a/src/datamatrix/detector/datamatrix_detector.rs b/src/datamatrix/detector/datamatrix_detector.rs index 89e1f39..7a12213 100644 --- a/src/datamatrix/detector/datamatrix_detector.rs +++ b/src/datamatrix/detector/datamatrix_detector.rs @@ -53,9 +53,7 @@ impl<'a> Detector<'_> { if let Some(point) = self.correctTopRight(&points) { points[3] = point; } else { - return Err(Exceptions::NotFoundException(Some( - "point 4 unfound".to_owned(), - ))); + return Err(Exceptions::notFound("point 4 unfound".to_owned())); } // 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 a5d188d..b0d5d49 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs @@ -254,7 +254,7 @@ fn Scan( )); } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } pub fn detect( @@ -359,6 +359,6 @@ pub fn detect( } // #ifndef __cpp_impl_coroutine - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) // #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 4a9976b..c26b0e1 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: &RXingResultPoint) -> Result<(), Exceptions> { if self.direction_inward == RXingResultPoint::default() { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } self.points.push(*p); if self.points.len() == 1 { @@ -241,7 +241,7 @@ impl DMRegressionLine { end: &RXingResultPoint, ) -> Result { if self.points.len() <= 3 { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } // re-evaluate and filter out all points too far away. required for the gapSizes calculation. @@ -267,11 +267,11 @@ impl DMRegressionLine { &(*self .points .last() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? - *self .points .first() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?), + .ok_or(Exceptions::indexOutOfBoundsEmpty())?), )) as f64; // calculate the width of 2 modules (first black pixel to first black pixel) @@ -297,7 +297,7 @@ impl DMRegressionLine { &self.project( self.points .last() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ), ) 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 d547e93..a7f717d 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs @@ -199,7 +199,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 == RXingResultPoint::centered(&pEdge) { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } self.p = RXingResultPoint::centered(&pEdge); @@ -277,7 +277,7 @@ impl<'a> EdgeTracer<'_> { .points() .first() .as_ref() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?), + .ok_or(Exceptions::indexOutOfBoundsEmpty())?), ) { return Ok(false); } @@ -307,9 +307,9 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?) + .ok_or(Exceptions::indexOutOfBoundsEmpty())?) { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } if !line.points().is_empty() && &&self.p @@ -317,7 +317,7 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? { return Ok(false); } @@ -363,7 +363,7 @@ impl<'a> EdgeTracer<'_> { line.points() .last() .as_ref() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ), ) < 1.0 { @@ -380,7 +380,7 @@ impl<'a> EdgeTracer<'_> { - line .points() .last() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) }; line.add(&self.p)?; @@ -396,7 +396,7 @@ impl<'a> EdgeTracer<'_> { + *line .points() .first() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?), + .ok_or(Exceptions::indexOutOfBoundsEmpty())?), ) { return Ok(false); } diff --git a/src/datamatrix/detector/zxing_cpp_detector/util.rs b/src/datamatrix/detector/zxing_cpp_detector/util.rs index 00e3c01..3067631 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/util.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/util.rs @@ -26,7 +26,7 @@ pub fn intersect( l2: &DMRegressionLine, ) -> Result { if !(l1.isValid() && l2.isValid()) { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } 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 a235321..ec7fd38 100644 --- a/src/datamatrix/encoder/ascii_encoder.rs +++ b/src/datamatrix/encoder/ascii_encoder.rs @@ -31,12 +31,12 @@ impl Encoder for ASCIIEncoder { .getMessage() .chars() .nth(context.pos as usize) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, context .getMessage() .chars() .nth(context.pos as usize + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, )? as u8); context.pos += 2; } else { @@ -73,9 +73,7 @@ impl Encoder for ASCIIEncoder { } _ => { - return Err(Exceptions::IllegalStateException(Some(format!( - "Illegal mode: {newMode}" - )))); + return Err(Exceptions::illegalState(format!("Illegal mode: {newMode}"))); } } } else if high_level_encoder::isExtendedASCII(c) { @@ -104,9 +102,9 @@ impl ASCIIEncoder { let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); Ok((num + 130) as char) } else { - Err(Exceptions::IllegalArgumentException(Some(format!( + Err(Exceptions::illegalArgument(format!( "not digits: {digit1}{digit2}" - )))) + ))) } } } diff --git a/src/datamatrix/encoder/base256_encoder.rs b/src/datamatrix/encoder/base256_encoder.rs index f62d9ed..bc73eb7 100644 --- a/src/datamatrix/encoder/base256_encoder.rs +++ b/src/datamatrix/encoder/base256_encoder.rs @@ -53,7 +53,7 @@ impl Encoder for Base256Encoder { context.updateSymbolInfoWithLength(currentSize); let mustPad = (context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() - currentSize as u32) > 0; @@ -62,29 +62,29 @@ impl Encoder for Base256Encoder { buffer.replace_range( 0..1, &char::from_u32(dataCount as u32) - .ok_or(Exceptions::ParseException(None))? + .ok_or(Exceptions::parseEmpty())? .to_string(), ); } else if dataCount <= 1555 { buffer.replace_range( 0..1, &char::from_u32((dataCount as u32 / 250) + 249) - .ok_or(Exceptions::ParseException(None))? + .ok_or(Exceptions::parseEmpty())? .to_string(), ); let (ci_pos, _) = buffer .char_indices() .nth(1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; buffer.insert( ci_pos, char::from_u32(dataCount as u32 % 250) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ); } else { - return Err(Exceptions::IllegalStateException(Some(format!( + return Err(Exceptions::illegalState(format!( "Message length not in valid ranges: {dataCount}" - )))); + ))); } } let c = buffer.chars().count(); @@ -95,10 +95,10 @@ impl Encoder for Base256Encoder { buffer .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, context.getCodewordCount() as u32 + 1, ) - .ok_or(Exceptions::ParseException(None))? as u8, + .ok_or(Exceptions::parseEmpty())? as u8, ); } Ok(()) diff --git a/src/datamatrix/encoder/c40_encoder.rs b/src/datamatrix/encoder/c40_encoder.rs index b6c3d3a..ff00213 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -65,7 +65,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() as usize - curCodewordCount; @@ -140,7 +140,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() as usize - curCodewordCount; let rest = buffer.chars().count() % 3; @@ -182,9 +182,7 @@ impl C40Encoder { context: &mut EncoderContext, buffer: &mut String, ) -> Result<(), Exceptions> { - context.writeCodewords( - &Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?, - ); + context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::formatEmpty())?); buffer.replace_range(0..3, ""); // buffer.delete(0, 3); Ok(()) @@ -207,7 +205,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() as usize - curCodewordCount; @@ -236,9 +234,9 @@ impl C40Encoder { context.writeCodeword(C40_UNLATCH); } } else { - return Err(Exceptions::IllegalStateException(Some( + return Err(Exceptions::illegalState( "Unexpected case. Please report!".to_owned(), - ))); + )); } context.signalEncoderChange(ASCII_ENCODATION); diff --git a/src/datamatrix/encoder/default_placement.rs b/src/datamatrix/encoder/default_placement.rs index a4091a3..efebc72 100644 --- a/src/datamatrix/encoder/default_placement.rs +++ b/src/datamatrix/encoder/default_placement.rs @@ -164,7 +164,7 @@ impl DefaultPlacement { .codewords .chars() .nth(pos) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32; + .ok_or(Exceptions::indexOutOfBoundsEmpty())? 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 cf1cab0..c42f252 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -76,7 +76,7 @@ impl EdifactEncoder { context.updateSymbolInfo(); let mut available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() - context.getCodewordCount() as u32; let remaining = context.getRemainingCharacters(); @@ -85,7 +85,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + 1); available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() - context.getCodewordCount() as u32; } @@ -95,9 +95,9 @@ impl EdifactEncoder { } if count > 4 { - return Err(Exceptions::IllegalStateException(Some( + return Err(Exceptions::illegalState( "Count must not exceed 4".to_owned(), - ))); + )); } let restChars = count - 1; let encoded = Self::encodeToCodewords(buffer)?; @@ -108,7 +108,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + restChars); let available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() - context.getCodewordCount() as u32; if available >= 3 { @@ -149,32 +149,32 @@ impl EdifactEncoder { fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { - return Err(Exceptions::IllegalStateException(Some( + return Err(Exceptions::illegalState( "StringBuilder must not be empty".to_owned(), - ))); + )); } let c1 = sb .chars() .next() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; let c2 = if len >= 2 { sb.chars() .nth(1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? } else { 0 as char }; let c3 = if len >= 3 { sb.chars() .nth(2) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? } else { 0 as char }; let c4 = if len >= 4 { sb.chars() .nth(3) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? } else { 0 as char }; @@ -184,12 +184,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::IndexOutOfBoundsException(None))?); + res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBoundsEmpty())?); if len >= 2 { - res.push(char::from_u32(cw2).ok_or(Exceptions::IndexOutOfBoundsException(None))?); + res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBoundsEmpty())?); } if len >= 3 { - res.push(char::from_u32(cw3).ok_or(Exceptions::IndexOutOfBoundsException(None))?); + res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBoundsEmpty())?); } Ok(res) diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index c2a9c7f..f9eebf7 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -63,14 +63,12 @@ impl<'a> EncoderContext<'_> { ISO_8859_1_ENCODER .decode(&encoded_bytes, encoding::DecoderTrap::Strict) .map_err(|e| { - Exceptions::ParseException(Some(format!( - "round trip decode should always work: {e}" - ))) + Exceptions::parse(format!("round trip decode should always work: {e}")) })? } else { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Message contains characters outside ISO-8859-1 encoding.".to_owned(), - ))); + )); }; Ok(Self { symbol_lookup: Rc::new(SymbolInfoLookup::new()), diff --git a/src/datamatrix/encoder/error_correction.rs b/src/datamatrix/encoder/error_correction.rs index 4c07b9b..69dabb6 100644 --- a/src/datamatrix/encoder/error_correction.rs +++ b/src/datamatrix/encoder/error_correction.rs @@ -154,9 +154,9 @@ const ALOG: [u32; 255] = { */ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "The number of codewords does not match the selected symbol".to_owned(), - ))); + )); } let mut sb = String::with_capacity( (symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()) as usize, @@ -185,7 +185,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result Result Result Result 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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } 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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } 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 b08d9cc..b89f4ee 100644 --- a/src/datamatrix/encoder/high_level_encoder.rs +++ b/src/datamatrix/encoder/high_level_encoder.rs @@ -223,7 +223,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( c40Encoder.encodeMaximalC40(&mut context)?; encodingMode = context .getNewEncoding() - .ok_or(Exceptions::IllegalStateException(None))?; + .ok_or(Exceptions::illegalStateEmpty())?; context.resetEncoderSignal(); } @@ -232,7 +232,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( if context.getNewEncoding().is_some() { encodingMode = context .getNewEncoding() - .ok_or(Exceptions::IllegalStateException(None))?; + .ok_or(Exceptions::illegalStateEmpty())?; context.resetEncoderSignal(); } } @@ -240,7 +240,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( context.updateSymbolInfo(); let capacity = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity(); if len < capacity as usize && encodingMode != ASCII_ENCODATION @@ -611,7 +611,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 { pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { // let hex = Integer.toHexString(c); // hex = "0000".substring(0, 4 - hex.length()) + hex; - Err(Exceptions::IllegalArgumentException(Some(format!( + Err(Exceptions::illegalArgument(format!( "Illegal character: {c} (0x{c})" - )))) + ))) } diff --git a/src/datamatrix/encoder/minimal_encoder.rs b/src/datamatrix/encoder/minimal_encoder.rs index 67ee60b..b5e609b 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<(), Ex if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() || edges[vertexIndex][edge.getEndMode()?.ordinal()] .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .cachedTotalSize > edge.cachedTotalSize { @@ -635,9 +635,9 @@ fn encodeMinimally(input: Rc) -> Result { } if minimalJ < 0 { - return Err(Exceptions::IllegalStateException(Some(format!( + return Err(Exceptions::illegalState(format!( "Internal error: failed to encode \"{input}\"" - )))); + ))); } RXingResult::new(edges[inputLength][minimalJ as usize].clone()) } @@ -669,7 +669,7 @@ impl Edge { previous: Option>, ) -> Result { if fromPosition + characterLength > input.length() as u32 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } 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::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); }; 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 1ff6b9e..0e79c8f 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -128,9 +128,9 @@ impl SymbolInfo { 2 | 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::IllegalStateException(Some( + _ => Err(Exceptions::illegalState( "Cannot handle this number of data regions".to_owned(), - ))), + )), } } @@ -140,9 +140,9 @@ impl SymbolInfo { 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::IllegalStateException(Some( + _ => Err(Exceptions::illegalState( "Cannot handle this number of data regions".to_owned(), - ))), + )), } } @@ -310,9 +310,9 @@ impl<'a> SymbolInfoLookup<'a> { } } if fail { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Can't find a symbol arrangement that matches the message. Data codewords: {dataCodewords}" - )))); + ))); } Ok(None) } diff --git a/src/datamatrix/encoder/x12_encoder.rs b/src/datamatrix/encoder/x12_encoder.rs index c479f24..3031d68 100644 --- a/src/datamatrix/encoder/x12_encoder.rs +++ b/src/datamatrix/encoder/x12_encoder.rs @@ -81,7 +81,7 @@ impl X12Encoder { context.updateSymbolInfo(); let available = context .getSymbolInfo() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getDataCapacity() - context.getCodewordCount() as u32; let count = buffer.chars().count(); diff --git a/src/helpers.rs b/src/helpers.rs index 68e853b..592b6d9 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -35,20 +35,20 @@ pub fn detect_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "file does not exist".to_owned(), - ))); + )); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::IllegalArgumentException(Some("file cannot be opened".to_owned()))); + return Err(Exceptions::illegalArgument("file cannot be opened".to_owned())); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "file cannot be read".to_owned(), - ))); + )); } let mut multi_format_reader = MultiFormatReader::default(); @@ -88,20 +88,20 @@ pub fn detect_multiple_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "file does not exist".to_owned(), - ))); + )); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::IllegalArgumentException(Some("file cannot be opened".to_owned()))); + return Err(Exceptions::illegalArgument("file cannot be opened".to_owned())); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "file cannot be read".to_owned(), - ))); + )); } let multi_format_reader = MultiFormatReader::default(); @@ -134,7 +134,7 @@ pub fn detect_in_file_with_hints( hints: &mut DecodingHintDictionary, ) -> Result { let Ok(img) = image::open(file_name) else { - return Err(Exceptions::IllegalArgumentException(Some(format!("file '{file_name}' not found or cannot be opened")))); + return Err(Exceptions::illegalArgument(format!("file '{file_name}' not found or cannot be opened"))); }; let mut multi_format_reader = MultiFormatReader::default(); @@ -167,9 +167,8 @@ pub fn detect_multiple_in_file_with_hints( file_name: &str, hints: &mut DecodingHintDictionary, ) -> Result, Exceptions> { - let img = image::open(file_name).map_err(|e| { - Exceptions::RuntimeException(Some(format!("couldn't read {file_name}: {e}"))) - })?; + let img = image::open(file_name) + .map_err(|e| Exceptions::runtime(format!("couldn't read {file_name}: {e}")))?; let multi_format_reader = MultiFormatReader::default(); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); @@ -256,9 +255,9 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Excepti let image: image::DynamicImage = bit_matrix.into(); match image.save(file_name) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::IllegalArgumentException(Some(format!( + Err(err) => Err(Exceptions::illegalArgument(format!( "could not save file '{file_name}': {err}" - )))), + ))), } } @@ -268,10 +267,10 @@ pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exception match svg::save(file_name, &svg) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::IllegalArgumentException(Some(format!( + Err(err) => Err(Exceptions::illegalArgument(format!( "could not save file '{}': {}", file_name, err - )))), + ))), } } @@ -303,8 +302,8 @@ pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptio Ok(()) }() { Ok(_) => Ok(()), - Err(_) => Err(Exceptions::IllegalArgumentException(Some(format!( + Err(_) => Err(Exceptions::illegalArgument(format!( "could not write to '{file_name}'" - )))), + ))), } } diff --git a/src/luma_luma_source.rs b/src/luma_luma_source.rs index 37631fa..5f60e7b 100644 --- a/src/luma_luma_source.rs +++ b/src/luma_luma_source.rs @@ -95,9 +95,9 @@ impl LuminanceSource for Luma8LuminanceSource { } fn rotateCounterClockwise45(&self) -> Result, crate::Exceptions> { - Err(crate::Exceptions::UnsupportedOperationException(Some( + Err(crate::Exceptions::unsupportedOperation( "This luminance source does not support rotation by 45 degrees.".to_owned(), - ))) + )) } } diff --git a/src/luminance_source.rs b/src/luminance_source.rs index acf1896..21954bf 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -91,9 +91,9 @@ pub trait LuminanceSource { _width: usize, _height: usize, ) -> Result, Exceptions> { - Err(Exceptions::UnsupportedOperationException(Some( + Err(Exceptions::unsupportedOperation( "This luminance source does not support cropping.".to_owned(), - ))) + )) } /** @@ -118,9 +118,9 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise(&self) -> Result, Exceptions> { - Err(Exceptions::UnsupportedOperationException(Some( + Err(Exceptions::unsupportedOperation( "This luminance source does not support rotation by 90 degrees.".to_owned(), - ))) + )) } /** @@ -130,9 +130,9 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise45(&self) -> Result, Exceptions> { - Err(Exceptions::UnsupportedOperationException(Some( + Err(Exceptions::unsupportedOperation( "This luminance source does not support rotation by 45 degrees.".to_owned(), - ))) + )) } #[inline(always)] diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index 33f2578..c46ec43 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -86,7 +86,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); } // 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 d142f85..c43422f 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::NotFoundException(None)), + _ => return Err(Exceptions::notFoundEmpty()), } datawords[0..10].clone_from_slice(&codewords[0..10]); diff --git a/src/maxicode/detector.rs b/src/maxicode/detector.rs index dc67188..85eabc4 100644 --- a/src/maxicode/detector.rs +++ b/src/maxicode/detector.rs @@ -318,7 +318,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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; // we should have an idea where the center is at this point, @@ -341,7 +341,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result Result Result std::cmp::Ordering { pub fn read_bits(image: &BitMatrix) -> Result { let enclosingRectangle = image .getEnclosingRectangle() - .ok_or(Exceptions::NotFoundException(None))?; + .ok_or(Exceptions::notFoundEmpty())?; 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 a7f422c..fd7041b 100644 --- a/src/maxicode/maxi_code_reader.rs +++ b/src/maxicode/maxi_code_reader.rs @@ -126,11 +126,10 @@ impl MaxiCodeReader { fn extractPureBits(image: &BitMatrix) -> Result { let enclosingRectangleOption = image.getEnclosingRectangle(); if enclosingRectangleOption.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } - let enclosingRectangle = - enclosingRectangleOption.ok_or(Exceptions::NotFoundException(None))?; + let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFoundEmpty())?; 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 301889d..b995a21 100644 --- a/src/multi/generic_multiple_barcode_reader.rs +++ b/src/multi/generic_multiple_barcode_reader.rs @@ -56,7 +56,7 @@ impl MultipleBarcodeReader for GenericMultipleBarcodeReader { let mut results = Vec::new(); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); if results.is_empty() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(results) } diff --git a/src/multi/qrcode/detector/multi_detector.rs b/src/multi/qrcode/detector/multi_detector.rs index bd4d934..0cf0dec 100644 --- a/src/multi/qrcode/detector/multi_detector.rs +++ b/src/multi/qrcode/detector/multi_detector.rs @@ -53,7 +53,7 @@ impl<'a> MultiDetector<'_> { let infos = finder.findMulti(hints)?; if infos.is_empty() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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 7e68975..49803d6 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -93,9 +93,9 @@ impl<'a> MultiFinderPatternFinder<'_> { if size < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::NotFoundException(Some( + return Err(Exceptions::notFound( "Couldn't find enough finder patterns".to_owned(), - ))); + )); } /* @@ -212,7 +212,7 @@ impl<'a> MultiFinderPatternFinder<'_> { if !results.is_empty() { Ok(results) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/multi/qrcode/qr_code_multi_reader.rs b/src/multi/qrcode/qr_code_multi_reader.rs index ce0190f..3622614 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::NotFoundException(None))); + return Err(output.err().unwrap_or(Exceptions::notFoundEmpty())); } } diff --git a/src/multi_format_reader.rs b/src/multi_format_reader.rs index dd797c9..a19cbe0 100644 --- a/src/multi_format_reader.rs +++ b/src/multi_format_reader.rs @@ -192,6 +192,6 @@ impl MultiFormatReader { } } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/multi_format_writer.rs b/src/multi_format_writer.rs index 8371cd7..2de19ea 100644 --- a/src/multi_format_writer.rs +++ b/src/multi_format_writer.rs @@ -71,9 +71,9 @@ impl Writer for MultiFormatWriter { BarcodeFormat::DATA_MATRIX => Box::::default(), BarcodeFormat::AZTEC => Box::::default(), _ => { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "No encoder available for format {format:?}" - )))) + ))) } }; diff --git a/src/oned/coda_bar_reader.rs b/src/oned/coda_bar_reader.rs index fe3dcc8..2f0634f 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // 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::ParseException(None))?); + .push(char::from_u32(charOffset as u32).ok_or(Exceptions::parseEmpty())?); 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } self.validatePattern(startOffset)?; @@ -113,7 +113,7 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize] .to_string(), ); @@ -123,23 +123,23 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .next() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let endchar = self .decodeRowRXingResult .chars() .nth(self.decodeRowRXingResult.chars().count() - 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // remove stop/start characters character and check if a long enough string is contained if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize { // Almost surely a false positive ( start + stop + at least 1 character) - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if !matches!( @@ -243,7 +243,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize]; for j in (0_usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -282,7 +282,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize]; for j in (0usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -290,7 +290,7 @@ impl CodaBarReader { let category = (j & 1) + ((pattern as usize) & 1) * 2; let size = self.counters[(pos + j)]; if (size as f32) < mins[category] || (size as f32) > maxes[category] { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } pattern >>= 1; } @@ -311,7 +311,7 @@ impl CodaBarReader { let mut i = row.getNextUnset(0); let end = row.getSize(); if i >= end { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut isWhite = true; let mut count = 0; @@ -363,7 +363,7 @@ impl CodaBarReader { i += 2; } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } 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 553f51b..a773667 100644 --- a/src/oned/coda_bar_writer.rs +++ b/src/oned/coda_bar_writer.rs @@ -43,12 +43,12 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let firstChar = contents .chars() .next() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_ascii_uppercase(); let lastChar = contents .chars() .nth(contents.chars().count() - 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_ascii_uppercase(); let startsNormal = CodaBarReader::arrayContains(&START_END_CHARS, firstChar); let endsNormal = CodaBarReader::arrayContains(&START_END_CHARS, lastChar); @@ -56,26 +56,26 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar); if startsNormal { if !endsNormal { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Invalid start/end guards: {contents}" - )))); + ))); } // else already has valid start/end contents.to_owned() } else if startsAlt { if !endsAlt { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Invalid start/end guards: {contents}" - )))); + ))); } // else already has valid start/end contents.to_owned() } else { // Doesn't start with a guard if endsNormal || endsAlt { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Invalid start/end guards: {contents}" - )))); + ))); } // else doesn't end with guard either, so add a default format!("{DEFAULT_GUARD}{contents}{DEFAULT_GUARD}") @@ -93,9 +93,9 @@ impl OneDimensionalCodeWriter for CodaBarWriter { ) { resultLength += 10; } else { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Cannot encode : '{ch}'" - )))); + ))); } } // A blank is placed between each character. @@ -108,7 +108,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let mut c = contents .chars() .nth(index) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .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 f9b8ca9..f73d264 100644 --- a/src/oned/code_128_reader.rs +++ b/src/oned/code_128_reader.rs @@ -50,7 +50,7 @@ impl OneDReader for Code128Reader { CODE_START_A => CODE_CODE_A, CODE_START_B => CODE_CODE_B, CODE_START_C => CODE_CODE_C, - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), }; let mut done = false; @@ -100,9 +100,7 @@ impl OneDReader for Code128Reader { // Take care of illegal start codes match code { - CODE_START_A | CODE_START_B | CODE_START_C => { - return Err(Exceptions::FormatException(None)) - } + CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::formatEmpty()), _ => {} } @@ -296,21 +294,21 @@ impl OneDReader for Code128Reader { row.getSize().min(nextStart + (nextStart - lastStart) / 2), false, )? { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier as usize * lastCode as usize; // lastCode is the checksum then: if (checksumTotal % 103) as u8 != lastCode { - return Err(Exceptions::ChecksumException(None)); + return Err(Exceptions::checksumEmpty()); } // Need to pull out the check digits from string let resultLength = result.chars().count(); if resultLength == 0 { // false positive - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // Only bother if the result had at least one character, and if the checksum digit happened to @@ -331,9 +329,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::IndexOutOfBoundsException(None))?; + *rawByte = *rawCodes.get(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?; } let mut resultObject = RXingResult::new( &result, @@ -407,7 +403,7 @@ impl Code128Reader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn decodeCode( @@ -432,7 +428,7 @@ impl Code128Reader { if bestMatch >= 0 { Ok(bestMatch as u8) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } } diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index 04a6d77..f08e1d1 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -99,23 +99,23 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result forcedCodeSet = CODE_CODE_A as i32, "B" => forcedCodeSet = CODE_CODE_B as i32, "C" => forcedCodeSet = CODE_CODE_C as i32, _ => { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Unsupported code set hint: {codeSetHint}" - )))) + ))) } } } @@ -134,9 +134,9 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 127 { // no full Latin-1 character set available at the moment // shift and manual code change are not supported - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Bad character in input: ASCII value={c}" - )))); + ))); } } } @@ -149,18 +149,18 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 95 && c <= 127 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Bad character in input for forced code set A: ASCII value={c}" - )))); + ))); } } CODE_CODE_B_I32 => // allows no ascii below 32 (terminal symbols) { if c <= 32 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Bad character in input for forced code set B: ASCII value={c}" - )))); + ))); } } CODE_CODE_C_I32 => @@ -172,9 +172,9 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result {} @@ -195,8 +195,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception while position < length { //Select code to use let newCodeSet = if forcedCodeSet == -1 { - chooseCode(contents, position, codeSet) - .ok_or(Exceptions::IllegalStateException(None))? + chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalStateEmpty())? } else { forcedCodeSet as usize // THIS IS RISKY }; @@ -209,7 +208,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception match contents .chars() .nth(position) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? { ESCAPE_FNC_1 => patternIndex = CODE_FNC_1 as isize, ESCAPE_FNC_2 => patternIndex = CODE_FNC_2 as isize, @@ -229,7 +228,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as isize - ' ' as isize; if patternIndex < 0 { @@ -241,7 +240,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as isize - ' ' as isize } @@ -249,9 +248,9 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception // CODE_CODE_C if position + 1 == length { // this is the last character, but the encoding is C, which always encodes two characers - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Bad number of characters for digit only encoding.".to_owned(), - ))); + )); } let s: String = contents .char_indices() @@ -260,7 +259,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception .map(|(_u, c)| c) .collect(); patternIndex = s.parse::().map_err(|e| { - Exceptions::ParseException(Some(format!("issue parsing {s}: {e}"))) + Exceptions::parse(format!("issue parsing {s}: {e}")) })?; position += 1; } // Also incremented below @@ -536,7 +535,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; if contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? == ESCAPE_FNC_1 { addPattern( @@ -555,9 +554,8 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; .collect(); addPattern( &mut patterns, - s.parse::().map_err(|e| { - Exceptions::ParseException(Some(format!("unable to parse {s} {e}"))) - })?, + s.parse::() + .map_err(|e| Exceptions::parse(format!("unable to parse {s} {e}")))?, &mut checkSum, &mut checkWeight, i, @@ -572,7 +570,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; let mut patternIndex = match contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? { ESCAPE_FNC_1 => CODE_FNC_1 as isize, ESCAPE_FNC_2 => CODE_FNC_2 as isize, @@ -590,7 +588,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as isize - ' ' as isize } @@ -682,7 +680,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; minPath: &mut Vec>, ) -> Result { if position >= contents.chars().count() { - return Err(Exceptions::IllegalStateException(None)); + return Err(Exceptions::illegalStateEmpty()); } let mCost = memoizedCost[charset.ordinal()][position]; if mCost > 0 { @@ -763,10 +761,10 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } } if minCost == u32::MAX { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Bad character in input: ASCII value={}", contents.chars().nth(position).unwrap_or('x') - )))); + ))); // throw new IllegalArgumentException("Bad character in input: ASCII value=" + (int) contents.charAt(position)); } memoizedCost[charset.ordinal()][position] = minCost; diff --git a/src/oned/code_39_reader.rs b/src/oned/code_39_reader.rs index 6a80c1a..6a2d20c 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if self.usingCheckDigit { @@ -96,7 +96,7 @@ impl OneDReader for Code39Reader { self.decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { total += pos; } @@ -105,20 +105,20 @@ impl OneDReader for Code39Reader { .decodeRowRXingResult .chars() .nth(max) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? != Self::ALPHABET_STRING .chars() .nth(total % 43) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } self.decodeRowRXingResult.truncate(max); } if self.decodeRowRXingResult.chars().count() == 0 { // false positive - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let resultString = if self.extendedMode { @@ -246,7 +246,7 @@ impl Code39Reader { isWhite = !isWhite; } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } // 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::IndexOutOfBoundsException(None)); + .ok_or(Exceptions::indexOutOfBoundsEmpty()); } } if pattern == Self::ASTERISK_ENCODING { return Ok('*'); } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn decodeExtended(encoded: &str) -> Result { @@ -325,46 +325,46 @@ impl Code39Reader { let c = encoded .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; if c == '+' || c == '$' || c == '%' || c == '/' { let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; 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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } '$' => { // $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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } '%' => { // %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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else if ('F'..='J').contains(&next) { decodedChar = char::from_u32(next as u32 - 11) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else if ('K'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 + 16) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else if ('P'..='T').contains(&next) { decodedChar = char::from_u32(next as u32 + 43) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else if next == 'U' { decodedChar = 0 as char; } else if next == 'V' { @@ -374,18 +374,18 @@ impl Code39Reader { } else if next == 'X' || next == 'Y' || next == 'Z' { decodedChar = 127 as char; } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } '/' => { // /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::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } _ => {} diff --git a/src/oned/code_39_writer.rs b/src/oned/code_39_writer.rs index c7bc102..a929ce7 100644 --- a/src/oned/code_39_writer.rs +++ b/src/oned/code_39_writer.rs @@ -33,9 +33,9 @@ impl OneDimensionalCodeWriter for Code39Writer { let mut contents = contents.to_owned(); let mut length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested contents should be less than 80 digits long, but got {length}" - )))); + ))); } let mut i = 0; @@ -47,14 +47,14 @@ impl OneDimensionalCodeWriter for Code39Writer { contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) .is_none() { contents = Self::tryToConvertToExtendedMode(&contents)?; length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(Some(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)")))); + return Err(Exceptions::illegalArgument(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)"))); } break; } @@ -70,7 +70,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::IndexOutOfBoundsException(None))?) else { + let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?) else { continue; }; Self::toIntArray( @@ -117,58 +117,58 @@ impl Code39Writer { extendedContent.push('$'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 1)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character < ' ' { extendedContent.push('%'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 27)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= ',' || character == '/' || character == ':' { extendedContent.push('/'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 33)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= '9' { extendedContent.push( char::from_u32('0' as u32 + (character as u32 - 48)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= '?' { extendedContent.push('%'); extendedContent.push( char::from_u32('F' as u32 + (character as u32 - 59)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= 'Z' { extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 65)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= '_' { extendedContent.push('%'); extendedContent.push( char::from_u32('K' as u32 + (character as u32 - 91)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= 'z' { extendedContent.push('+'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 97)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character as u32 <= 127 { extendedContent.push('%'); extendedContent.push( char::from_u32('P' as u32 + (character as u32 - 123)) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(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 5f73fcb..ed7235f 100644 --- a/src/oned/code_93_reader.rs +++ b/src/oned/code_93_reader.rs @@ -63,7 +63,7 @@ impl OneDReader for Code93Reader { one_d_reader::recordPattern(row, nextStart, &mut theCounters)?; let pattern = Self::toPattern(&theCounters); if pattern < 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -92,12 +92,12 @@ impl OneDReader for Code93Reader { // Should be at least one more black module if nextStart == end || !row.get(nextStart) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if self.decodeRowRXingResult.chars().count() < 2 { // false positive -- need at least 2 checksum digits - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Self::checkChecksums(&self.decodeRowRXingResult)?; @@ -191,7 +191,7 @@ impl Code93Reader { isWhite = !isWhite; } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn toPattern(counters: &[u32; 6]) -> i32 { @@ -221,7 +221,7 @@ impl Code93Reader { return Ok(Self::ALPHABET[i]); } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn decodeExtended(encoded: &str) -> Result { @@ -234,52 +234,52 @@ impl Code93Reader { let c = encoded .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; if ('a'..='d').contains(&c) { if i >= length - 1 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; 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::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 + 32).ok_or(Exceptions::parseEmpty())?; } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } '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::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 - 64).ok_or(Exceptions::parseEmpty())?; } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } '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::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 - 38).ok_or(Exceptions::parseEmpty())?; } else if ('F'..='J').contains(&next) { // %F to %J map to ; < = > ? - decodedChar = char::from_u32(next as u32 - 11) - .ok_or(Exceptions::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 - 11).ok_or(Exceptions::parseEmpty())?; } else if ('K'..='O').contains(&next) { // %K to %O map to [ \ ] ^ _ - decodedChar = char::from_u32(next as u32 + 16) - .ok_or(Exceptions::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 + 16).ok_or(Exceptions::parseEmpty())?; } else if ('P'..='T').contains(&next) { // %P to %T map to { | } ~ DEL - decodedChar = char::from_u32(next as u32 + 43) - .ok_or(Exceptions::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 + 43).ok_or(Exceptions::parseEmpty())?; } 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::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } '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::ParseException(None))?; + decodedChar = + char::from_u32(next as u32 - 32).ok_or(Exceptions::parseEmpty())?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } _ => {} @@ -342,7 +342,7 @@ impl Code93Reader { result .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) .map_or_else(|| -1_i32, |v| v as i32); weight += 1; @@ -353,10 +353,10 @@ impl Code93Reader { if result .chars() .nth(checkPosition) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? != Self::ALPHABET[(total as usize) % 47] { - Err(Exceptions::ChecksumException(None)) + Err(Exceptions::checksumEmpty()) } else { Ok(()) } diff --git a/src/oned/code_93_writer.rs b/src/oned/code_93_writer.rs index be3b7ae..06905c7 100644 --- a/src/oned/code_93_writer.rs +++ b/src/oned/code_93_writer.rs @@ -35,7 +35,7 @@ impl OneDimensionalCodeWriter for Code93Writer { let mut contents = Self::convertToExtended(contents)?; let length = contents.chars().count(); if length > 80 { - return Err(Exceptions::IllegalArgumentException(Some(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" )))); + return Err(Exceptions::illegalArgument(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 @@ -48,7 +48,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::IndexOutOfBoundsException(None))?) else {panic!("alphabet")}; + let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?) else {panic!("alphabet")}; pos += Self::appendPattern( &mut result, pos, @@ -65,7 +65,7 @@ impl OneDimensionalCodeWriter for Code93Writer { Code93Reader::ALPHABET_STRING .chars() .nth(check1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ); let check2 = Self::computeChecksumIndex(&contents, 15); @@ -157,14 +157,14 @@ impl Code93Writer { extendedContent.push('a'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - 1) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } 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::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character == ' ' || character == '$' || character == '%' || character == '+' { // space $ % + @@ -174,7 +174,7 @@ impl Code93Writer { extendedContent.push('c'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - '!' as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character <= '9' { extendedContent.push(character); @@ -186,7 +186,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('F' as u32 + character as u32 - ';' as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character == '@' { // @: (%)V @@ -199,7 +199,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('K' as u32 + character as u32 - '[' as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if character == '`' { // `: (%)W @@ -209,19 +209,19 @@ impl Code93Writer { extendedContent.push('d'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - 'a' as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } 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::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(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 809cb54..c5eaf3a 100644 --- a/src/oned/ean_13_reader.rs +++ b/src/oned/ean_13_reader.rs @@ -66,7 +66,7 @@ impl UPCEANReader for EAN13Reader { )?; resultString.push( char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -90,8 +90,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::ParseException(None))?, + char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -154,12 +153,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::ParseException(None))?, + char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parseEmpty())?, ); return Ok(()); } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index 26a0942..f585dc6 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -45,15 +45,15 @@ impl OneDimensionalCodeWriter for EAN13Writer { } 13 => { if !reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Contents do not pass checksum".to_owned(), - ))); + )); } } _ => { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested contents should be 12 or 13 digits long, but got {length}" - )))) + ))) } } @@ -62,9 +62,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; + .ok_or(Exceptions::parseEmpty())? as usize; let parities = EAN13Reader::FIRST_DIGIT_ENCODINGS[firstDigit]; let mut result = [false; CODE_WIDTH]; let mut pos = 0; @@ -79,9 +79,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; + .ok_or(Exceptions::parseEmpty())? as usize; if (parities >> (6 - i) & 1) == 1 { digit += 10; } @@ -100,9 +100,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; + .ok_or(Exceptions::parseEmpty())? as usize; pos += EAN13Writer::appendPattern( &mut result, diff --git a/src/oned/ean_8_reader.rs b/src/oned/ean_8_reader.rs index 5e20ab3..8d5e652 100644 --- a/src/oned/ean_8_reader.rs +++ b/src/oned/ean_8_reader.rs @@ -53,8 +53,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::ParseException(None))?, + char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -71,8 +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::ParseException(None))?, + char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; diff --git a/src/oned/ean_8_writer.rs b/src/oned/ean_8_writer.rs index e329d46..3191bd4 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -55,15 +55,15 @@ impl OneDimensionalCodeWriter for EAN8Writer { } 8 => { if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Contents do not pass checksum".to_owned(), - ))); + )); } } _ => { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested contents should be 7 or 8 digits long, but got {length}" - )))) + ))) } } @@ -80,10 +80,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? - as usize; + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize; pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], false) as usize; } @@ -96,10 +95,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? - as usize; + .ok_or(Exceptions::indexOutOfBoundsEmpty())? 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 0f13089..cadaa45 100644 --- a/src/oned/itf_reader.rs +++ b/src/oned/itf_reader.rs @@ -140,7 +140,7 @@ impl OneDReader for ITFReader { lengthOK = true; } if !lengthOK { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let mut resultObject = RXingResult::new( @@ -195,13 +195,11 @@ impl ITFReader { } let mut bestMatch = self.decodeDigit(&counterBlack)?; - resultString.push( - char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::ParseException(None))?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parseEmpty())?); bestMatch = self.decodeDigit(&counterWhite)?; - resultString.push( - char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::ParseException(None))?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parseEmpty())?); payloadStart += counterDigitPair.iter().sum::() as usize; } @@ -262,7 +260,7 @@ impl ITFReader { if quietCount != 0 { // Unable to find the necessary number of quiet zone pixels. - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } else { Ok(()) } @@ -279,7 +277,7 @@ impl ITFReader { let width = row.getSize(); let endStart = row.getNextSet(0); if endStart == width { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(endStart) @@ -374,7 +372,7 @@ impl ITFReader { isWhite = !isWhite; } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** @@ -403,7 +401,7 @@ impl ITFReader { if bestMatch >= 0 { Ok(bestMatch as u32 % 10) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } } diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index 2363d25..57d14d2 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -32,14 +32,14 @@ impl OneDimensionalCodeWriter for ITFWriter { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { let length = contents.chars().count(); if length % 2 != 0 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "The length of the input should be even".to_owned(), - ))); + )); } if length > 80 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested contents should be less than 80 digits long, but got {length}" - )))); + ))); } Self::checkNumeric(contents)?; @@ -51,15 +51,15 @@ impl OneDimensionalCodeWriter for ITFWriter { let one = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; + .ok_or(Exceptions::parseEmpty())? as usize; let two = contents .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; + .ok_or(Exceptions::parseEmpty())? 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 8248e44..5bdc70e 100644 --- a/src/oned/multi_format_one_d_reader.rs +++ b/src/oned/multi_format_one_d_reader.rs @@ -46,7 +46,7 @@ impl OneDReader for MultiFormatOneDReader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } impl MultiFormatOneDReader { @@ -168,7 +168,7 @@ impl Reader for MultiFormatOneDReader { Ok(result) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/oned/multi_format_upc_ean_reader.rs b/src/oned/multi_format_upc_ean_reader.rs index 25d5a3a..768d868 100644 --- a/src/oned/multi_format_upc_ean_reader.rs +++ b/src/oned/multi_format_upc_ean_reader.rs @@ -134,7 +134,7 @@ impl OneDReader for MultiFormatUPCEANReader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } @@ -200,7 +200,7 @@ impl Reader for MultiFormatUPCEANReader { Ok(result) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 50d7e40..0ec8f3d 100644 --- a/src/oned/one_d_code_writer.rs +++ b/src/oned/one_d_code_writer.rs @@ -100,9 +100,9 @@ pub trait OneDimensionalCodeWriter: Writer { */ fn checkNumeric(contents: &str) -> Result<(), Exceptions> { if !NUMERIC.is_match(contents) { - Err(Exceptions::IllegalArgumentException(Some( + Err(Exceptions::illegalArgument( "Input should only contain digits 0-9".to_owned(), - ))) + )) } else { Ok(()) } @@ -163,29 +163,29 @@ impl Writer for L { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Found empty contents".to_owned(), - ))); + )); } if width < 0 || height < 0 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Negative size is not allowed. Input: {width}x{height}" - )))); + ))); } if let Some(supportedFormats) = self.getSupportedWriteFormats() { if !supportedFormats.contains(format) { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Can only encode {supportedFormats:?}, but got {format:?}" - )))); + ))); } } let mut sidesMargin = self.getDefaultMargin(); if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) { - sidesMargin = margin.parse::().map_err(|e| { - Exceptions::IllegalArgumentException(Some(format!("couldnt parse {margin}: {e}"))) - })?; + sidesMargin = margin + .parse::() + .map_err(|e| Exceptions::illegalArgument(format!("couldnt parse {margin}: {e}")))?; } let code = self.encode_oned_with_hints(contents, hints)?; diff --git a/src/oned/one_d_reader.rs b/src/oned/one_d_reader.rs index fd0adcc..ae96948 100644 --- a/src/oned/one_d_reader.rs +++ b/src/oned/one_d_reader.rs @@ -131,7 +131,7 @@ pub trait OneDReader: Reader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** @@ -218,7 +218,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu let end = row.getSize(); if start >= end { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut isWhite = !row.get(start); @@ -241,7 +241,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. if !(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end)) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(()) } @@ -263,7 +263,7 @@ pub fn recordPatternInReverse( } } if numTransitionsLeft >= 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } recordPattern(row, start + 1, counters)?; diff --git a/src/oned/rss/abstract_rss_reader.rs b/src/oned/rss/abstract_rss_reader.rs index 5e2ee2d..ec086e3 100644 --- a/src/oned/rss/abstract_rss_reader.rs +++ b/src/oned/rss/abstract_rss_reader.rs @@ -38,7 +38,7 @@ pub trait AbstractRSSReaderTrait: OneDReader { return Ok(value as u32); } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index b183bd9..a3ebc7a 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -50,23 +50,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::ParseException(None))? - != ' ' - { - return Err(Exceptions::IllegalStateException(Some( - "space expected".to_owned(), - ))); + if dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())? != ' ' { + return Err(Exceptions::illegalState("space expected".to_owned())); } continue; } - let currentChar = dotsAndXs - .chars() - .nth(i) - .ok_or(Exceptions::ParseException(None))?; + let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())?; if currentChar == 'X' || currentChar == 'x' { binary.set(counter); } @@ -92,7 +82,7 @@ pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result( _ => {} } - Err(Exceptions::IllegalStateException(Some(format!( + Err(Exceptions::illegalState(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 4e487d4..e4026c0 100644 --- a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01392xDecoder<'_> {} impl AbstractExpandedDecoder for AI01392xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::NotFoundException(None)); + return Err(crate::Exceptions::notFoundEmpty()); } 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 d6dbd9b..29dd58b 100644 --- a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs @@ -39,7 +39,7 @@ impl AI01decoder for AI01393xDecoder<'_> {} impl AbstractExpandedDecoder for AI01393xDecoder<'_> { fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { - return Err(crate::Exceptions::NotFoundException(None)); + return Err(crate::Exceptions::notFoundEmpty()); } 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 ab25f1f..38138c9 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs @@ -57,7 +57,7 @@ impl AbstractExpandedDecoder for AI013x0x1xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE + Self::DATE_SIZE { - return Err(crate::Exceptions::NotFoundException(None)); + return Err(crate::Exceptions::notFoundEmpty()); } 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 0c70233..5058863 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs @@ -53,7 +53,7 @@ impl AbstractExpandedDecoder for AI013x0xDecoder<'_> { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE { - return Err(crate::Exceptions::NotFoundException(None)); + return Err(crate::Exceptions::notFoundEmpty()); } 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 ed32120..8489133 100644 --- a/src/oned/rss/expanded/decoders/decoded_numeric.rs +++ b/src/oned/rss/expanded/decoders/decoded_numeric.rs @@ -51,7 +51,7 @@ impl DecodedNumeric { if /*firstDigit < 0 ||*/ firstDigit > 10 || /*secondDigit < 0 ||*/ secondDigit > 10 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } Ok(Self { diff --git a/src/oned/rss/expanded/decoders/field_parser.rs b/src/oned/rss/expanded/decoders/field_parser.rs index e38a856..de5a4a0 100644 --- a/src/oned/rss/expanded/decoders/field_parser.rs +++ b/src/oned/rss/expanded/decoders/field_parser.rs @@ -145,7 +145,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result Result Result Result Result { if rawInformation.chars().count() < aiSize { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let ai: String = rawInformation.chars().take(aiSize).collect(); if rawInformation.chars().count() < aiSize + fieldSize { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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 4524de2..e1aeabd 100644 --- a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs +++ b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs @@ -199,7 +199,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if let Some(r) = result.getDecodedInformation() { Ok(r.clone()) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } @@ -345,8 +345,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::ParseException(None))?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parseEmpty())?, )); } @@ -355,14 +354,14 @@ impl<'a> GeneralAppIdDecoder<'_> { if (64..90).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, - char::from_u32(sevenBitValue + 1).ok_or(Exceptions::ParseException(None))?, + char::from_u32(sevenBitValue + 1).ok_or(Exceptions::parseEmpty())?, )); } if (90..116).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, - char::from_u32(sevenBitValue + 7).ok_or(Exceptions::ParseException(None))?, + char::from_u32(sevenBitValue + 7).ok_or(Exceptions::parseEmpty())?, )); } @@ -389,7 +388,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 250 => '?', 251 => '_', 252 => ' ', - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), }; Ok(DecodedChar::new(pos + 8, c)) @@ -424,8 +423,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::ParseException(None))?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parseEmpty())?, )); } @@ -434,7 +432,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if (32..58).contains(&sixBitValue) { return Ok(DecodedChar::new( pos + 6, - char::from_u32(sixBitValue + 33).ok_or(Exceptions::ParseException(None))?, + char::from_u32(sixBitValue + 33).ok_or(Exceptions::parseEmpty())?, )); } @@ -445,9 +443,9 @@ impl<'a> GeneralAppIdDecoder<'_> { 61 => '.', 62 => '/', _ => { - return Err(Exceptions::IllegalStateException(Some(format!( + return Err(Exceptions::illegalState(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 c6381cd..d0f48b7 100644 --- a/src/oned/rss/expanded/rss_expanded_reader.rs +++ b/src/oned/rss/expanded/rss_expanded_reader.rs @@ -227,7 +227,7 @@ impl Reader for RSSExpandedReader { Ok(result) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } } @@ -297,9 +297,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::IllegalStateException(None))); + return Err(to_add_res.err().unwrap_or(Exceptions::illegalStateEmpty())); } else { // exit this loop when retrieveNextPair() fails and throws done = true; @@ -331,7 +329,7 @@ impl RSSExpandedReader { // } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn checkRows(&mut self, reverse: bool) -> Option> { @@ -378,7 +376,7 @@ impl RSSExpandedReader { let row = self .rows .get(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; self.pairs.clear(); for collectedRow in &collectedRows.clone() { // for (ExpandedRow collectedRow : collectedRows) { @@ -406,7 +404,7 @@ impl RSSExpandedReader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /// Whether the pairs form a valid find pattern sequence, @@ -537,24 +535,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::illegalStateEmpty())?; let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?; let resultingString = decoder.parseInformation()?; let firstPoints = pairs .get(0) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .getFinderPattern() .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getRXingResultPoints(); let lastPoints = pairs .last() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .getFinderPattern() .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getRXingResultPoints(); let mut result = RXingResult::new( @@ -653,9 +651,7 @@ impl RSSExpandedReader { let leftChar = self.decodeDataCharacter( row, - pattern - .as_ref() - .ok_or(Exceptions::NotFoundException(None))?, + pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?, isOddPattern, true, )?; @@ -663,18 +659,16 @@ impl RSSExpandedReader { if !previousPairs.is_empty() && previousPairs .last() - .ok_or(Exceptions::NotFoundException(None))? + .ok_or(Exceptions::notFoundEmpty())? .mustBeLast() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let rightChar = self .decodeDataCharacter( row, - pattern - .as_ref() - .ok_or(Exceptions::NotFoundException(None))?, + pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?, isOddPattern, false, ) @@ -706,11 +700,11 @@ impl RSSExpandedReader { } else { let lastPair = previousPairs .last() - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; rowOffset = lastPair .getFinderPattern() .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getStartEnd()[1] as i32; } let mut searchingEvenPair = previousPairs.len() % 2 != 0; @@ -762,7 +756,7 @@ impl RSSExpandedReader { isWhite = !isWhite; } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn reverseCounters(counters: &mut [u32]) { @@ -859,7 +853,7 @@ impl RSSExpandedReader { let expectedElementWidth: f32 = (pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) as f32 / 15.0; if (elementWidth - expectedElementWidth).abs() / expectedElementWidth > 0.3 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } for (i, counter) in counters.iter().enumerate() { @@ -868,12 +862,12 @@ impl RSSExpandedReader { let mut count = (value + 0.5) as i32; // Round if count < 1 { if value < 0.3 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } count = 1; } else if count > 8 { if value > 8.7 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } count = 8; } @@ -913,7 +907,7 @@ impl RSSExpandedReader { let checksumPortion = oddChecksumPortion + evenChecksumPortion; if (oddSum & 0x01) != 0 || !(4..=13).contains(&oddSum) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let group = ((13 - oddSum) / 2) as usize; @@ -961,12 +955,12 @@ impl RSSExpandedReader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } decrementEven = true; } @@ -974,12 +968,12 @@ impl RSSExpandedReader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } incrementEven = true; } @@ -987,7 +981,7 @@ impl RSSExpandedReader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // Both bad if oddSum < evenSum { @@ -998,16 +992,16 @@ impl RSSExpandedReader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } - _ => return Err(Exceptions::NotFoundException(None)), + _ => return Err(Exceptions::notFoundEmpty()), } if incrementOdd { if decrementOdd { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -1016,7 +1010,7 @@ impl RSSExpandedReader { } if incrementEven { if decrementEven { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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 1bf5ff8..5adddd4 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::IllegalStateException(None)); + .ok_or(Exceptions::illegalStateEmpty()); } } } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } impl Reader for RSS14Reader { @@ -126,7 +126,7 @@ impl Reader for RSS14Reader { Ok(result) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } } @@ -343,7 +343,7 @@ impl RSS14Reader { if outsideChar { if (oddSum & 0x01) != 0 || !(4..=12).contains(&oddSum) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let group = ((12 - oddSum) / 2) as usize; let oddWidest = Self::OUTSIDE_ODD_WIDEST[group]; @@ -358,7 +358,7 @@ impl RSS14Reader { )) } else { if (evenSum & 0x01) != 0 || !(4..=10).contains(&evenSum) { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let group = ((10 - evenSum) / 2) as usize; let oddWidest = Self::INSIDE_ODD_WIDEST[group]; @@ -417,7 +417,7 @@ impl RSS14Reader { isWhite = !isWhite; } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } fn parseFoundFinderPattern( @@ -518,12 +518,12 @@ impl RSS14Reader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } decrementEven = true; } @@ -531,12 +531,12 @@ impl RSS14Reader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } incrementEven = true; } @@ -544,7 +544,7 @@ impl RSS14Reader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // Both bad if oddSum < evenSum { @@ -555,15 +555,15 @@ impl RSS14Reader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } - _ => return Err(Exceptions::NotFoundException(None)), + _ => return Err(Exceptions::notFoundEmpty()), } if incrementOdd { if decrementOdd { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -572,7 +572,7 @@ impl RSS14Reader { } if incrementEven { if decrementEven { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Self::increment(&mut self.evenCounts, &self.evenRoundingErrors); } diff --git a/src/oned/upc_a_reader.rs b/src/oned/upc_a_reader.rs index a4904da..f0e7d1c 100644 --- a/src/oned/upc_a_reader.rs +++ b/src/oned/upc_a_reader.rs @@ -104,7 +104,7 @@ impl UPCAReader { Ok(upcaRXingResult) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } } diff --git a/src/oned/upc_a_writer.rs b/src/oned/upc_a_writer.rs index 339dd35..487f327 100644 --- a/src/oned/upc_a_writer.rs +++ b/src/oned/upc_a_writer.rs @@ -48,9 +48,9 @@ impl Writer for UPCAWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::UPC_A { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Can only encode UPC-A, but got {format:?}" - )))); + ))); } // Transform a UPC-A code into the equivalent EAN-13 code and write it that way self.0.encode_with_hints( diff --git a/src/oned/upc_e_reader.rs b/src/oned/upc_e_reader.rs index 248b85f..82173b9 100644 --- a/src/oned/upc_e_reader.rs +++ b/src/oned/upc_e_reader.rs @@ -51,7 +51,7 @@ impl UPCEANReader for UPCEReader { 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::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -69,7 +69,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::illegalArgumentEmpty())?, ) } @@ -133,17 +133,16 @@ impl UPCEReader { resultString.insert( 0, char::from_u32('0' as u32 + numSys as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); resultString.push( - char::from_u32('0' as u32 + d as u32) - .ok_or(Exceptions::ParseException(None))?, + char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parseEmpty())?, ); return Ok(()); } } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index f88568a..9a4bf2c 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -46,24 +46,24 @@ 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::IllegalArgumentException(None))?, + .ok_or(Exceptions::illegalArgumentEmpty())?, )?; contents.push_str(&check.to_string()); } 8 => { if !reader.checkStandardUPCEANChecksum( &upc_e_reader::convertUPCEtoUPCA(&contents) - .ok_or(Exceptions::IllegalArgumentException(None))?, + .ok_or(Exceptions::illegalArgumentEmpty())?, )? { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Contents do not pass checksum".to_owned(), - ))); + )); } } _ => { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Requested contents should be 7 or 8 digits long, but got {length}" - )))) + ))) } } @@ -72,21 +72,21 @@ impl OneDimensionalCodeWriter for UPCEWriter { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; //Character.digit(contents.charAt(0), 10); + .ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(0), 10); if firstDigit != 0 && firstDigit != 1 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Number system must be 0 or 1".to_owned(), - ))); + )); } let checkDigit = contents .chars() .nth(7) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; //Character.digit(contents.charAt(7), 10); + .ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(7), 10); let parities = UPCEReader::NUMSYS_AND_CHECK_DIGIT_PATTERNS[firstDigit][checkDigit]; let mut result = [false; CODE_WIDTH]; @@ -98,9 +98,9 @@ impl OneDimensionalCodeWriter for UPCEWriter { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? .to_digit(10) - .ok_or(Exceptions::ParseException(None))? as usize; //Character.digit(contents.charAt(i), 10); + .ok_or(Exceptions::parseEmpty())? 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 0ab38ab..28c5ca6 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 { )?; resultString.push( char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -105,15 +105,16 @@ impl UPCEANExtension2Support { } if resultString.chars().count() != 2 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } - if resultString.parse::().map_err(|e| { - Exceptions::ParseException(Some(format!("could not parse {resultString}: {e}"))) - })? % 4 + if resultString + .parse::() + .map_err(|e| Exceptions::parse(format!("could not parse {resultString}: {e}")))? + % 4 != checkParity { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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 8bbbaf8..a314e2e 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 { )?; resultString.push( char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); rowOffset += counters.iter().sum::() as usize; @@ -105,15 +105,14 @@ impl UPCEANExtension5Support { } if resultString.chars().count() != 5 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let checkDigit = Self::determineCheckDigit(lgPatternFound)?; - if Self::extensionChecksum(resultString) - .ok_or(Exceptions::IllegalArgumentException(None))? + if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgumentEmpty())? != checkDigit as u32 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(rowOffset as u32) @@ -148,7 +147,7 @@ impl UPCEANExtension5Support { return Ok(d); } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** diff --git a/src/oned/upc_ean_reader.rs b/src/oned/upc_ean_reader.rs index 60d9a72..806304b 100644 --- a/src/oned/upc_ean_reader.rs +++ b/src/oned/upc_ean_reader.rs @@ -182,18 +182,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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let resultString = result; // UPC/EAN should never be less than 8 chars anyway if resultString.chars().count() < 8 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } if !self.checkChecksum(&resultString)? { - return Err(Exceptions::ChecksumException(None)); + return Err(Exceptions::checksumEmpty()); } let left = (startGuardRange[1] + startGuardRange[0]) as f32 / 2.0; @@ -241,7 +241,7 @@ pub trait UPCEANReader: OneDReader { } } if !valid { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } @@ -292,7 +292,7 @@ pub trait UPCEANReader: OneDReader { let char_in_question = s .chars() .nth(length - 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; let check = char_in_question.is_ascii_digit(); let check_against = &s[..length - 1]; //s.subSequence(0, length - 1); @@ -302,7 +302,7 @@ pub trait UPCEANReader: OneDReader { == if check { char_in_question .to_digit(10) - .ok_or(Exceptions::ParseException(None))? + .ok_or(Exceptions::parseEmpty())? } else { u32::MAX }) @@ -314,13 +314,13 @@ pub trait UPCEANReader: OneDReader { let mut i = length as isize - 1; while i >= 0 { // for (int i = length - 1; i >= 0; i -= 2) { - let digit = - (s.chars() - .nth(i as usize) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as i32) - - ('0' as i32); + let digit = (s + .chars() + .nth(i as usize) + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32) + - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } sum += digit; @@ -330,13 +330,13 @@ pub trait UPCEANReader: OneDReader { let mut i = length as isize - 2; while i >= 0 { // for (int i = length - 2; i >= 0; i -= 2) { - let digit = - (s.chars() - .nth(i as usize) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as i32) - - ('0' as i32); + let digit = (s + .chars() + .nth(i as usize) + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32) + - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } sum += digit; @@ -423,7 +423,7 @@ pub trait UPCEANReader: OneDReader { } } - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** @@ -460,7 +460,7 @@ pub trait UPCEANReader: OneDReader { if bestMatch >= 0 { Ok(bestMatch as usize) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/pdf417/decoder/bounding_box.rs b/src/pdf417/decoder/bounding_box.rs index 4cf5aca..05622a4 100644 --- a/src/pdf417/decoder/bounding_box.rs +++ b/src/pdf417/decoder/bounding_box.rs @@ -44,7 +44,7 @@ impl BoundingBox { let leftUnspecified = topLeft.is_none() || bottomLeft.is_none(); let rightUnspecified = topRight.is_none() || bottomRight.is_none(); if leftUnspecified && rightUnspecified { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let newTopLeft; @@ -53,21 +53,21 @@ impl BoundingBox { let newBottomRight; if leftUnspecified { - newTopRight = topRight.ok_or(Exceptions::IllegalStateException(None))?; - newBottomRight = bottomRight.ok_or(Exceptions::IllegalStateException(None))?; + newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?; + newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?; newTopLeft = RXingResultPoint::new(0.0, newTopRight.getY()); newBottomLeft = RXingResultPoint::new(0.0, newBottomRight.getY()); } else if rightUnspecified { - newTopLeft = topLeft.ok_or(Exceptions::IllegalStateException(None))?; - newBottomLeft = bottomLeft.ok_or(Exceptions::IllegalStateException(None))?; + newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?; + newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?; newTopRight = RXingResultPoint::new(image.getWidth() as f32 - 1.0, newTopLeft.getY()); newBottomRight = RXingResultPoint::new(image.getWidth() as f32 - 1.0, newBottomLeft.getY()); } else { - newTopLeft = topLeft.ok_or(Exceptions::IllegalStateException(None))?; - newTopRight = topRight.ok_or(Exceptions::IllegalStateException(None))?; - newBottomLeft = bottomLeft.ok_or(Exceptions::IllegalStateException(None))?; - newBottomRight = bottomRight.ok_or(Exceptions::IllegalStateException(None))?; + newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?; + newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?; + newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?; + newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?; } Ok(BoundingBox { @@ -104,17 +104,17 @@ impl BoundingBox { if leftBox.is_none() { return Ok(rightBox .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .clone()); } if rightBox.is_none() { return Ok(leftBox .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .clone()); } - let leftBox = leftBox.ok_or(Exceptions::IllegalStateException(None))?; - let rightBox = rightBox.ok_or(Exceptions::IllegalStateException(None))?; + let leftBox = leftBox.ok_or(Exceptions::illegalStateEmpty())?; + let rightBox = rightBox.ok_or(Exceptions::illegalStateEmpty())?; 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 a3c2cc3..522e3d2 100644 --- a/src/pdf417/decoder/decoded_bit_stream_parser.rs +++ b/src/pdf417/decoder/decoded_bit_stream_parser.rs @@ -122,7 +122,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { result.append_char( - char::from_u32(codewords[codeIndex]).ok_or(Exceptions::ParseException(None))?, + char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parseEmpty())?, ); codeIndex += 1; } @@ -149,7 +149,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result // Should not see these outside a macro block { - return Err(Exceptions::FormatException(None)) + return Err(Exceptions::formatEmpty()) } _ => { // Default to text compaction. During testing numerous barcodes @@ -164,7 +164,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result codewords[0] as usize { // we must have at least two bytes left for the segment index - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS]; for seq in segmentIndexArray @@ -204,7 +204,7 @@ pub fn decodeMacroBlock( resultMetadata.setSegmentIndex(parsed_int); } else { // too large; bad input? - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } // Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec @@ -221,7 +221,7 @@ pub fn decodeMacroBlock( } if fileId.chars().count() == 0 { // at least one fileId codeword is required (Annex H.2) - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } resultMetadata.setFileId(fileId); @@ -258,7 +258,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); }; resultMetadata.setSegmentCount(parsed_segment_count); } @@ -267,7 +267,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); }; resultMetadata.setTimestamp(parsed_timestamp); } @@ -276,7 +276,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); }; resultMetadata.setChecksum(parsed_checksum); } @@ -285,18 +285,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::FormatException(None)); + return Err(Exceptions::formatEmpty()); }; resultMetadata.setFileSize(parsed_file_size); } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } MACRO_PDF417_TERMINATOR => { codeIndex += 1; resultMetadata.setLastSegment(true); } - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } @@ -388,7 +388,7 @@ fn textCompaction( result, subMode, ) - .ok_or(Exceptions::IllegalStateException(None))?; + .ok_or(Exceptions::illegalStateEmpty())?; result.appendECI(codewords[codeIndex])?; codeIndex += 1; textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; @@ -770,18 +770,16 @@ fn numericCompaction( Remove leading 1 => RXingResult is 000213298174000 */ fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result { - let mut result = 0 - .to_biguint() - .ok_or(Exceptions::ArithmeticException(None))?; + let mut result = 0.to_biguint().ok_or(Exceptions::arithmeticEmpty())?; for i in 0..count { result += &EXP900[count - i - 1] * (codewords[i] .to_biguint() - .ok_or(Exceptions::ArithmeticException(None))?); + .ok_or(Exceptions::arithmeticEmpty())?); } let resultString = result.to_string(); if !resultString.starts_with('1') { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } Ok(resultString[1..].to_owned()) } diff --git a/src/pdf417/decoder/ec/error_correction.rs b/src/pdf417/decoder/ec/error_correction.rs index 791fe22..6c7dc59 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -103,7 +103,7 @@ pub fn decode( // for (int i = 0; i < errorLocations.length; i++) { let position = received.len() as isize - 1 - field.log(errorLocations[i])? as isize; if position < 0 { - return Err(Exceptions::ChecksumException(Some(file!().to_string()))); + return Err(Exceptions::checksum(file!().to_string())); } received[position as usize] = field.subtract(received[position as usize], errorMagnitudes[i]); @@ -140,7 +140,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::ChecksumException(Some(file!().to_string()))); + return Err(Exceptions::checksum(file!().to_string())); } r = rLastLast; let mut q = ModulusPoly::getZero(field); //field.getZero(); @@ -162,7 +162,7 @@ fn runEuclideanAlgorithm( let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::ChecksumException(Some(file!().to_string()))); + return Err(Exceptions::checksum(file!().to_string())); } let inverse = field.inverse(sigmaTildeAtZero)?; @@ -190,7 +190,7 @@ fn findErrorLocations( i += 1; } if e != numErrors { - return Err(Exceptions::ChecksumException(Some(file!().to_string()))); + return Err(Exceptions::checksum(file!().to_string())); } Ok(result) } diff --git a/src/pdf417/decoder/ec/modulus_gf.rs b/src/pdf417/decoder/ec/modulus_gf.rs index 539342b..f891dbb 100644 --- a/src/pdf417/decoder/ec/modulus_gf.rs +++ b/src/pdf417/decoder/ec/modulus_gf.rs @@ -77,7 +77,7 @@ impl ModulusGF { pub fn log(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::ArithmeticException(None)) + Err(Exceptions::arithmeticEmpty()) } else { Ok(self.logTable[a as usize]) } @@ -85,7 +85,7 @@ impl ModulusGF { pub fn inverse(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::ArithmeticException(None)) + Err(Exceptions::arithmeticEmpty()) } 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 7ac93bc..694c8f9 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -36,7 +36,7 @@ impl ModulusPoly { coefficients: Vec, ) -> Result { if coefficients.is_empty() { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } let orig_coefs = coefficients.clone(); let mut coefficients = coefficients; @@ -126,9 +126,9 @@ impl ModulusPoly { pub fn add(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "ModulusPolys do not have same ModulusGF field".to_owned(), - ))); + )); } if self.isZero() { return Ok(other); @@ -160,9 +160,9 @@ impl ModulusPoly { pub fn subtract(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "ModulusPolys do not have same ModulusGF field".to_owned(), - ))); + )); } if other.isZero() { return Ok(Rc::new(self.clone())); @@ -172,9 +172,9 @@ impl ModulusPoly { pub fn multiply(&self, other: Rc) -> Result, Exceptions> { if !(self.field == other.field) { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "ModulusPolys do not have same ModulusGF field".to_owned(), - ))); + )); } if self.isZero() || other.isZero() { return Ok(Self::getZero(self.field)); diff --git a/src/pdf417/decoder/pdf_417_scanning_decoder.rs b/src/pdf417/decoder/pdf_417_scanning_decoder.rs index a5c49fd..8198ae8 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // 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::IllegalStateException(None))? as i32; + .ok_or(Exceptions::illegalStateEmpty())? 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } barcodeMatrix01.setValue(calculatedNumberOfCodewords); } else if numberOfCodewords[0] != calculatedNumberOfCodewords @@ -508,7 +508,7 @@ fn createDecoderRXingResultFromAmbiguousValues( // // // } if ambiguousIndexCount.is_empty() { - return Err(Exceptions::ChecksumException(None)); + return Err(Exceptions::checksumEmpty()); } 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::ChecksumException(None)); + return Err(Exceptions::checksumEmpty()); } } } tries -= 1; } - Err(Exceptions::ChecksumException(None)) + Err(Exceptions::checksumEmpty()) } fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec> { @@ -845,7 +845,7 @@ fn decodeCodewords( erasures: &mut [u32], ) -> Result { if codewords.is_empty() { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } 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::ChecksumException(None)); + return Err(Exceptions::checksumEmpty()); } 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::FormatException(None)); + return Err(Exceptions::formatEmpty()); } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. let numberOfCodewords = codewords[0]; if numberOfCodewords > codewords.len() as u32 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } if numberOfCodewords == 0 { // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) if numECCodewords < codewords.len() as u32 { codewords[0] = codewords.len() as u32 - numECCodewords; } else { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } } Ok(()) diff --git a/src/pdf417/detector/pdf_417_detector.rs b/src/pdf417/detector/pdf_417_detector.rs index b747c32..bd49234 100644 --- a/src/pdf417/detector/pdf_417_detector.rs +++ b/src/pdf417/detector/pdf_417_detector.rs @@ -78,8 +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::NotFoundException(None))?; + let barcodeCoordinates = detect(multiple, &bitMatrix).ok_or(Exceptions::notFoundEmpty())?; 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 4f4b24f..3000a7d 100644 --- a/src/pdf417/encoder/compaction.rs +++ b/src/pdf417/encoder/compaction.rs @@ -40,8 +40,8 @@ impl TryFrom<&String> for Compaction { _ => {} } } - Err(Exceptions::FormatException(Some(format!( + Err(Exceptions::format(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 6f99a8c..406670d 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -161,7 +161,7 @@ impl PDF417 { pattern = CODEWORD_TABLE[cluster][fullCodewords .chars() .nth(idx) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize]; Self::encodeChar(pattern, 17, logic.getCurrentRowMut()); idx += 1; @@ -226,17 +226,17 @@ impl PDF417 { //2. step: construct data codewords if sourceCodeWords + errorCorrectionCodeWords + 1 > 929 { // +1 for symbol length CW - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(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::ParseException(None))?); + sb.push(char::from_u32(n).ok_or(Exceptions::parseEmpty())?); sb.push_str(&highLevel); for _i in 0..pad { - sb.push(char::from_u32(900).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(900).ok_or(Exceptions::parseEmpty())?); //PAD characters } let dataCodewords = sb; @@ -315,9 +315,9 @@ impl PDF417 { } } - dimension.ok_or(Exceptions::WriterException(Some( + dimension.ok_or(Exceptions::writer( "Unable to fit message in columns".to_owned(), - ))) + )) } /** diff --git a/src/pdf417/encoder/pdf_417_error_correction.rs b/src/pdf417/encoder/pdf_417_error_correction.rs index bf7522c..41d71c7 100644 --- a/src/pdf417/encoder/pdf_417_error_correction.rs +++ b/src/pdf417/encoder/pdf_417_error_correction.rs @@ -119,9 +119,9 @@ static EC_COEFFICIENTS: Lazy<[Vec; 9]> = Lazy::new(|| { */ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { if errorCorrectionLevel > 8 { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Error correction level must be between 0 and 8!".to_owned(), - ))); + )); } Ok(1 << (errorCorrectionLevel + 1)) } @@ -135,9 +135,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result Result { if n == 0 { - Err(Exceptions::IllegalArgumentException(Some( - "n must be > 0".to_owned(), - ))) + Err(Exceptions::illegalArgument("n must be > 0".to_owned())) } else if n <= 40 { Ok(2) } else if n <= 160 { @@ -147,9 +145,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result= 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::ParseException(None))?; + e[j] = char::from_u32((e[j - 1] as u32 + t3) % 929).ok_or(Exceptions::parseEmpty())?; j -= 1; } t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel as usize][0]) % 929; t3 = 929 - t2; - e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::ParseException(None))?; + e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::parseEmpty())?; } 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::ParseException(None))?; + e[j as usize] = + char::from_u32(929 - e[j as usize] as u32).ok_or(Exceptions::parseEmpty())?; } 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 4da0f17..2fb60cd 100644 --- a/src/pdf417/encoder/pdf_417_high_level_encoder.rs +++ b/src/pdf417/encoder/pdf_417_high_level_encoder.rs @@ -179,15 +179,13 @@ pub fn encodeHighLevel( ) -> Result { let mut encoding = encoding; if msg.is_empty() { - return Err(Exceptions::WriterException(Some( - "Empty message not allowed".to_owned(), - ))); + return Err(Exceptions::writer("Empty message not allowed".to_owned())); } if encoding.is_none() && !autoECI { for ch in msg.chars() { if ch as u32 > 255 { - return Err(Exceptions::WriterException(Some(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(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch))); } } } @@ -204,11 +202,11 @@ pub fn encodeHighLevel( } else if DEFAULT_ENCODING.name() != encoding .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .name() { if let Some(eci) = CharacterSetECI::getCharacterSetECI( - encoding.ok_or(Exceptions::IllegalStateException(None))?, + encoding.ok_or(Exceptions::illegalStateEmpty())?, ) { encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?; } @@ -230,7 +228,7 @@ pub fn encodeHighLevel( Compaction::BYTE => { let msgBytes = encoding .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .encode(&input.to_string(), encoding::EncoderTrap::Strict) .unwrap_or_default(); //input.to_string().getBytes(encoding); encodeBinary( @@ -242,7 +240,7 @@ pub fn encodeHighLevel( )?; } Compaction::NUMERIC => { - sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parseEmpty())?); encodeNumeric(&input, p, len as u32, &mut sb)?; } _ => { @@ -257,9 +255,7 @@ pub fn encodeHighLevel( } let n = determineConsecutiveDigitCount(&input, p)?; if n >= 13 { - sb.push( - char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::ParseException(None))?, - ); + sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parseEmpty())?); encodingMode = NUMERIC_COMPACTION; textSubMode = SUBMODE_ALPHA; //Reset after latch encodeNumeric(&input, p, n, &mut sb)?; @@ -268,10 +264,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::ParseException(None))?, - ); + sb.push(char::from_u32(LATCH_TO_TEXT).ok_or(Exceptions::parseEmpty())?); encodingMode = TEXT_COMPACTION; textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch } @@ -295,7 +288,7 @@ pub fn encodeHighLevel( .collect::(); if let Ok(enc_str) = encoding .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .encode(&str, encoding::EncoderTrap::Strict) { Some(enc_str) @@ -311,9 +304,7 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, 1, TEXT_COMPACTION, &mut sb)?; } else { encodeBinary( - bytes - .as_ref() - .ok_or(Exceptions::IllegalStateException(None))?, + bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?, 0, 1, TEXT_COMPACTION, @@ -326,14 +317,10 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, p + b, encodingMode, &mut sb)?; } else { encodeBinary( - bytes - .as_ref() - .ok_or(Exceptions::IllegalStateException(None))?, + bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?, 0, - bytes - .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? - .len() as u32, + bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?.len() + as u32, encodingMode, &mut sb, )?; @@ -385,8 +372,7 @@ fn encodeText( tmp.push(26 as char); //space } else { tmp.push( - char::from_u32(ch as u32 - 65) - .ok_or(Exceptions::ParseException(None))?, + char::from_u32(ch as u32 - 65).ok_or(Exceptions::parseEmpty())?, ); } } else if isAlphaLower(ch) { @@ -401,7 +387,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } } @@ -412,16 +398,12 @@ fn encodeText( tmp.push(26 as char); //space } else { tmp.push( - char::from_u32(ch as u32 - 97) - .ok_or(Exceptions::ParseException(None))?, + char::from_u32(ch as u32 - 97).ok_or(Exceptions::parseEmpty())?, ); } } else if isAlphaUpper(ch) { tmp.push(27 as char); //as - tmp.push( - char::from_u32(ch as u32 - 65) - .ok_or(Exceptions::ParseException(None))?, - ); + tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::parseEmpty())?); //space cannot happen here, it is also in "Lower" } else if isMixed(ch) { submode = SUBMODE_MIXED; @@ -431,7 +413,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } } @@ -440,7 +422,7 @@ fn encodeText( if isMixed(ch) { tmp.push( char::from_u32(MIXED[ch as usize] as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else if isAlphaUpper(ch) { submode = SUBMODE_ALPHA; @@ -462,7 +444,7 @@ fn encodeText( tmp.push(29 as char); //ps tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } } @@ -472,7 +454,7 @@ fn encodeText( if isPunctuation(ch) { tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); } else { submode = SUBMODE_ALPHA; @@ -497,20 +479,19 @@ fn encodeText( + tmp .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? - as u32, + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32, ) - .ok_or(Exceptions::ParseException(None))?; + .ok_or(Exceptions::parseEmpty())?; sb.push(h); } else { h = tmp .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?; + .ok_or(Exceptions::indexOutOfBoundsEmpty())?; } } if (len % 2) != 0 { - sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::parseEmpty())?); //ps } Ok(submode) @@ -602,11 +583,11 @@ fn encodeBinary( sb: &mut String, ) -> Result<(), Exceptions> { if count == 1 && startmode == TEXT_COMPACTION { - sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::parseEmpty())?); } else if (count % 6) == 0 { - sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::parseEmpty())?); } else { - sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::parseEmpty())?); } let mut idx = startpos; @@ -620,7 +601,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::ParseException(None))?; + *ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::parseEmpty())?; t /= 900; } sb.push_str(&chars.into_iter().rev().collect::()); @@ -644,8 +625,8 @@ fn encodeNumeric( ) -> Result<(), Exceptions> { let mut idx = 0; let mut tmp = String::with_capacity(count as usize / 3 + 1); - let NUM900: num::BigUint = num::BigUint::from(900_u16); //.ok_or(Exceptions::ParseException(None))?; - let NUM0: num::BigUint = num::BigUint::from(0_u8); //.ok_or(Exceptions::ParseException(None))?; + let NUM900: num::BigUint = num::BigUint::from(900_u16); //.ok_or(Exceptions::parseEmpty())?; + let NUM0: num::BigUint = num::BigUint::from(0_u8); //.ok_or(Exceptions::parseEmpty())?; // let num900: u128 = 900; // const NUM0: u128 = 0; @@ -662,17 +643,15 @@ fn encodeNumeric( .iter() .collect::() ); - // let mut bigint: u128 = part.parse().map_err(|_| Exceptions::ParseException(None))?; + // let mut bigint: u128 = part.parse().map_err(|_| Exceptions::parseEmpty())?; let mut bigint = num::BigUint::from_str(&part) - .map_err(|e| Exceptions::ParseException(Some(format!("issue parsing {part}: {e}"))))?; // part.parse().map_err(|_| Exceptions::ParseException(None))?; + .map_err(|e| Exceptions::parse(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::ParseException(Some(format!( - "erorr converting {bigint} to u32: {e}" - ))) + Exceptions::parse(format!("erorr converting {bigint} to u32: {e}")) })?) - .ok_or(Exceptions::ParseException(None))?, + .ok_or(Exceptions::parseEmpty())?, ); bigint /= &NUM900; @@ -818,15 +797,15 @@ fn determineConsecutiveBinaryCount( if !can_encode { if TypeId::of::() != TypeId::of::() { - return Err(Exceptions::IllegalStateException(Some( + return Err(Exceptions::illegalState( "expected NoECIInput type".to_owned(), - ))); + )); } let ch = input.charAt(idx)?; - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "Non-encodable character detected: {} (Unicode: {})", ch, ch as u32 - )))); + ))); } } idx += 1; @@ -836,19 +815,19 @@ fn determineConsecutiveBinaryCount( fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> { if (0..900).contains(&eci) { - sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::ParseException(None))?); - sb.push(char::from_u32(eci as u32).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32(eci as u32).ok_or(Exceptions::parseEmpty())?); } else if eci < 810900 { - sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::ParseException(None))?); - sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::ParseException(None))?); - sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::parseEmpty())?); } else if eci < 811800 { - sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::ParseException(None))?); - sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::ParseException(None))?); + sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::parseEmpty())?); } else { - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "ECI number not in valid range from 0..811799, but was {eci}" - )))); + ))); } Ok(()) } @@ -863,7 +842,7 @@ impl ECIInput for NoECIInput { self.0 .chars() .nth(index) - .ok_or(Exceptions::IndexOutOfBoundsException(None)) + .ok_or(Exceptions::indexOutOfBoundsEmpty()) } fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { diff --git a/src/pdf417/pdf_417_reader.rs b/src/pdf417/pdf_417_reader.rs index 25d0d4c..353f9a4 100644 --- a/src/pdf417/pdf_417_reader.rs +++ b/src/pdf417/pdf_417_reader.rs @@ -57,7 +57,7 @@ impl Reader for PDF417Reader { ) -> Result { let result = Self::decode(image, hints, false)?; if result.is_empty() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } Ok(result[0].clone()) } @@ -127,7 +127,7 @@ impl PDF417Reader { pdf417RXingResultMetadata .clone() .downcast::() - .map_err(|_| Exceptions::IllegalStateException(None))?, + .map_err(|_| Exceptions::illegalStateEmpty())?, ); result.putMetadata(RXingResultMetadataType::PDF417_EXTRA_METADATA, data); } diff --git a/src/pdf417/pdf_417_writer.rs b/src/pdf417/pdf_417_writer.rs index 5c03e69..e047898 100644 --- a/src/pdf417/pdf_417_writer.rs +++ b/src/pdf417/pdf_417_writer.rs @@ -59,9 +59,9 @@ impl Writer for PDF417Writer { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::PDF_417 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Can only encode PDF_417, but got {format}" - )))); + ))); } let mut encoder = PDF417::new(); @@ -149,7 +149,7 @@ impl PDF417Writer { let mut originalScale = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getScaledMatrix(1, aspectRatio); let mut rotated = false; if (height > width) != (originalScale[0].len() < originalScale.len()) { @@ -165,17 +165,16 @@ impl PDF417Writer { let mut scaledMatrix = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .getScaledMatrix(scale, scale * aspectRatio); if rotated { scaledMatrix = Self::rotateArray(&scaledMatrix); } return Self::bitMatrixFromBitArray(&scaledMatrix, margin) - .ok_or(Exceptions::IllegalStateException(None)); + .ok_or(Exceptions::illegalStateEmpty()); } - Self::bitMatrixFromBitArray(&originalScale, margin) - .ok_or(Exceptions::IllegalStateException(None)) + Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::illegalStateEmpty()) } /** diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index dd3a363..b2bd6f2 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -166,9 +166,9 @@ impl PlanarYUVLuminanceSource { inverted: bool, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Crop rectangle does not fit within image data.".to_owned(), - ))); + )); } let mut new_s: Self = Self { @@ -328,7 +328,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { self.invert, ) { Ok(new) => Ok(Box::new(new)), - Err(_err) => Err(Exceptions::UnsupportedOperationException(None)), + Err(_err) => Err(Exceptions::unsupportedOperationEmpty()), } } diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index ae8eb1c..5dcd990 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -36,9 +36,9 @@ impl BitMatrixParser { pub fn new(bit_matrix: BitMatrix) -> Result { let dimension = bit_matrix.getHeight(); if dimension < 21 || (dimension & 0x03) != 1 { - Err(Exceptions::FormatException(Some(format!( + Err(Exceptions::format(format!( "{dimension} < 21 || ({dimension} % 0x03) != 1" - )))) + ))) } else { Ok(Self { bitMatrix: bit_matrix, @@ -61,7 +61,7 @@ impl BitMatrixParser { return self .parsedFormatInfo .as_ref() - .ok_or(Exceptions::ParseException(None)); + .ok_or(Exceptions::parseEmpty()); } // Read top-left format info bits @@ -94,7 +94,7 @@ impl BitMatrixParser { self.parsedFormatInfo .as_ref() - .ok_or(Exceptions::FormatException(None)) + .ok_or(Exceptions::formatEmpty()) } /** @@ -146,7 +146,7 @@ impl BitMatrixParser { return Ok(theParsedVersion); } } - Err(Exceptions::FormatException(None)) + Err(Exceptions::formatEmpty()) } fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 { @@ -227,7 +227,7 @@ impl BitMatrixParser { } if resultOffset != version.getTotalCodewords() as usize { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } Ok(result) } diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index 8c364dd..5bc3066 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -55,7 +55,7 @@ impl DataBlock { ecLevel: ErrorCorrectionLevel, ) -> Result, Exceptions> { if rawCodewords.len() as u32 != version.getTotalCodewords() { - return Err(Exceptions::IllegalArgumentException(None)); + return Err(Exceptions::illegalArgumentEmpty()); } // 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 e4d77e4..5f89774 100755 --- a/src/qrcode/decoder/data_mask.rs +++ b/src/qrcode/decoder/data_mask.rs @@ -228,9 +228,9 @@ impl TryFrom for DataMask { 5 => Ok(DataMask::DATA_MASK_101), 6 => Ok(DataMask::DATA_MASK_110), 7 => Ok(DataMask::DATA_MASK_111), - _ => Err(Exceptions::IllegalArgumentException(Some(format!( + _ => Err(Exceptions::illegalArgument(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 f791e4f..635a63d 100644 --- a/src/qrcode/decoder/decoded_bit_stream_parser.rs +++ b/src/qrcode/decoder/decoded_bit_stream_parser.rs @@ -78,10 +78,10 @@ pub fn decode( } Mode::STRUCTURED_APPEND => { if bits.available() < 16 { - return Err(Exceptions::FormatException(Some(format!( + return Err(Exceptions::format(format!( "Mode::Structured append expected bits.available() < 16, found bits of {}", bits.available() - )))); + ))); } // sequence number and parity is added later to the result metadata // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue @@ -93,9 +93,7 @@ pub fn decode( let value = parseECIValue(&mut bits)?; currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value).ok(); if currentCharacterSetECI.is_none() { - return Err(Exceptions::FormatException(Some(format!( - "Value of {value} not valid" - )))); + return Err(Exceptions::format(format!("Value of {value} not valid"))); } } Mode::HANZI => { @@ -132,7 +130,7 @@ pub fn decode( currentCharacterSetECI, hints, )?, - _ => return Err(Exceptions::FormatException(None)), + _ => return Err(Exceptions::formatEmpty()), } } } @@ -181,7 +179,7 @@ fn decodeHanziSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -207,13 +205,11 @@ fn decodeHanziSegment( count -= 1; } - let gb_encoder = encoding::label::encoding_from_whatwg_label("GBK") - .ok_or(Exceptions::IllegalStateException(None))?; + let gb_encoder = + encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalStateEmpty())?; let encode_string = gb_encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| { - Exceptions::ParseException(Some(format!("unable to decode buffer {buffer:?}: {e}"))) - })?; + .map_err(|e| Exceptions::parse(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); Ok(()) } @@ -227,7 +223,7 @@ fn decodeKanjiSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -256,8 +252,7 @@ fn decodeKanjiSegment( let encoder = { let _ = currentCharacterSetECI; let _ = hints; - encoding::label::encoding_from_whatwg_label("SJIS") - .ok_or(Exceptions::FormatException(None))? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::formatEmpty())? }; #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -270,15 +265,12 @@ fn decodeKanjiSegment( encoding::all::ISO_8859_1 } } else { - encoding::label::encoding_from_whatwg_label("SJIS") - .ok_or(Exceptions::FormatException(None))? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::formatEmpty())? }; let encode_string = encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| { - Exceptions::ParseException(Some(format!("unable to decode buffer {buffer:?}: {e}"))) - })?; + .map_err(|e| Exceptions::parse(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); @@ -295,7 +287,7 @@ fn decodeByteSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if 8 * count > bits.available() { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let mut readBytes = vec![0u8; count]; @@ -311,8 +303,7 @@ fn decodeByteSegment( // give a hint. { #[cfg(not(feature = "allow_forced_iso_ied_18004_compliance"))] - StringUtils::guessCharset(&readBytes, hints) - .ok_or(Exceptions::IllegalStateException(None))? + StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalStateEmpty())? } #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -327,14 +318,14 @@ fn decodeByteSegment( CharacterSetECI::getCharset( currentCharacterSetECI .as_ref() - .ok_or(Exceptions::IllegalStateException(None))?, + .ok_or(Exceptions::illegalStateEmpty())?, ) }; let encode_string = if currentCharacterSetECI.is_some() && currentCharacterSetECI .as_ref() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? == &CharacterSetECI::Cp437 { { @@ -346,11 +337,7 @@ fn decodeByteSegment( } else { encoding .decode(&readBytes, encoding::DecoderTrap::Strict) - .map_err(|e| { - Exceptions::ParseException(Some(format!( - "unable to decode buffer {readBytes:?}: {e}" - ))) - })? + .map_err(|e| Exceptions::parse(format!("unable to decode buffer {readBytes:?}: {e}")))? }; result.push_str(&encode_string); @@ -361,13 +348,13 @@ fn decodeByteSegment( fn toAlphaNumericChar(value: u32) -> Result { if value as usize >= ALPHANUMERIC_CHARS.len() { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } ALPHANUMERIC_CHARS .chars() .nth(value as usize) - .ok_or(Exceptions::FormatException(None)) + .ok_or(Exceptions::formatEmpty()) } fn decodeAlphanumericSegment( @@ -381,7 +368,7 @@ fn decodeAlphanumericSegment( let mut count = count; while count > 1 { if bits.available() < 11 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let nextTwoCharsBits = bits.readBits(11)?; result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?); @@ -391,7 +378,7 @@ fn decodeAlphanumericSegment( if count == 1 { // special case: one character left if bits.available() < 6 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } result.push(toAlphaNumericChar(bits.readBits(6)?)?); } @@ -402,14 +389,14 @@ fn decodeAlphanumericSegment( if result .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? == '%' { if i < result.len() - 1 && result .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? + .ok_or(Exceptions::indexOutOfBoundsEmpty())? == '%' { // %% is rendered as % @@ -435,11 +422,11 @@ fn decodeNumericSegment( while count >= 3 { // Each 10 bits encodes three digits if bits.available() < 10 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let threeDigitsBits = bits.readBits(10)?; if threeDigitsBits >= 1000 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } result.push(toAlphaNumericChar(threeDigitsBits / 100)?); result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?); @@ -449,22 +436,22 @@ fn decodeNumericSegment( if count == 2 { // Two digits left over to read, encoded in 7 bits if bits.available() < 7 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let twoDigitsBits = bits.readBits(7)?; if twoDigitsBits >= 100 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } result.push(toAlphaNumericChar(twoDigitsBits / 10)?); result.push(toAlphaNumericChar(twoDigitsBits % 10)?); } else if count == 1 { // One digit left over to read if bits.available() < 4 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } let digitBits = bits.readBits(4)?; if digitBits >= 10 { - return Err(Exceptions::FormatException(None)); + return Err(Exceptions::formatEmpty()); } result.push(toAlphaNumericChar(digitBits)?); } @@ -489,5 +476,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result { return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes); } - Err(Exceptions::FormatException(None)) + Err(Exceptions::formatEmpty()) } diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index a43e8fd..b9137e8 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -47,9 +47,9 @@ impl ErrorCorrectionLevel { 1 => Ok(Self::L), 2 => Ok(Self::H), 3 => Ok(Self::Q), - _ => Err(Exceptions::IllegalArgumentException(Some(format!( + _ => Err(Exceptions::illegalArgument(format!( "{bits} is not a valid bit selection" - )))), + ))), } } @@ -109,8 +109,8 @@ impl FromStr for ErrorCorrectionLevel { return number_possible.try_into(); } - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "could not parse {s} into an ec level" - )))); + ))); } } diff --git a/src/qrcode/decoder/mode.rs b/src/qrcode/decoder/mode.rs index 1d927ae..9790f43 100644 --- a/src/qrcode/decoder/mode.rs +++ b/src/qrcode/decoder/mode.rs @@ -68,9 +68,7 @@ impl Mode { { Ok(Self::HANZI) } - _ => Err(Exceptions::IllegalArgumentException(Some(format!( - "{bits} is not valid" - )))), + _ => Err(Exceptions::illegalArgument(format!("{bits} is not valid"))), } } diff --git a/src/qrcode/decoder/qrcode_decoder.rs b/src/qrcode/decoder/qrcode_decoder.rs index 6076ae3..b7b10ab 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::ChecksumException(None))) + Err(ce.unwrap_or(Exceptions::checksumEmpty())) } } _ => Err(er), diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index 2528583..2710ce6 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -101,18 +101,16 @@ impl Version { dimension: u32, ) -> Result<&'static Version, Exceptions> { if dimension % 4 != 1 { - return Err(Exceptions::FormatException(Some( - "dimension incorrect".to_owned(), - ))); + return Err(Exceptions::format("dimension incorrect".to_owned())); } Self::getVersionForNumber((dimension - 17) / 4) } pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> { if !(1..=40).contains(&versionNumber) { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "version out of spec".to_owned(), - ))); + )); } Ok(&VERSIONS[versionNumber as usize - 1]) } @@ -140,7 +138,7 @@ impl Version { return Self::getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } /** diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index df3d59a..5619b3e 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -161,9 +161,9 @@ impl AlignmentPatternFinder { Ok(*(self .possibleCenters .get(0) - .ok_or(Exceptions::IndexOutOfBoundsException(None)))?) + .ok_or(Exceptions::indexOutOfBoundsEmpty()))?) } else { - Err(Exceptions::NotFoundException(None)) + Err(Exceptions::notFoundEmpty()) } } diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 0b93a8e..2c0ef0c 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -696,7 +696,7 @@ impl<'a> FinderPatternFinder<'_> { let startSize = self.possibleCenters.len(); if startSize < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } self.possibleCenters @@ -713,19 +713,19 @@ impl<'a> FinderPatternFinder<'_> { for i in 0..self.possibleCenters.len() { let Some(fpi) = self.possibleCenters.get(i) else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; let minModuleSize = fpi.getEstimatedModuleSize(); for j in (i + 1)..(self.possibleCenters.len() - 1) { let Some(fpj) = self.possibleCenters.get(j) else { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; 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::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); }; let maxModuleSize = fpk.getEstimatedModuleSize(); if maxModuleSize > minModuleSize * 1.4 { @@ -777,16 +777,16 @@ impl<'a> FinderPatternFinder<'_> { } if distortion == f64::MAX { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if bestPatterns[0].is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } - let p1 = bestPatterns[0].ok_or(Exceptions::NotFoundException(None))?; - let p2 = bestPatterns[1].ok_or(Exceptions::NotFoundException(None))?; - let p3 = bestPatterns[2].ok_or(Exceptions::NotFoundException(None))?; + let p1 = bestPatterns[0].ok_or(Exceptions::notFoundEmpty())?; + let p2 = bestPatterns[1].ok_or(Exceptions::notFoundEmpty())?; + let p3 = bestPatterns[2].ok_or(Exceptions::notFoundEmpty())?; Ok([p1, p2, p3]) } diff --git a/src/qrcode/detector/qrcode_detector.rs b/src/qrcode/detector/qrcode_detector.rs index 6110b92..9010000 100644 --- a/src/qrcode/detector/qrcode_detector.rs +++ b/src/qrcode/detector/qrcode_detector.rs @@ -105,7 +105,7 @@ impl<'a> Detector<'_> { let moduleSize = self.calculateModuleSize(topLeft, topRight, bottomLeft); if moduleSize < 1.0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let dimension = Self::computeDimension(topLeft, topRight, bottomLeft, moduleSize)?; let provisionalVersion = Version::getProvisionalVersionForDimension(dimension)?; @@ -147,7 +147,7 @@ impl<'a> Detector<'_> { alignmentPattern.as_ref(), dimension, ) - .ok_or(Exceptions::NotFoundException(None))?; + .ok_or(Exceptions::notFoundEmpty())?; let bits = Detector::sampleGrid(self.image, &transform, dimension)?; @@ -160,7 +160,7 @@ impl<'a> Detector<'_> { if alignmentPattern.is_some() { points.push( alignmentPattern - .ok_or(Exceptions::NotFoundException(None))? + .ok_or(Exceptions::notFoundEmpty())? .into_rxing_result_point(), ) } @@ -241,7 +241,7 @@ impl<'a> Detector<'_> { match dimension & 0x03 { 0 => dimension += 1, 2 => dimension -= 1, - 3 => return Err(Exceptions::NotFoundException(None)), + 3 => return Err(Exceptions::notFoundEmpty()), _ => {} } Ok(dimension as u32) @@ -428,13 +428,13 @@ impl<'a> Detector<'_> { let alignmentAreaLeftX = 0.max(estAlignmentX as i32 - allowance as i32) as u32; let alignmentAreaRightX = (self.image.getWidth() - 1).min(estAlignmentX + allowance); if ((alignmentAreaRightX - alignmentAreaLeftX) as f32) < overallEstModuleSize * 3.0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let alignmentAreaTopY = 0.max(estAlignmentY as i32 - allowance as i32) as u32; let alignmentAreaBottomY = (self.image.getHeight() - 1).min(estAlignmentY + allowance); if alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize as u32 * 3 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } let mut alignmentFinder = AlignmentPatternFinder::new( diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index 80b660c..e6c4a22 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -174,9 +174,9 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "Invalid mask pattern: {maskPattern}" - )))) + ))) } }; // switch (maskPattern) { diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index f8de1a7..3c20946 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -278,11 +278,11 @@ pub fn embedDataBits( } // All bits should be consumed. if bitIndex != dataBits.getSize() { - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "Not all bits consumed: {}/{}", bitIndex, dataBits.getSize() - )))); + ))); } Ok(()) } @@ -323,9 +323,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::IllegalArgumentException(Some( - "0 polynomial".to_owned(), - ))); + return Err(Exceptions::illegalArgument("0 polynomial".to_owned())); } let mut value = value; // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 @@ -349,9 +347,7 @@ pub fn makeTypeInfoBits( bits: &mut BitArray, ) -> Result<(), Exceptions> { if !QRCode::isValidMaskPattern(maskPattern as i32) { - return Err(Exceptions::WriterException(Some( - "Invalid mask pattern".to_owned(), - ))); + return Err(Exceptions::writer("Invalid mask pattern".to_owned())); } let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern; bits.appendBits(typeInfo, 5)?; @@ -365,10 +361,10 @@ pub fn makeTypeInfoBits( if bits.getSize() != 15 { // Just in case. - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "should not happen but we got: {}", bits.getSize() - )))); + ))); } Ok(()) } @@ -382,10 +378,10 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(), if bits.getSize() != 18 { // Just in case. - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "should not happen but we got: {}", bits.getSize() - )))); + ))); } Ok(()) } @@ -415,7 +411,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) { // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<(), Exceptions> { if matrix.get(8, matrix.getHeight() - 8) == 0 { - return Err(Exceptions::WriterException(None)); + return Err(Exceptions::writerEmpty()); } matrix.set(8, matrix.getHeight() - 8, 1); Ok(()) @@ -428,7 +424,7 @@ pub fn embedHorizontalSeparationPattern( ) -> Result<(), Exceptions> { for x in 0..8 { if !isEmpty(matrix.get(xStart + x, yStart)) { - return Err(Exceptions::WriterException(None)); + return Err(Exceptions::writerEmpty()); } matrix.set(xStart + x, yStart, 0); } @@ -442,7 +438,7 @@ pub fn embedVerticalSeparationPattern( ) -> Result<(), Exceptions> { for y in 0..7 { if !isEmpty(matrix.get(xStart, yStart + y)) { - return Err(Exceptions::WriterException(None)); + return Err(Exceptions::writerEmpty()); } matrix.set(xStart, yStart + y, 0); } diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index bd44de7..17926b2 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -158,9 +158,9 @@ impl MinimalEncoder { Self::getVersion(Self::getVersionSize(result.getVersion()))?, &self.ecLevel, ) { - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "Data too big for version {version}" - )))); + ))); } Ok(result) } else { @@ -186,9 +186,9 @@ impl MinimalEncoder { } } if smallestRXingResult < 0 { - return Err(Exceptions::WriterException(Some( + return Err(Exceptions::writer( "Data too big for any version".to_owned(), - ))); + )); } Ok(results[smallestRXingResult as usize].clone()) } @@ -249,9 +249,9 @@ impl MinimalEncoder { Some(Mode::ALPHANUMERIC) => Ok(1), Some(Mode::BYTE) => Ok(3), Some(Mode::KANJI) | None => Ok(0), - _ => Err(Exceptions::IllegalArgumentException(Some(format!( + _ => Err(Exceptions::illegalArgument(format!( "Illegal mode {mode:?}" - )))), + ))), } } @@ -264,23 +264,23 @@ impl MinimalEncoder { let vertexIndex = position + edge .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? .characterLength as usize; let modeEdges = &mut edges[vertexIndex][edge .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? .charsetEncoderIndex]; - let modeOrdinal = Self::getCompactedOrdinal(Some( - edge.as_ref().ok_or(Exceptions::FormatException(None))?.mode, - ))? as usize; + let modeOrdinal = + Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::formatEmpty())?.mode))? + as usize; if modeEdges[modeOrdinal].is_none() || modeEdges[modeOrdinal] .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? .cachedTotalSize > edge .as_ref() - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? .cachedTotalSize { modeEdges[modeOrdinal] = edge; @@ -304,12 +304,12 @@ impl MinimalEncoder { .encoders .canEncode( &self.stringToEncode[from], - priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?, + priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?, ) - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? { - start = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?; - end = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))? + 1; + start = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?; + end = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())? + 1; } for i in start..end { @@ -318,10 +318,10 @@ impl MinimalEncoder { .canEncode( self.stringToEncode .get(from) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, i, ) - .ok_or(Exceptions::FormatException(None))? + .ok_or(Exceptions::formatEmpty())? { self.addEdge( edges, @@ -337,7 +337,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::WriterException(None))?, + .ok_or(Exceptions::writerEmpty())?, )), )?; } @@ -347,7 +347,7 @@ impl MinimalEncoder { &Mode::KANJI, self.stringToEncode .get(from) - .ok_or(Exceptions::FormatException(None))?, + .ok_or(Exceptions::formatEmpty())?, ) { self.addEdge( edges, @@ -363,7 +363,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::WriterException(None))?, + .ok_or(Exceptions::writerEmpty())?, )), )?; } @@ -373,7 +373,7 @@ impl MinimalEncoder { &Mode::ALPHANUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { self.addEdge( edges, @@ -388,7 +388,7 @@ impl MinimalEncoder { &Mode::ALPHANUMERIC, self.stringToEncode .get(from + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { 1 @@ -400,7 +400,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::WriterException(None))?, + .ok_or(Exceptions::writerEmpty())?, )), )?; } @@ -409,7 +409,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { self.addEdge( edges, @@ -424,7 +424,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { 1 @@ -433,7 +433,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from + 2) - .ok_or(Exceptions::IndexOutOfBoundsException(None))?, + .ok_or(Exceptions::indexOutOfBoundsEmpty())?, ) { 2 @@ -445,7 +445,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::WriterException(None))?, + .ok_or(Exceptions::writerEmpty())?, )), )?; } @@ -608,22 +608,22 @@ impl MinimalEncoder { version, edges[inputLength][minJ][minK] .as_ref() - .ok_or(Exceptions::WriterException(None))? + .ok_or(Exceptions::writerEmpty())? .clone(), self.isGS1, &self.ecLevel, self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::WriterException(None))?) + .ok_or(Exceptions::writerEmpty())?) } else { - Err(Exceptions::WriterException(Some(format!( + Err(Exceptions::writer(format!( r#"Internal error: failed to encode "{}"#, self.stringToEncode .iter() .map(String::from) .collect::() - )))) + ))) } } } @@ -1033,7 +1033,7 @@ impl RXingResultNode { bits, self.encoders .getCharset(self.charsetEncoderIndex) - .ok_or(Exceptions::WriterException(None))?, + .ok_or(Exceptions::writerEmpty())?, )?; } Ok(()) diff --git a/src/qrcode/encoder/qrcode_encoder.rs b/src/qrcode/encoder/qrcode_encoder.rs index a6d21ac..c0f36ec 100644 --- a/src/qrcode/encoder/qrcode_encoder.rs +++ b/src/qrcode/encoder/qrcode_encoder.rs @@ -101,8 +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::WriterException(None))?, + encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writerEmpty())?, ) } } @@ -181,9 +180,9 @@ pub fn encode_with_hints( version = Version::getVersionForNumber(versionNumber)?; let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version); if !willFit(bitsNeeded, version, &ec_level) { - return Err(Exceptions::WriterException(Some( + return Err(Exceptions::writer( "Data too big for requested version".to_owned(), - ))); + )); } } else { version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?; @@ -391,9 +390,9 @@ fn chooseVersion( return Ok(version); } } - Err(Exceptions::WriterException(Some(format!( + Err(Exceptions::writer(format!( "data too big {numInputBits}/{ecLevel:?}" - )))) + ))) } /** @@ -419,9 +418,9 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> { let capacity = num_data_bytes * 8; if bits.getSize() > capacity as usize { - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "data bits cannot fit in the QR Code{capacity} > " - )))); + ))); } // Append Mode.TERMINATE if there is enough space (value is 0000) for _i in 0..4 { @@ -447,9 +446,9 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?; } if bits.getSize() != capacity as usize { - return Err(Exceptions::WriterException(Some( + return Err(Exceptions::writer( "Bits size does not equal capacity".to_owned(), - ))); + )); } Ok(()) } @@ -468,9 +467,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // numECBytesInBlock: &mut [u32], ) -> Result<(u32, u32), Exceptions> { if block_id >= num_rsblocks { - return Err(Exceptions::WriterException(Some( - "Block ID too large".to_owned(), - ))); + return Err(Exceptions::writer("Block ID too large".to_owned())); } // numRsBlocksInGroup2 = 196 % 5 = 1 let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks; @@ -491,24 +488,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // Sanity checks. // 26 = 26 if num_ec_bytes_in_group1 != numEcBytesInGroup2 { - return Err(Exceptions::WriterException(Some( - "EC bytes mismatch".to_owned(), - ))); + return Err(Exceptions::writer("EC bytes mismatch".to_owned())); } // 5 = 4 + 1. if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 { - return Err(Exceptions::WriterException(Some( - "RS blocks mismatch".to_owned(), - ))); + return Err(Exceptions::writer("RS blocks mismatch".to_owned())); } // 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::WriterException(Some( - "total bytes mismatch".to_owned(), - ))); + return Err(Exceptions::writer("total bytes mismatch".to_owned())); } Ok(if block_id < num_rs_blocks_in_group1 { @@ -530,9 +521,9 @@ pub fn interleaveWithECBytes( ) -> Result { // "bits" must have "getNumDataBytes" bytes of data. if bits.getSizeInBytes() as u32 != num_data_bytes { - return Err(Exceptions::WriterException(Some( + return Err(Exceptions::writer( "Number of bits and data bytes does not match".to_owned(), - ))); + )); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll @@ -565,9 +556,9 @@ pub fn interleaveWithECBytes( data_bytes_offset += numDataBytesInBlock as usize; } if num_data_bytes != data_bytes_offset as u32 { - return Err(Exceptions::WriterException(Some( + return Err(Exceptions::writer( "Data bytes does not match offset".to_owned(), - ))); + )); } let mut result = BitArray::new(); @@ -592,11 +583,11 @@ pub fn interleaveWithECBytes( } if num_total_bytes != result.getSizeInBytes() as u32 { // Should be same. - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "Interleaving error: {} and {} differ.", num_total_bytes, result.getSizeInBytes() - )))); + ))); } Ok(result) @@ -642,11 +633,11 @@ pub fn appendLengthInfo( ) -> Result<(), Exceptions> { let numBits = mode.getCharacterCountBits(version); if num_letters >= (1 << numBits) { - return Err(Exceptions::WriterException(Some(format!( + return Err(Exceptions::writer(format!( "{} is bigger than {}", num_letters, ((1 << numBits) - 1) - )))); + ))); } bits.appendBits(num_letters, numBits as usize) } @@ -665,9 +656,7 @@ pub fn appendBytes( Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits), Mode::BYTE => append8BitBytes(content, bits, encoding), Mode::KANJI => appendKanjiBytes(content, bits), - _ => Err(Exceptions::WriterException(Some(format!( - "Invalid mode: {mode:?}" - )))), + _ => Err(Exceptions::writer(format!("Invalid mode: {mode:?}"))), } } @@ -678,19 +667,19 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce let num1 = content .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8 + .ok_or(Exceptions::indexOutOfBoundsEmpty())? 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::IndexOutOfBoundsException(None))? as u8 + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 - b'0'; let num3 = content .chars() .nth(i + 2) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8 + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 - b'0'; bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?; i += 3; @@ -699,7 +688,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce let num2 = content .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8 + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 - b'0'; bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?; i += 2; @@ -720,20 +709,20 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(), content .chars() .nth(i) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32, + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32, ); if code1 == -1 { - return Err(Exceptions::WriterException(None)); + return Err(Exceptions::writerEmpty()); } if i + 1 < length { let code2 = getAlphanumericCode( content .chars() .nth(i + 1) - .ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32, + .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32, ); if code2 == -1 { - return Err(Exceptions::WriterException(None)); + return Err(Exceptions::writerEmpty()); } // Encode two alphanumeric letters in 11 bits. bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?; @@ -754,7 +743,7 @@ pub fn append8BitBytes( ) -> Result<(), Exceptions> { let bytes = encoding .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?; + .map_err(|e| Exceptions::writer(format!("error {e}")))?; for b in bytes { bits.appendBits(b as u32, 8)?; } @@ -766,11 +755,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except let bytes = sjis .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?; + .map_err(|e| Exceptions::writer(format!("error {e}")))?; if bytes.len() % 2 != 0 { - return Err(Exceptions::WriterException(Some( - "Kanji byte size not even".to_owned(), - ))); + return Err(Exceptions::writer("Kanji byte size not even".to_owned())); } let max_i = bytes.len() - 1; // bytes.length must be even let mut i = 0; @@ -785,9 +772,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except subtracted = code as i32 - 0xc140; } if subtracted == -1 { - return Err(Exceptions::WriterException(Some( - "Invalid byte sequence".to_owned(), - ))); + return Err(Exceptions::writer("Invalid byte sequence".to_owned())); } 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 023eb98..d641b7e 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -83,7 +83,7 @@ impl Reader for QRCodeReader { // if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) { other .downcast_ref::() - .ok_or(Exceptions::IllegalStateException(None))? + .ok_or(Exceptions::illegalStateEmpty())? .applyMirroredCorrection(&mut points); } } @@ -153,12 +153,11 @@ impl QRCodeReader { let leftTopBlack = image.getTopLeftOnBit(); let rightBottomBlack = image.getBottomRightOnBit(); if leftTopBlack.is_none() || rightBottomBlack.is_none() { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } - let leftTopBlack = leftTopBlack.ok_or(Exceptions::IndexOutOfBoundsException(None))?; - let rightBottomBlack = - rightBottomBlack.ok_or(Exceptions::IndexOutOfBoundsException(None))?; + let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBoundsEmpty())?; + let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBoundsEmpty())?; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -169,7 +168,7 @@ impl QRCodeReader { // Sanity check! if left >= right || top >= bottom { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if bottom - top != right - left { @@ -178,17 +177,17 @@ impl QRCodeReader { right = left + (bottom - top); if right >= image.getWidth() as i32 { // Abort if that would not make sense -- off image - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } } let matrixWidth = ((right as f32 - left as f32 + 1.0) / moduleSize).round() as u32; let matrixHeight = ((bottom as f32 - top as f32 + 1.0) / moduleSize).round() as u32; if matrixWidth == 0 || matrixHeight == 0 { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } if matrixHeight != matrixWidth { // Only possibly decode square regions - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } // Push in the "border" by half the module width so that we start @@ -206,7 +205,7 @@ impl QRCodeReader { if nudgedTooFarRight > 0 { if nudgedTooFarRight > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } left -= nudgedTooFarRight; } @@ -215,7 +214,7 @@ impl QRCodeReader { if nudgedTooFarDown > 0 { if nudgedTooFarDown > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } top -= nudgedTooFarDown; } @@ -252,7 +251,7 @@ impl QRCodeReader { y += 1; } if x == width || y == height { - return Err(Exceptions::NotFoundException(None)); + return Err(Exceptions::notFoundEmpty()); } 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 b3a458a..7bbd359 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -58,22 +58,22 @@ impl Writer for QRCodeWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "found empty contents".to_owned(), - ))); + )); } if format != &BarcodeFormat::QR_CODE { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "can only encode QR_CODE, but got {format:?}" - )))); + ))); // throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } if width < 0 || height < 0 { - return Err(Exceptions::IllegalArgumentException(Some(format!( + return Err(Exceptions::illegalArgument(format!( "requested dimensions are too small: {width}x{height}" - )))); + ))); } let errorCorrectionLevel = if let Some(EncodeHintValue::ErrorCorrection(ec_level)) = @@ -86,9 +86,9 @@ impl Writer for QRCodeWriter { let quietZone = if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) { - margin.parse::().map_err(|e| { - Exceptions::ParseException(Some(format!("could not parse {margin}: {e}"))) - })? + margin + .parse::() + .map_err(|e| Exceptions::parse(format!("could not parse {margin}: {e}")))? } else { QUIET_ZONE_SIZE }; @@ -110,14 +110,10 @@ impl QRCodeWriter { ) -> Result { let input = code.getMatrix(); if input.is_none() { - return Err(Exceptions::IllegalStateException(Some( - "matrix is empty".to_owned(), - ))); + return Err(Exceptions::illegalState("matrix is empty".to_owned())); } - let input = input - .as_ref() - .ok_or(Exceptions::IllegalStateException(None))?; + let input = input.as_ref().ok_or(Exceptions::illegalStateEmpty())?; 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 a069a32..3c4c3bf 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -127,7 +127,7 @@ impl LuminanceSource for RGBLuminanceSource { height, ) { Ok(crop) => Ok(Box::new(crop)), - Err(_error) => Err(Exceptions::UnsupportedOperationException(None)), + Err(_error) => Err(Exceptions::unsupportedOperationEmpty()), } } @@ -179,9 +179,9 @@ impl RGBLuminanceSource { height: usize, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::IllegalArgumentException(Some( + return Err(Exceptions::illegalArgument( "Crop rectangle does not fit within image data.".to_owned(), - ))); + )); } Ok(Self { luminances: pixels.to_owned(), diff --git a/src/svg_luminance_source.rs b/src/svg_luminance_source.rs index f0c31ed..2785e0f 100644 --- a/src/svg_luminance_source.rs +++ b/src/svg_luminance_source.rs @@ -56,11 +56,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::FormatException(Some(format!("could not parse svg data: {}", "err")))); + return Err(Exceptions::format(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::FormatException(Some("could not create pixmap".to_owned()))); + return Err(Exceptions::format("could not create pixmap".to_owned())); }; resvg::render( @@ -71,11 +71,11 @@ 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::FormatException(Some("could not create image buffer".to_owned()))); + return Err(Exceptions::format("could not create image buffer".to_owned())); }; // let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else { - // return Err(Exceptions::FormatException(Some("could not generate image".to_owned()))); + // return Err(Exceptions::format("could not generate image".to_owned())); // }; Ok(Self(BufferedImageLuminanceSource::new(DynamicImage::from( From 528ddea41c9904082daae8c82196e110b792d1fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 11:03:27 +0000 Subject: [PATCH 3/6] remove .to_owned() calls on &str in exceptions --- src/aztec/decoder.rs | 14 ++++------ src/aztec/detector.rs | 4 +-- src/aztec/encoder/aztec_encoder.rs | 6 ++--- src/aztec/encoder/high_level_encoder.rs | 4 +-- src/aztec/encoder/state.rs | 2 +- src/client/result/AddressBookParsedResult.rs | 6 ++--- src/client/result/VINResultParser.rs | 8 +++--- src/common/bit_array.rs | 4 +-- src/common/bit_matrix.rs | 18 +++++-------- src/common/character_set_eci.rs | 2 +- src/common/default_grid_sampler.rs | 2 +- src/common/global_histogram_binarizer.rs | 2 +- src/common/reedsolomon/generic_gf_poly.rs | 10 +++---- src/common/reedsolomon/reedsolomon_decoder.rs | 12 ++++----- src/common/reedsolomon/reedsolomon_encoder.rs | 8 ++---- src/datamatrix/data_matrix_writer.rs | 8 +++--- src/datamatrix/decoder/bit_matrix_parser.rs | 2 +- .../decoder/decoded_bit_stream_parser.rs | 2 +- .../detector/datamatrix_detector.rs | 2 +- src/datamatrix/encoder/c40_encoder.rs | 4 +-- src/datamatrix/encoder/edifact_encoder.rs | 8 ++---- src/datamatrix/encoder/encoder_context.rs | 2 +- src/datamatrix/encoder/error_correction.rs | 2 +- src/datamatrix/encoder/symbol_info.rs | 4 +-- src/helpers.rs | 20 +++++--------- src/luma_luma_source.rs | 2 +- src/luminance_source.rs | 6 ++--- .../detector/multi_finder_pattern_finder.rs | 4 +-- src/oned/code_128_writer.rs | 2 +- src/oned/ean_13_writer.rs | 4 +-- src/oned/ean_8_writer.rs | 4 +-- src/oned/itf_writer.rs | 2 +- src/oned/one_d_code_writer.rs | 6 ++--- src/oned/rss/expanded/binary_util.rs | 2 +- src/oned/upc_e_writer.rs | 8 ++---- src/pdf417/decoder/ec/modulus_poly.rs | 6 ++--- src/pdf417/encoder/pdf_417.rs | 4 +-- .../encoder/pdf_417_error_correction.rs | 6 ++--- .../encoder/pdf_417_high_level_encoder.rs | 6 ++--- src/planar_yuv_luminance_source.rs | 2 +- src/qrcode/decoder/version.rs | 6 ++--- src/qrcode/encoder/matrix_util.rs | 4 +-- src/qrcode/encoder/minimal_encoder.rs | 4 +-- src/qrcode/encoder/qrcode_encoder.rs | 26 +++++++------------ src/qrcode/qr_code_writer.rs | 6 ++--- src/rgb_luminance_source.rs | 2 +- src/svg_luminance_source.rs | 6 ++--- 47 files changed, 107 insertions(+), 167 deletions(-) diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index cb10079..f584b69 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -170,11 +170,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { decoded_bytes.clear(); match n { 0 => result.push(29 as char), // translate FNC1 as ASCII 29 - 7 => { - return Err(Exceptions::format( - "FLG(7) is reserved and illegal".to_owned(), - )) - } // FLG(7) is reserved and illegal + 7 => return Err(Exceptions::format("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; @@ -186,7 +182,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::format("Not a decimal digit".to_owned())); + return Err(Exceptions::format("Not a decimal digit")); // Not a decimal digit } eci = eci * 10 + (next_digit - 2); @@ -194,7 +190,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { } let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); if charset_eci.is_err() { - return Err(Exceptions::format("Charset must exist".to_owned())); + return Err(Exceptions::format("Charset must exist")); } encdr = CharacterSetECI::getCharset(&charset_eci?); } @@ -238,7 +234,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::illegalState("bad encoding".to_owned())); + return Err(Exceptions::illegalState("bad encoding")); } // result.push_str(decodedBytes.toString(encoding.name())); //} catch (UnsupportedEncodingException uee) { @@ -290,7 +286,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { 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::illegalState("Bad table".to_owned())), + _ => Err(Exceptions::illegalState("Bad table")), } // switch (table) { // case UPPER: diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index aaedb29..097947b 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -127,7 +127,7 @@ impl<'a> Detector<'_> { || !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[3]) { - return Err(Exceptions::notFound("no valid points".to_owned())); + return Err(Exceptions::notFound("no valid points")); } let length = 2 * self.nb_center_layers; // Get the bits around the bull's eye @@ -208,7 +208,7 @@ impl<'a> Detector<'_> { return Ok(shift); } } - Err(Exceptions::notFound("rotation failure".to_owned())) + Err(Exceptions::notFound("rotation failure")) } /** diff --git a/src/aztec/encoder/aztec_encoder.rs b/src/aztec/encoder/aztec_encoder.rs index 0d55196..baf7b17 100644 --- a/src/aztec/encoder/aztec_encoder.rs +++ b/src/aztec/encoder/aztec_encoder.rs @@ -188,13 +188,13 @@ pub fn encode_bytes_with_charset( stuffed_bits = stuffBits(&bits, word_size as usize)?; if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers { return Err(Exceptions::illegalArgument( - "Data to large for user specified layer".to_owned(), + "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::illegalArgument( - "Data to large for user specified layer".to_owned(), + "Data to large for user specified layer", )); } } else { @@ -208,7 +208,7 @@ pub fn encode_bytes_with_charset( // for (int i = 0; ; i++) { if i > MAX_NB_BITS { return Err(Exceptions::illegalArgument( - "Data too large for an Aztec code".to_owned(), + "Data too large for an Aztec code", )); } compact = i <= 3; diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index cb59088..108258f 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -248,9 +248,7 @@ impl HighLevelEncoder { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { - return Err(Exceptions::illegalArgument( - "No ECI code for character set".to_owned(), - )); + return Err(Exceptions::illegalArgument("No ECI code for character set")); } // if self.charset != null { // CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset); diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index 9834cc7..bb82b84 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -81,7 +81,7 @@ impl State { } else */ if eci > 999999 { return Err(Exceptions::illegalArgument( - "ECI code must be between 0 and 999999".to_owned(), + "ECI code must be between 0 and 999999", )); // throw new IllegalArgumentException("ECI code must be between 0 and 999999"); } else { diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index b9e9418..28313d5 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -121,17 +121,17 @@ impl AddressBookParsedRXingResult { ) -> Result { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { return Err(Exceptions::illegalArgument( - "Phone numbers and types lengths differ".to_owned(), + "Phone numbers and types lengths differ", )); } if emails.len() != email_types.len() && !email_types.is_empty() { return Err(Exceptions::illegalArgument( - "Emails and types lengths differ".to_owned(), + "Emails and types lengths differ", )); } if addresses.len() != address_types.len() && !address_types.is_empty() { return Err(Exceptions::illegalArgument( - "Addresses and types lengths differ".to_owned(), + "Addresses and types lengths differ", )); } Ok(Self { diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 41b0757..842da2d 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -91,9 +91,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::illegalArgument( - "vin char out of range".to_owned(), - )), + _ => Err(Exceptions::illegalArgument("vin char out of range")), } } @@ -104,7 +102,7 @@ fn vin_position_weight(position: usize) -> Result { 9 => Ok(0), 10..=17 => Ok(19 - position), _ => Err(Exceptions::illegalArgument( - "vin position weight out of bounds".to_owned(), + "vin position weight out of bounds", )), } } @@ -113,7 +111,7 @@ fn check_char(remainder: u8) -> Result { match remainder { 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), - _ => Err(Exceptions::illegalArgument("remainder too high".to_owned())), + _ => Err(Exceptions::illegalArgument("remainder too high")), } } diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 1ed68ba..6c5fd8c 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -254,7 +254,7 @@ impl BitArray { pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { if num_bits > 32 { return Err(Exceptions::illegalArgument( - "num bits must be between 0 and 32".to_owned(), + "num bits must be between 0 and 32", )); } @@ -286,7 +286,7 @@ impl BitArray { pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { if self.size != other.size { - return Err(Exceptions::illegalArgument("Sizes don't match".to_owned())); + return Err(Exceptions::illegalArgument("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 10d70a3..2d0c893 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::illegalArgument( - "Both dimensions must be greater than 0".to_owned(), + "Both dimensions must be greater than 0", )); } Ok(Self { @@ -151,9 +151,7 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgument( - "row lengths do not match".to_owned(), - )); + return Err(Exceptions::illegalArgument("row lengths do not match")); } rowStartPos = bitsPos; nRows += 1; @@ -182,9 +180,7 @@ impl BitMatrix { // first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgument( - "row lengths do not match".to_owned(), - )); + return Err(Exceptions::illegalArgument("row lengths do not match")); } nRows += 1; } @@ -312,7 +308,7 @@ impl BitMatrix { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { return Err(Exceptions::illegalArgument( - "input matrix dimensions do not match".to_owned(), + "input matrix dimensions do not match", )); } // let mut rowArray = BitArray::with_size(self.width as usize); @@ -364,14 +360,14 @@ impl BitMatrix { // } if height < 1 || width < 1 { return Err(Exceptions::illegalArgument( - "height and width must be at least 1".to_owned(), + "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::illegalArgument( - "the region must fit inside the matrix".to_owned(), + "the region must fit inside the matrix", )); } for y in top..bottom { @@ -445,7 +441,7 @@ impl BitMatrix { Ok(()) } _ => Err(Exceptions::illegalArgument( - "degrees must be a multiple of 0, 90, 180, or 270".to_owned(), + "degrees must be a multiple of 0, 90, 180, or 270", )), } } diff --git a/src/common/character_set_eci.rs b/src/common/character_set_eci.rs index 97d9063..284127b 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -244,7 +244,7 @@ impl CharacterSetECI { 28 => Ok(CharacterSetECI::Big5), 29 => Ok(CharacterSetECI::GB18030), 30 => Ok(CharacterSetECI::EUC_KR), - _ => Err(Exceptions::notFound("Bad ECI Value".to_owned())), + _ => Err(Exceptions::notFound("Bad ECI Value")), } } diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index 3669669..f890394 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -99,7 +99,7 @@ impl GridSampler for DefaultGridSampler { if image .try_get(points[x] as u32, points[x + 1] as u32) .ok_or(Exceptions::notFound( - "index out of bounds, see documentation in file for explanation".to_owned(), + "index out of bounds, see documentation in file for explanation", ))? { // Black(-ish) pixel diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index 9c6a6af..b9e5431 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -234,7 +234,7 @@ impl GlobalHistogramBinarizer { // than waste time trying to decode the image, and risk false positives. if secondPeak - firstPeak <= numBuckets / 16 { return Err(Exceptions::notFound( - "secondPeak - firstPeak <= numBuckets / 16 ".to_owned(), + "secondPeak - firstPeak <= numBuckets / 16 ", )); } diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index 43eabda..f0a8d78 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -141,7 +141,7 @@ impl GenericGFPoly { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { return Err(Exceptions::illegalArgument( - "GenericGFPolys do not have same GenericGF field".to_owned(), + "GenericGFPolys do not have same GenericGF field", )); } if self.isZero() { @@ -178,7 +178,7 @@ impl GenericGFPoly { if self.field != other.field { //if (!field.equals(other.field)) { return Err(Exceptions::illegalArgument( - "GenericGFPolys do not have same GenericGF field".to_owned(), + "GenericGFPolys do not have same GenericGF field", )); } if self.isZero() || other.isZero() { @@ -253,11 +253,11 @@ impl GenericGFPoly { ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { if self.field != other.field { return Err(Exceptions::illegalArgument( - "GenericGFPolys do not have same GenericGF field".to_owned(), + "GenericGFPolys do not have same GenericGF field", )); } if other.isZero() { - return Err(Exceptions::illegalArgument("Divide by 0".to_owned())); + return Err(Exceptions::illegalArgument("Divide by 0")); } let mut quotient = self.getZero(); @@ -266,7 +266,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::illegalArgument("arithmetic issue".to_owned())), + Err(_issue) => return Err(Exceptions::illegalArgument("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 ac28f67..292b967 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -92,11 +92,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::reedSolomon("Bad error location".to_owned())); + return Err(Exceptions::reedSolomon("Bad error location")); } let position: isize = received.len() as isize - 1 - log_value as isize; if position < 0 { - return Err(Exceptions::reedSolomon("Bad error location".to_owned())); + return Err(Exceptions::reedSolomon("Bad error location")); } received[position as usize] = GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); @@ -134,7 +134,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::reedSolomon("r_{i-1} was zero".to_owned())); + return Err(Exceptions::reedSolomon("r_{i-1} was zero")); } r = rLastLast; let mut q = r.getZero(); @@ -160,12 +160,12 @@ impl ReedSolomonDecoder { let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero".to_owned())); + return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero")); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, - Err(_err) => return Err(Exceptions::reedSolomon("ArithmetricException".to_owned())), + Err(_err) => return Err(Exceptions::reedSolomon("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::reedSolomon( - "Error locator degree does not match number of roots".to_owned(), + "Error locator degree does not match number of roots", )); } Ok(result) diff --git a/src/common/reedsolomon/reedsolomon_encoder.rs b/src/common/reedsolomon/reedsolomon_encoder.rs index 3695fa4..1a6476e 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -73,15 +73,11 @@ impl ReedSolomonEncoder { pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<(), Exceptions> { if ec_bytes == 0 { - return Err(Exceptions::illegalArgument( - "No error correction bytes".to_owned(), - )); + return Err(Exceptions::illegalArgument("No error correction bytes")); } let data_bytes = to_encode.len() - ec_bytes; if data_bytes == 0 { - return Err(Exceptions::illegalArgument( - "No data bytes provided".to_owned(), - )); + return Err(Exceptions::illegalArgument("No data bytes provided")); } let fld = self.field; let generator = self.buildGenerator(ec_bytes); diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index 03b67ec..a86d301 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -60,9 +60,7 @@ impl Writer for DataMatrixWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument( - "Found empty contents".to_owned(), - )); + return Err(Exceptions::illegalArgument("Found empty contents")); } if format != &BarcodeFormat::DATA_MATRIX { @@ -123,7 +121,7 @@ impl Writer for DataMatrixWriter { if hasEncodingHint { let Some(EncodeHintValue::CharacterSet(char_set_name)) = hints.get(&EncodeHintType::CHARACTER_SET) else { - return Err(Exceptions::illegalArgument("charset does not exist".to_owned())) + return Err(Exceptions::illegalArgument("charset does not exist")) }; charset = encoding::label::encoding_from_whatwg_label(char_set_name); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); @@ -157,7 +155,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::notFound("symbol info is bad".to_owned())) + return Err(Exceptions::notFound("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 eccd707..635ea6b 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -457,7 +457,7 @@ impl BitMatrixParser { if bitMatrix.getHeight() != symbolSizeRows { return Err(Exceptions::illegalArgument( - "Dimension of bitMatrix must match the version size".to_owned(), + "Dimension of bitMatrix must match the version size", )); } diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index 95331da..946417e 100644 --- a/src/datamatrix/decoder/decoded_bit_stream_parser.rs +++ b/src/datamatrix/decoder/decoded_bit_stream_parser.rs @@ -279,7 +279,7 @@ fn decodeAsciiSegment( // Must be first ISO 16022:2006 5.6.1 { return Err(Exceptions::format( - "structured append tag must be first code word".to_owned(), + "structured append tag must be first code word", )); } parse_structured_append(bits, &mut sai)?; diff --git a/src/datamatrix/detector/datamatrix_detector.rs b/src/datamatrix/detector/datamatrix_detector.rs index 7a12213..bf6b39f 100644 --- a/src/datamatrix/detector/datamatrix_detector.rs +++ b/src/datamatrix/detector/datamatrix_detector.rs @@ -53,7 +53,7 @@ impl<'a> Detector<'_> { if let Some(point) = self.correctTopRight(&points) { points[3] = point; } else { - return Err(Exceptions::notFound("point 4 unfound".to_owned())); + return Err(Exceptions::notFound("point 4 unfound")); } // points[3] = self.correctTopRight(&points); // if points[3] == null { diff --git a/src/datamatrix/encoder/c40_encoder.rs b/src/datamatrix/encoder/c40_encoder.rs index ff00213..e3e6a45 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -234,9 +234,7 @@ impl C40Encoder { context.writeCodeword(C40_UNLATCH); } } else { - return Err(Exceptions::illegalState( - "Unexpected case. Please report!".to_owned(), - )); + return Err(Exceptions::illegalState("Unexpected case. Please report!")); } context.signalEncoderChange(ASCII_ENCODATION); diff --git a/src/datamatrix/encoder/edifact_encoder.rs b/src/datamatrix/encoder/edifact_encoder.rs index c42f252..9ae75b5 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -95,9 +95,7 @@ impl EdifactEncoder { } if count > 4 { - return Err(Exceptions::illegalState( - "Count must not exceed 4".to_owned(), - )); + return Err(Exceptions::illegalState("Count must not exceed 4")); } let restChars = count - 1; let encoded = Self::encodeToCodewords(buffer)?; @@ -149,9 +147,7 @@ impl EdifactEncoder { fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { - return Err(Exceptions::illegalState( - "StringBuilder must not be empty".to_owned(), - )); + return Err(Exceptions::illegalState("StringBuilder must not be empty")); } let c1 = sb .chars() diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index f9eebf7..5d34815 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -67,7 +67,7 @@ impl<'a> EncoderContext<'_> { })? } else { return Err(Exceptions::illegalArgument( - "Message contains characters outside ISO-8859-1 encoding.".to_owned(), + "Message contains characters outside ISO-8859-1 encoding.", )); }; Ok(Self { diff --git a/src/datamatrix/encoder/error_correction.rs b/src/datamatrix/encoder/error_correction.rs index 69dabb6..9e7a023 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::illegalArgument( - "The number of codewords does not match the selected symbol".to_owned(), + "The number of codewords does not match the selected symbol", )); } let mut sb = String::with_capacity( diff --git a/src/datamatrix/encoder/symbol_info.rs b/src/datamatrix/encoder/symbol_info.rs index 0e79c8f..40df3f6 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -129,7 +129,7 @@ impl SymbolInfo { 16 => Ok(4), 36 => Ok(6), _ => Err(Exceptions::illegalState( - "Cannot handle this number of data regions".to_owned(), + "Cannot handle this number of data regions", )), } } @@ -141,7 +141,7 @@ impl SymbolInfo { 16 => Ok(4), 36 => Ok(6), _ => Err(Exceptions::illegalState( - "Cannot handle this number of data regions".to_owned(), + "Cannot handle this number of data regions", )), } } diff --git a/src/helpers.rs b/src/helpers.rs index 592b6d9..640391e 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -35,20 +35,16 @@ pub fn detect_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgument( - "file does not exist".to_owned(), - )); + return Err(Exceptions::illegalArgument("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgument("file cannot be opened".to_owned())); + return Err(Exceptions::illegalArgument("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgument( - "file cannot be read".to_owned(), - )); + return Err(Exceptions::illegalArgument("file cannot be read")); } let mut multi_format_reader = MultiFormatReader::default(); @@ -88,20 +84,16 @@ pub fn detect_multiple_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgument( - "file does not exist".to_owned(), - )); + return Err(Exceptions::illegalArgument("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgument("file cannot be opened".to_owned())); + return Err(Exceptions::illegalArgument("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgument( - "file cannot be read".to_owned(), - )); + return Err(Exceptions::illegalArgument("file cannot be read")); } let multi_format_reader = MultiFormatReader::default(); diff --git a/src/luma_luma_source.rs b/src/luma_luma_source.rs index 5f60e7b..497844c 100644 --- a/src/luma_luma_source.rs +++ b/src/luma_luma_source.rs @@ -96,7 +96,7 @@ impl LuminanceSource for Luma8LuminanceSource { fn rotateCounterClockwise45(&self) -> Result, crate::Exceptions> { Err(crate::Exceptions::unsupportedOperation( - "This luminance source does not support rotation by 45 degrees.".to_owned(), + "This luminance source does not support rotation by 45 degrees.", )) } } diff --git a/src/luminance_source.rs b/src/luminance_source.rs index 21954bf..2c55378 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -92,7 +92,7 @@ pub trait LuminanceSource { _height: usize, ) -> Result, Exceptions> { Err(Exceptions::unsupportedOperation( - "This luminance source does not support cropping.".to_owned(), + "This luminance source does not support cropping.", )) } @@ -119,7 +119,7 @@ pub trait LuminanceSource { */ fn rotateCounterClockwise(&self) -> Result, Exceptions> { Err(Exceptions::unsupportedOperation( - "This luminance source does not support rotation by 90 degrees.".to_owned(), + "This luminance source does not support rotation by 90 degrees.", )) } @@ -131,7 +131,7 @@ pub trait LuminanceSource { */ fn rotateCounterClockwise45(&self) -> Result, Exceptions> { Err(Exceptions::unsupportedOperation( - "This luminance source does not support rotation by 45 degrees.".to_owned(), + "This luminance source does not support rotation by 45 degrees.", )) } diff --git a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs index 49803d6..43d9a7b 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -93,9 +93,7 @@ impl<'a> MultiFinderPatternFinder<'_> { if size < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::notFound( - "Couldn't find enough finder patterns".to_owned(), - )); + return Err(Exceptions::notFound("Couldn't find enough finder patterns")); } /* diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index f08e1d1..e8c0c6d 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -249,7 +249,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception if position + 1 == length { // this is the last character, but the encoding is C, which always encodes two characers return Err(Exceptions::illegalArgument( - "Bad number of characters for digit only encoding.".to_owned(), + "Bad number of characters for digit only encoding.", )); } let s: String = contents diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index f585dc6..05c094a 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -45,9 +45,7 @@ impl OneDimensionalCodeWriter for EAN13Writer { } 13 => { if !reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgument( - "Contents do not pass checksum".to_owned(), - )); + return Err(Exceptions::illegalArgument("Contents do not pass checksum")); } } _ => { diff --git a/src/oned/ean_8_writer.rs b/src/oned/ean_8_writer.rs index 3191bd4..9857d35 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -55,9 +55,7 @@ impl OneDimensionalCodeWriter for EAN8Writer { } 8 => { if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgument( - "Contents do not pass checksum".to_owned(), - )); + return Err(Exceptions::illegalArgument("Contents do not pass checksum")); } } _ => { diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index 57d14d2..ffd32b3 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -33,7 +33,7 @@ impl OneDimensionalCodeWriter for ITFWriter { let length = contents.chars().count(); if length % 2 != 0 { return Err(Exceptions::illegalArgument( - "The length of the input should be even".to_owned(), + "The length of the input should be even", )); } if length > 80 { diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 0ec8f3d..315f54d 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<(), Exceptions> { if !NUMERIC.is_match(contents) { Err(Exceptions::illegalArgument( - "Input should only contain digits 0-9".to_owned(), + "Input should only contain digits 0-9", )) } else { Ok(()) @@ -163,9 +163,7 @@ impl Writer for L { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument( - "Found empty contents".to_owned(), - )); + return Err(Exceptions::illegalArgument("Found empty contents")); } if width < 0 || height < 0 { diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index a3ebc7a..5493ef4 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -51,7 +51,7 @@ pub fn buildBitArrayFromString(data: &str) -> Result { if i % 9 == 0 { // spaces if dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())? != ' ' { - return Err(Exceptions::illegalState("space expected".to_owned())); + return Err(Exceptions::illegalState("space expected")); } continue; } diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index 9a4bf2c..90cf4af 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -55,9 +55,7 @@ impl OneDimensionalCodeWriter for UPCEWriter { &upc_e_reader::convertUPCEtoUPCA(&contents) .ok_or(Exceptions::illegalArgumentEmpty())?, )? { - return Err(Exceptions::illegalArgument( - "Contents do not pass checksum".to_owned(), - )); + return Err(Exceptions::illegalArgument("Contents do not pass checksum")); } } _ => { @@ -76,9 +74,7 @@ impl OneDimensionalCodeWriter for UPCEWriter { .to_digit(10) .ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(0), 10); if firstDigit != 0 && firstDigit != 1 { - return Err(Exceptions::illegalArgument( - "Number system must be 0 or 1".to_owned(), - )); + return Err(Exceptions::illegalArgument("Number system must be 0 or 1")); } let checkDigit = contents diff --git a/src/pdf417/decoder/ec/modulus_poly.rs b/src/pdf417/decoder/ec/modulus_poly.rs index 694c8f9..693c4bd 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -127,7 +127,7 @@ impl ModulusPoly { pub fn add(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { return Err(Exceptions::illegalArgument( - "ModulusPolys do not have same ModulusGF field".to_owned(), + "ModulusPolys do not have same ModulusGF field", )); } if self.isZero() { @@ -161,7 +161,7 @@ impl ModulusPoly { pub fn subtract(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { return Err(Exceptions::illegalArgument( - "ModulusPolys do not have same ModulusGF field".to_owned(), + "ModulusPolys do not have same ModulusGF field", )); } if other.isZero() { @@ -173,7 +173,7 @@ impl ModulusPoly { pub fn multiply(&self, other: Rc) -> Result, Exceptions> { if !(self.field == other.field) { return Err(Exceptions::illegalArgument( - "ModulusPolys do not have same ModulusGF field".to_owned(), + "ModulusPolys do not have same ModulusGF field", )); } if self.isZero() || other.isZero() { diff --git a/src/pdf417/encoder/pdf_417.rs b/src/pdf417/encoder/pdf_417.rs index 406670d..e502971 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -315,9 +315,7 @@ impl PDF417 { } } - dimension.ok_or(Exceptions::writer( - "Unable to fit message in columns".to_owned(), - )) + dimension.ok_or(Exceptions::writer("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 41d71c7..a24d6e0 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::illegalArgument( - "Error correction level must be between 0 and 8!".to_owned(), + "Error correction level must be between 0 and 8!", )); } Ok(1 << (errorCorrectionLevel + 1)) @@ -135,7 +135,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result Result { if n == 0 { - Err(Exceptions::illegalArgument("n must be > 0".to_owned())) + Err(Exceptions::illegalArgument("n must be > 0")) } else if n <= 40 { Ok(2) } else if n <= 160 { @@ -145,7 +145,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result Result { let mut encoding = encoding; if msg.is_empty() { - return Err(Exceptions::writer("Empty message not allowed".to_owned())); + return Err(Exceptions::writer("Empty message not allowed")); } if encoding.is_none() && !autoECI { @@ -797,9 +797,7 @@ fn determineConsecutiveBinaryCount( if !can_encode { if TypeId::of::() != TypeId::of::() { - return Err(Exceptions::illegalState( - "expected NoECIInput type".to_owned(), - )); + return Err(Exceptions::illegalState("expected NoECIInput type")); } let ch = input.charAt(idx)?; return Err(Exceptions::writer(format!( diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index b2bd6f2..653e50b 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -167,7 +167,7 @@ impl PlanarYUVLuminanceSource { ) -> Result { if left + width > data_width || top + height > data_height { return Err(Exceptions::illegalArgument( - "Crop rectangle does not fit within image data.".to_owned(), + "Crop rectangle does not fit within image data.", )); } diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index 2710ce6..a1fc8ec 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -101,16 +101,14 @@ impl Version { dimension: u32, ) -> Result<&'static Version, Exceptions> { if dimension % 4 != 1 { - return Err(Exceptions::format("dimension incorrect".to_owned())); + return Err(Exceptions::format("dimension incorrect")); } Self::getVersionForNumber((dimension - 17) / 4) } pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> { if !(1..=40).contains(&versionNumber) { - return Err(Exceptions::illegalArgument( - "version out of spec".to_owned(), - )); + return Err(Exceptions::illegalArgument("version out of spec")); } Ok(&VERSIONS[versionNumber as usize - 1]) } diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index 3c20946..1368b3c 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -323,7 +323,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::illegalArgument("0 polynomial".to_owned())); + return Err(Exceptions::illegalArgument("0 polynomial")); } let mut value = value; // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 @@ -347,7 +347,7 @@ pub fn makeTypeInfoBits( bits: &mut BitArray, ) -> Result<(), Exceptions> { if !QRCode::isValidMaskPattern(maskPattern as i32) { - return Err(Exceptions::writer("Invalid mask pattern".to_owned())); + return Err(Exceptions::writer("Invalid mask pattern")); } let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern; bits.appendBits(typeInfo, 5)?; diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index 17926b2..d7c16ca 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -186,9 +186,7 @@ impl MinimalEncoder { } } if smallestRXingResult < 0 { - return Err(Exceptions::writer( - "Data too big for any version".to_owned(), - )); + return Err(Exceptions::writer("Data too big for any version")); } Ok(results[smallestRXingResult as usize].clone()) } diff --git a/src/qrcode/encoder/qrcode_encoder.rs b/src/qrcode/encoder/qrcode_encoder.rs index c0f36ec..723d714 100644 --- a/src/qrcode/encoder/qrcode_encoder.rs +++ b/src/qrcode/encoder/qrcode_encoder.rs @@ -180,9 +180,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::writer( - "Data too big for requested version".to_owned(), - )); + return Err(Exceptions::writer("Data too big for requested version")); } } else { version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?; @@ -446,9 +444,7 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?; } if bits.getSize() != capacity as usize { - return Err(Exceptions::writer( - "Bits size does not equal capacity".to_owned(), - )); + return Err(Exceptions::writer("Bits size does not equal capacity")); } Ok(()) } @@ -467,7 +463,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // numECBytesInBlock: &mut [u32], ) -> Result<(u32, u32), Exceptions> { if block_id >= num_rsblocks { - return Err(Exceptions::writer("Block ID too large".to_owned())); + return Err(Exceptions::writer("Block ID too large")); } // numRsBlocksInGroup2 = 196 % 5 = 1 let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks; @@ -488,18 +484,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // Sanity checks. // 26 = 26 if num_ec_bytes_in_group1 != numEcBytesInGroup2 { - return Err(Exceptions::writer("EC bytes mismatch".to_owned())); + return Err(Exceptions::writer("EC bytes mismatch")); } // 5 = 4 + 1. if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 { - return Err(Exceptions::writer("RS blocks mismatch".to_owned())); + return Err(Exceptions::writer("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::writer("total bytes mismatch".to_owned())); + return Err(Exceptions::writer("total bytes mismatch")); } Ok(if block_id < num_rs_blocks_in_group1 { @@ -522,7 +518,7 @@ pub fn interleaveWithECBytes( // "bits" must have "getNumDataBytes" bytes of data. if bits.getSizeInBytes() as u32 != num_data_bytes { return Err(Exceptions::writer( - "Number of bits and data bytes does not match".to_owned(), + "Number of bits and data bytes does not match", )); } @@ -556,9 +552,7 @@ pub fn interleaveWithECBytes( data_bytes_offset += numDataBytesInBlock as usize; } if num_data_bytes != data_bytes_offset as u32 { - return Err(Exceptions::writer( - "Data bytes does not match offset".to_owned(), - )); + return Err(Exceptions::writer("Data bytes does not match offset")); } let mut result = BitArray::new(); @@ -757,7 +751,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except .encode(content, encoding::EncoderTrap::Strict) .map_err(|e| Exceptions::writer(format!("error {e}")))?; if bytes.len() % 2 != 0 { - return Err(Exceptions::writer("Kanji byte size not even".to_owned())); + return Err(Exceptions::writer("Kanji byte size not even")); } let max_i = bytes.len() - 1; // bytes.length must be even let mut i = 0; @@ -772,7 +766,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except subtracted = code as i32 - 0xc140; } if subtracted == -1 { - return Err(Exceptions::writer("Invalid byte sequence".to_owned())); + return Err(Exceptions::writer("Invalid byte sequence")); } let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded as u32, 13)?; diff --git a/src/qrcode/qr_code_writer.rs b/src/qrcode/qr_code_writer.rs index 7bbd359..e9707e6 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -58,9 +58,7 @@ impl Writer for QRCodeWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument( - "found empty contents".to_owned(), - )); + return Err(Exceptions::illegalArgument("found empty contents")); } if format != &BarcodeFormat::QR_CODE { @@ -110,7 +108,7 @@ impl QRCodeWriter { ) -> Result { let input = code.getMatrix(); if input.is_none() { - return Err(Exceptions::illegalState("matrix is empty".to_owned())); + return Err(Exceptions::illegalState("matrix is empty")); } let input = input.as_ref().ok_or(Exceptions::illegalStateEmpty())?; diff --git a/src/rgb_luminance_source.rs b/src/rgb_luminance_source.rs index 3c4c3bf..2201910 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -180,7 +180,7 @@ impl RGBLuminanceSource { ) -> Result { if left + width > data_width || top + height > data_height { return Err(Exceptions::illegalArgument( - "Crop rectangle does not fit within image data.".to_owned(), + "Crop rectangle does not fit within image data.", )); } Ok(Self { diff --git a/src/svg_luminance_source.rs b/src/svg_luminance_source.rs index 2785e0f..5490ce7 100644 --- a/src/svg_luminance_source.rs +++ b/src/svg_luminance_source.rs @@ -60,7 +60,7 @@ impl SVGLuminanceSource { }; let Some(mut pixmap) = resvg::tiny_skia::Pixmap::new(tree.size.width() as u32, tree.size.height() as u32) else { - return Err(Exceptions::format("could not create pixmap".to_owned())); + return Err(Exceptions::format("could not create pixmap")); }; resvg::render( @@ -71,11 +71,11 @@ 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::format("could not create image buffer".to_owned())); + return Err(Exceptions::format("could not create image buffer")); }; // let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else { - // return Err(Exceptions::format("could not generate image".to_owned())); + // return Err(Exceptions::format("could not generate image")); // }; Ok(Self(BufferedImageLuminanceSource::new(DynamicImage::from( From df8828331decbd25c85b5d4b1ce54ea6bdd2426f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 11:18:56 +0000 Subject: [PATCH 4/6] remove more needless String conversions --- src/aztec/encoder/token.rs | 4 ++-- src/client/result/ResultParser.rs | 4 +--- src/client/result/VINResultParser.rs | 4 ++-- src/common/reedsolomon/generic_gf_poly.rs | 4 +--- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/aztec/encoder/token.rs b/src/aztec/encoder/token.rs index 7437b8f..5111904 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -31,9 +31,9 @@ impl TokenType { match self { TokenType::Simple(a) => a.appendTo(bit_array, text), TokenType::BinaryShift(a) => a.appendTo(bit_array, text), - TokenType::Empty => Err(Exceptions::illegalState(String::from( + TokenType::Empty => Err(Exceptions::illegalState( "cannot appendTo on Empty final item", - ))), + )), } } } diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index f2525c4..960eb05 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -300,9 +300,7 @@ pub fn urlDecode(encoded: &str) -> Result { if let Ok(decoded) = decode(encoded) { Ok(decoded.to_string()) } else { - Err(Exceptions::illegalState(String::from( - "UnsupportedEncodingException", - ))) + Err(Exceptions::illegalState("UnsupportedEncodingException")) } } diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 842da2d..6ee41a1 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -124,9 +124,9 @@ 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::illegalArgument(String::from( + _ => Err(Exceptions::illegalArgument( "model year argument out of range", - ))), + )), } } diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index f0a8d78..2d334ad 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -49,9 +49,7 @@ impl GenericGFPoly { */ pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { if coefficients.is_empty() { - return Err(Exceptions::illegalArgument(String::from( - "coefficients cannot be empty", - ))); + return Err(Exceptions::illegalArgument("coefficients cannot be empty")); } Ok(Self { field, From bfcdb397ad5bda17490f2eeeff857d98bd787b99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 11:25:01 +0000 Subject: [PATCH 5/6] remove even more needless string conversions --- src/aztec/decoder.rs | 2 +- src/datamatrix/decoder/decoded_bit_stream_parser.rs | 2 +- src/pdf417/decoder/ec/error_correction.rs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index f584b69..a755d52 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -164,7 +164,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { result.push_str( &encdr .decode(&decoded_bytes, encoding::DecoderTrap::Strict) - .map_err(|a| Exceptions::illegalState(a.to_string()))?, + .map_err(|a| Exceptions::illegalState(a))?, ); decoded_bytes.clear(); diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index 946417e..ab99204 100644 --- a/src/datamatrix/decoder/decoded_bit_stream_parser.rs +++ b/src/datamatrix/decoder/decoded_bit_stream_parser.rs @@ -755,7 +755,7 @@ fn decodeBase256Segment( result.append_string( &encoding::all::ISO_8859_1 .decode(&bytes, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parse(e.to_string()))?, + .map_err(|e| Exceptions::parse(e))?, ); byteSegments.push(bytes); diff --git a/src/pdf417/decoder/ec/error_correction.rs b/src/pdf417/decoder/ec/error_correction.rs index 6c7dc59..15fb758 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -103,7 +103,7 @@ pub fn decode( // 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::checksum(file!().to_string())); + return Err(Exceptions::checksum(file!())); } received[position as usize] = field.subtract(received[position as usize], errorMagnitudes[i]); @@ -140,7 +140,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::checksum(file!().to_string())); + return Err(Exceptions::checksum(file!())); } r = rLastLast; let mut q = ModulusPoly::getZero(field); //field.getZero(); @@ -162,7 +162,7 @@ fn runEuclideanAlgorithm( let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::checksum(file!().to_string())); + return Err(Exceptions::checksum(file!())); } let inverse = field.inverse(sigmaTildeAtZero)?; @@ -190,7 +190,7 @@ fn findErrorLocations( i += 1; } if e != numErrors { - return Err(Exceptions::checksum(file!().to_string())); + return Err(Exceptions::checksum(file!())); } Ok(result) } From 935519ced51bdec653013488bf177203365127d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vuka=C5=A1in=20Stepanovi=C4=87?= Date: Wed, 15 Feb 2023 12:52:59 +0000 Subject: [PATCH 6/6] rename helper methods --- src/aztec/aztec_reader.rs | 2 +- src/aztec/aztec_writer.rs | 4 +- src/aztec/decoder.rs | 29 ++--- src/aztec/detector.rs | 6 +- src/aztec/encoder/aztec_encoder.rs | 16 +-- src/aztec/encoder/high_level_encoder.rs | 4 +- src/aztec/encoder/state.rs | 4 +- src/aztec/encoder/token.rs | 2 +- src/client/result/AddressBookParsedResult.rs | 6 +- src/client/result/CalendarParsedResult.rs | 26 ++--- src/client/result/ResultParser.rs | 2 +- src/client/result/VINResultParser.rs | 19 +--- src/common/bit_array.rs | 8 +- src/common/bit_matrix.rs | 20 ++-- src/common/bit_source.rs | 2 +- src/common/character_set_eci.rs | 2 +- src/common/default_grid_sampler.rs | 4 +- .../detector/monochrome_rectangle_detector.rs | 4 +- .../detector/white_rectangle_detector.rs | 12 +- src/common/global_histogram_binarizer.rs | 2 +- src/common/grid_sampler.rs | 4 +- src/common/minimal_eci_input.rs | 16 +-- src/common/otsu_level_binarizer.rs | 2 +- src/common/reedsolomon/generic_gf.rs | 4 +- src/common/reedsolomon/generic_gf_poly.rs | 14 ++- src/common/reedsolomon/reedsolomon_decoder.rs | 16 +-- src/common/reedsolomon/reedsolomon_encoder.rs | 8 +- src/datamatrix/data_matrix_reader.rs | 12 +- src/datamatrix/data_matrix_writer.rs | 10 +- src/datamatrix/decoder/bit_matrix_parser.rs | 6 +- src/datamatrix/decoder/data_block.rs | 2 +- .../decoder/decoded_bit_stream_parser.rs | 75 +++++-------- src/datamatrix/decoder/version.rs | 4 +- .../detector/datamatrix_detector.rs | 2 +- .../zxing_cpp_detector/cpp_new_detector.rs | 4 +- .../zxing_cpp_detector/dm_regression_line.rs | 20 +--- .../zxing_cpp_detector/edge_tracer.rs | 23 ++-- .../detector/zxing_cpp_detector/util.rs | 2 +- src/datamatrix/encoder/ascii_encoder.rs | 10 +- src/datamatrix/encoder/base256_encoder.rs | 20 ++-- src/datamatrix/encoder/c40_encoder.rs | 12 +- src/datamatrix/encoder/default_placement.rs | 2 +- src/datamatrix/encoder/edifact_encoder.rs | 35 +++--- src/datamatrix/encoder/encoder_context.rs | 4 +- src/datamatrix/encoder/error_correction.rs | 16 +-- src/datamatrix/encoder/high_level_encoder.rs | 12 +- src/datamatrix/encoder/minimal_encoder.rs | 8 +- src/datamatrix/encoder/symbol_info.rs | 6 +- src/datamatrix/encoder/x12_encoder.rs | 2 +- src/exceptions.rs | 92 +++++----------- src/helpers.rs | 22 ++-- src/luma_luma_source.rs | 2 +- src/luminance_source.rs | 6 +- .../decoder/decoded_bit_stream_parser.rs | 2 +- src/maxicode/decoder/maxicode_decoder.rs | 2 +- src/maxicode/detector.rs | 14 +-- src/maxicode/maxi_code_reader.rs | 4 +- src/multi/generic_multiple_barcode_reader.rs | 2 +- src/multi/qrcode/detector/multi_detector.rs | 2 +- .../detector/multi_finder_pattern_finder.rs | 6 +- src/multi/qrcode/qr_code_multi_reader.rs | 2 +- src/multi_format_reader.rs | 2 +- src/multi_format_writer.rs | 2 +- src/oned/coda_bar_reader.rs | 29 +++-- src/oned/coda_bar_writer.rs | 14 +-- src/oned/code_128_reader.rs | 16 +-- src/oned/code_128_writer.rs | 42 +++---- src/oned/code_39_reader.rs | 49 ++++----- src/oned/code_39_writer.rs | 28 ++--- src/oned/code_93_reader.rs | 52 ++++----- src/oned/code_93_writer.rs | 24 ++-- src/oned/ean_13_reader.rs | 15 +-- src/oned/ean_13_writer.rs | 18 +-- src/oned/ean_8_reader.rs | 10 +- src/oned/ean_8_writer.rs | 14 ++- src/oned/itf_reader.rs | 16 ++- src/oned/itf_writer.rs | 12 +- src/oned/multi_format_one_d_reader.rs | 4 +- src/oned/multi_format_upc_ean_reader.rs | 4 +- src/oned/one_d_code_writer.rs | 14 +-- src/oned/one_d_reader.rs | 8 +- src/oned/rss/abstract_rss_reader.rs | 2 +- src/oned/rss/expanded/binary_util.rs | 13 +-- .../decoders/abstract_expanded_decoder.rs | 2 +- .../expanded/decoders/ai_01392x_decoder.rs | 2 +- .../expanded/decoders/ai_01393x_decoder.rs | 2 +- .../expanded/decoders/ai_013x0x1x_decoder.rs | 2 +- .../expanded/decoders/ai_013x0x_decoder.rs | 2 +- .../rss/expanded/decoders/decoded_numeric.rs | 2 +- .../rss/expanded/decoders/field_parser.rs | 12 +- .../decoders/general_app_id_decoder.rs | 16 +-- src/oned/rss/expanded/rss_expanded_reader.rs | 67 ++++++----- src/oned/rss/rss_14_reader.rs | 30 ++--- src/oned/upc_a_reader.rs | 2 +- src/oned/upc_a_writer.rs | 2 +- src/oned/upc_e_reader.rs | 20 ++-- src/oned/upc_e_writer.rs | 26 +++-- src/oned/upc_ean_extension_2_support.rs | 12 +- src/oned/upc_ean_extension_5_support.rs | 14 +-- src/oned/upc_ean_reader.rs | 26 ++--- src/pdf417/decoder/bounding_box.rs | 32 +++--- .../decoder/decoded_bit_stream_parser.rs | 38 +++---- src/pdf417/decoder/ec/error_correction.rs | 8 +- src/pdf417/decoder/ec/modulus_gf.rs | 4 +- src/pdf417/decoder/ec/modulus_poly.rs | 8 +- .../decoder/pdf_417_scanning_decoder.rs | 22 ++-- src/pdf417/detector/pdf_417_detector.rs | 2 +- src/pdf417/encoder/compaction.rs | 2 +- src/pdf417/encoder/pdf_417.rs | 10 +- .../encoder/pdf_417_error_correction.rs | 15 ++- .../encoder/pdf_417_high_level_encoder.rs | 104 ++++++++---------- src/pdf417/pdf_417_reader.rs | 4 +- src/pdf417/pdf_417_writer.rs | 10 +- src/planar_yuv_luminance_source.rs | 4 +- src/qrcode/decoder/bit_matrix_parser.rs | 15 +-- src/qrcode/decoder/data_block.rs | 2 +- src/qrcode/decoder/data_mask.rs | 2 +- .../decoder/decoded_bit_stream_parser.rs | 65 ++++++----- src/qrcode/decoder/error_correction_level.rs | 4 +- src/qrcode/decoder/mode.rs | 4 +- src/qrcode/decoder/qrcode_decoder.rs | 2 +- src/qrcode/decoder/version.rs | 6 +- .../detector/alignment_pattern_finder.rs | 4 +- src/qrcode/detector/finder_pattern_finder.rs | 18 +-- src/qrcode/detector/qrcode_detector.rs | 12 +- src/qrcode/encoder/mask_util.rs | 2 +- src/qrcode/encoder/matrix_util.rs | 16 +-- src/qrcode/encoder/minimal_encoder.rs | 70 +++++------- src/qrcode/encoder/qrcode_encoder.rs | 65 +++++------ src/qrcode/qr_code_reader.rs | 22 ++-- src/qrcode/qr_code_writer.rs | 12 +- src/rgb_luminance_source.rs | 4 +- src/svg_luminance_source.rs | 6 +- 133 files changed, 858 insertions(+), 1044 deletions(-) diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index 7c9ef34..6118bab 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::notFoundEmpty()); + return Err(Exceptions::notFound); }; let points = detectorRXingResult.getPoints(); diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index f376561..4bbc256 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -59,7 +59,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::illegalArgumentEmpty())?, + .ok_or(Exceptions::illegalArgument)?, ); } } @@ -95,7 +95,7 @@ fn encode( layers: i32, ) -> Result { if format != BarcodeFormat::AZTEC { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "can only encode AZTEC, but got {format:?}" ))); } diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index a755d52..f8b6b25 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -164,13 +164,13 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { result.push_str( &encdr .decode(&decoded_bytes, encoding::DecoderTrap::Strict) - .map_err(|a| Exceptions::illegalState(a))?, + .map_err(|a| Exceptions::illegalStateWith(a))?, ); decoded_bytes.clear(); match n { 0 => result.push(29 as char), // translate FNC1 as ASCII 29 - 7 => return Err(Exceptions::format("FLG(7) is reserved and illegal")), // FLG(7) is reserved and illegal + 7 => return Err(Exceptions::formatWith("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; @@ -182,7 +182,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::format("Not a decimal digit")); + return Err(Exceptions::formatWith("Not a decimal digit")); // Not a decimal digit } eci = eci * 10 + (next_digit - 2); @@ -190,7 +190,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result { } let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); if charset_eci.is_err() { - return Err(Exceptions::format("Charset must exist")); + return Err(Exceptions::formatWith("Charset must exist")); } encdr = CharacterSetECI::getCharset(&charset_eci?); } @@ -203,17 +203,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::indexOutOfBoundsEmpty())?, - ); - if str - .chars() - .nth(6) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? - == 'L' - { + shift_table = getTable(str.chars().nth(5).ok_or(Exceptions::indexOutOfBounds)?); + if str.chars().nth(6).ok_or(Exceptions::indexOutOfBounds)? == 'L' { latch_table = shift_table; } } else { @@ -234,7 +225,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::illegalState("bad encoding")); + return Err(Exceptions::illegalStateWith("bad encoding")); } // result.push_str(decodedBytes.toString(encoding.name())); //} catch (UnsupportedEncodingException uee) { @@ -286,7 +277,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { 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::illegalState("Bad table")), + _ => Err(Exceptions::illegalStateWith("Bad table")), } // switch (table) { // case UPPER: @@ -347,7 +338,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::format(format!( + return Err(Exceptions::formatWith(format!( "numCodewords {num_codewords}< numDataCodewords{num_data_codewords}" ))); } @@ -380,7 +371,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::formatEmpty()); + 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 097947b..d7afba2 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -127,7 +127,7 @@ impl<'a> Detector<'_> { || !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[3]) { - return Err(Exceptions::notFound("no valid points")); + return Err(Exceptions::notFoundWith("no valid points")); } let length = 2 * self.nb_center_layers; // Get the bits around the bull's eye @@ -208,7 +208,7 @@ impl<'a> Detector<'_> { return Ok(shift); } } - Err(Exceptions::notFound("rotation failure")) + Err(Exceptions::notFoundWith("rotation failure")) } /** @@ -320,7 +320,7 @@ impl<'a> Detector<'_> { } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } self.compact = self.nb_center_layers == 5; diff --git a/src/aztec/encoder/aztec_encoder.rs b/src/aztec/encoder/aztec_encoder.rs index baf7b17..6d6a609 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::illegalArgument(format!("'{data}' cannot be encoded as ISO_8859_1"))); + return Err(Exceptions::illegalArgumentWith(format!("'{data}' cannot be encoded as ISO_8859_1"))); }; encode_bytes_simple(&bytes) } @@ -75,7 +75,7 @@ pub fn encode( if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) { encode_bytes(&bytes, minECCPercent, userSpecifiedLayers) } else { - Err(Exceptions::illegalArgument(format!( + Err(Exceptions::illegalArgumentWith(format!( "'{data}' cannot be encoded as ISO_8859_1" ))) } @@ -102,7 +102,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::illegalArgument(format!( + Err(Exceptions::illegalArgumentWith(format!( "'{data}' cannot be encoded as ISO_8859_1" ))) } @@ -178,7 +178,7 @@ pub fn encode_bytes_with_charset( MAX_NB_BITS }) { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Illegal value {user_specified_layers} for layers" ))); } @@ -187,13 +187,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::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "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::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Data to large for user specified layer", )); } @@ -207,7 +207,7 @@ pub fn encode_bytes_with_charset( loop { // for (int i = 0; ; i++) { if i > MAX_NB_BITS { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Data too large for an Aztec code", )); } @@ -482,7 +482,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::illegalArgument(format!( + _ => Err(Exceptions::illegalArgumentWith(format!( "Unsupported word size {wordSize}" ))), } diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index 108258f..307efa8 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -248,7 +248,9 @@ impl HighLevelEncoder { initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; } } else { - return Err(Exceptions::illegalArgument("No ECI code for character set")); + return Err(Exceptions::illegalArgumentWith( + "No ECI code for character set", + )); } // if self.charset != null { // CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset); diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index bb82b84..2b1ca69 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -80,7 +80,7 @@ impl State { token.add(0, 3); // 0: FNC1 } else */ if eci > 999999 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "ECI code must be between 0 and 999999", )); // throw new IllegalArgumentException("ECI code must be between 0 and 999999"); @@ -88,7 +88,7 @@ impl State { let Ok(eci_digits) = encoding::all::ISO_8859_1 .encode(&format!("{eci}"), encoding::EncoderTrap::Strict) else { - return Err(Exceptions::illegalArgumentEmpty()) + return Err(Exceptions::illegalArgument) }; // 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 5111904..975fac4 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -31,7 +31,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::illegalState( + TokenType::Empty => Err(Exceptions::illegalStateWith( "cannot appendTo on Empty final item", )), } diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index 28313d5..8a40f3d 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -120,17 +120,17 @@ impl AddressBookParsedRXingResult { geo: Vec, ) -> Result { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Phone numbers and types lengths differ", )); } if emails.len() != email_types.len() && !email_types.is_empty() { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Emails and types lengths differ", )); } if addresses.len() != address_types.len() && !address_types.is_empty() { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Addresses and types lengths differ", )); } diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index e782a78..00f8fc0 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -166,7 +166,7 @@ impl CalendarParsedRXingResult { */ fn parseDate(when: String) -> Result { if !DATE_TIME.is_match(&when) { - return Err(Exceptions::parse(when)); + return Err(Exceptions::parseWith(when)); } if when.len() == 8 { // Show only year/month/day @@ -177,20 +177,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::parse(e.to_string())), + Err(e) => Err(Exceptions::parseWith(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::indexOutOfBoundsEmpty())? - == 'Z' - { + if when.len() == 16 && when.chars().nth(15).ok_or(Exceptions::indexOutOfBounds)? == '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::parse(format!("couldn't parse string: {e}"))), + Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))), }; } // Try once more, with weird tz formatting @@ -200,14 +194,14 @@ impl CalendarParsedRXingResult { let tz_parsed: Tz = match tz_part.parse() { Ok(time_zone) => time_zone, Err(e) => { - return Err(Exceptions::parse(format!( + return Err(Exceptions::parseWith(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::parse(format!("couldn't parse string: {e}"))), + Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))), }; } @@ -215,7 +209,9 @@ 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::parse(format!("couldn't parse local time: {e}"))), + Err(e) => Err(Exceptions::parseWith(format!( + "couldn't parse local time: {e}" + ))), }; } Self::parseDateTimeString(&when) @@ -252,7 +248,7 @@ impl CalendarParsedRXingResult { let z = parseable .as_str() .parse::() - .map_err(|e| Exceptions::parse(e.to_string()))?; + .map_err(|e| Exceptions::parseWith(e.to_string()))?; durationMS += unit * z; } } @@ -277,7 +273,7 @@ impl CalendarParsedRXingResult { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { Ok(dtm.timestamp()) } else { - Err(Exceptions::parse(format!( + Err(Exceptions::parseWith(format!( "Couldn't parse {dateTimeString}" ))) } diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index 960eb05..21d3cd3 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::illegalState("UnsupportedEncodingException")) + Err(Exceptions::illegalStateWith("UnsupportedEncodingException")) } } diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index 6ee41a1..1eada90 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -71,16 +71,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::illegalArgumentEmpty())?, - )?; + * vin_char_value(vin.chars().nth(i).ok_or(Exceptions::illegalArgument)?)?; } - let check_to_char = vin - .chars() - .nth(8) - .ok_or(Exceptions::illegalArgumentEmpty())?; + let check_to_char = vin.chars().nth(8).ok_or(Exceptions::illegalArgument)?; let expected_check_char = check_char((sum % 11) as u8)?; Ok(check_to_char == expected_check_char) } @@ -91,7 +84,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::illegalArgument("vin char out of range")), + _ => Err(Exceptions::illegalArgumentWith("vin char out of range")), } } @@ -101,7 +94,7 @@ fn vin_position_weight(position: usize) -> Result { 8 => Ok(10), 9 => Ok(0), 10..=17 => Ok(19 - position), - _ => Err(Exceptions::illegalArgument( + _ => Err(Exceptions::illegalArgumentWith( "vin position weight out of bounds", )), } @@ -111,7 +104,7 @@ fn check_char(remainder: u8) -> Result { match remainder { 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), - _ => Err(Exceptions::illegalArgument("remainder too high")), + _ => Err(Exceptions::illegalArgumentWith("remainder too high")), } } @@ -124,7 +117,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::illegalArgument( + _ => Err(Exceptions::illegalArgumentWith( "model year argument out of range", )), } diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 6c5fd8c..41c5292 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -168,7 +168,7 @@ impl BitArray { pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } if end == start { return Ok(()); @@ -211,7 +211,7 @@ impl BitArray { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result { let mut end = end; if end < start || end > self.size { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } if end == start { return Ok(true); // empty range matches @@ -253,7 +253,7 @@ impl BitArray { */ pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { if num_bits > 32 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "num bits must be between 0 and 32", )); } @@ -286,7 +286,7 @@ impl BitArray { pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { if self.size != other.size { - return Err(Exceptions::illegalArgument("Sizes don't match")); + return Err(Exceptions::illegalArgumentWith("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 2d0c893..824fc1f 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -65,7 +65,7 @@ impl BitMatrix { */ pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Both dimensions must be greater than 0", )); } @@ -137,12 +137,12 @@ impl BitMatrix { if string_representation .chars() .nth(pos) - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? == '\n' || string_representation .chars() .nth(pos) - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? == '\r' { if bitsPos > rowStartPos { @@ -151,7 +151,7 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgument("row lengths do not match")); + return Err(Exceptions::illegalArgumentWith("row lengths do not match")); } rowStartPos = bitsPos; nRows += 1; @@ -166,7 +166,7 @@ impl BitMatrix { bits[bitsPos] = false; bitsPos += 1; } else { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "illegal character encountered: {}", string_representation[pos..].to_owned() ))); @@ -180,7 +180,7 @@ impl BitMatrix { // first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(Exceptions::illegalArgument("row lengths do not match")); + return Err(Exceptions::illegalArgumentWith("row lengths do not match")); } nRows += 1; } @@ -307,7 +307,7 @@ impl BitMatrix { pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "input matrix dimensions do not match", )); } @@ -359,14 +359,14 @@ impl BitMatrix { // )); // } if height < 1 || width < 1 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "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::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "the region must fit inside the matrix", )); } @@ -440,7 +440,7 @@ impl BitMatrix { self.rotate180(); Ok(()) } - _ => Err(Exceptions::illegalArgument( + _ => Err(Exceptions::illegalArgumentWith( "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 b1a54a5..499d38b 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -70,7 +70,7 @@ impl BitSource { */ pub fn readBits(&mut self, numBits: usize) -> Result { if !(1..=32).contains(&numBits) || numBits > self.available() { - return Err(Exceptions::illegalArgument(numBits.to_string())); + return Err(Exceptions::illegalArgumentWith(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 284127b..b5b2653 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -244,7 +244,7 @@ impl CharacterSetECI { 28 => Ok(CharacterSetECI::Big5), 29 => Ok(CharacterSetECI::GB18030), 30 => Ok(CharacterSetECI::EUC_KR), - _ => Err(Exceptions::notFound("Bad ECI Value")), + _ => Err(Exceptions::notFoundWith("Bad ECI Value")), } } diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index f890394..0a4932d 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -67,7 +67,7 @@ impl GridSampler for DefaultGridSampler { transform: &PerspectiveTransform, ) -> Result { if dimensionX == 0 || dimensionY == 0 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut bits = BitMatrix::new(dimensionX, dimensionY)?; let mut points = vec![0.0; 2 * dimensionX as usize]; @@ -98,7 +98,7 @@ impl GridSampler for DefaultGridSampler { // } if image .try_get(points[x] as u32, points[x + 1] as u32) - .ok_or(Exceptions::notFound( + .ok_or(Exceptions::notFoundWith( "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 fd3e43e..c59f697 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -200,13 +200,13 @@ impl<'a> MonochromeRectangleDetector<'_> { } } } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } lastRange_z = range; y += deltaY; x += deltaX } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index 8e028de..7d0dd2d 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -77,7 +77,7 @@ impl<'a> WhiteRectangleDetector<'_> { || downInit >= image.getHeight() as i32 || rightInit >= image.getWidth() as i32 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(WhiteRectangleDetector { @@ -223,7 +223,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if z.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut t: Option = None; @@ -241,7 +241,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if t.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut x: Option = None; @@ -259,7 +259,7 @@ impl<'a> WhiteRectangleDetector<'_> { } if x.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut y: Option = None; @@ -277,12 +277,12 @@ impl<'a> WhiteRectangleDetector<'_> { } if y.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index b9e5431..0a70f43 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -233,7 +233,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::notFound( + return Err(Exceptions::notFoundWith( "secondPeak - firstPeak <= numBuckets / 16 ", )); } diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index 5fac919..2b05c1e 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -145,7 +145,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::notFoundEmpty()); + return Err(Exceptions::notFound); } nudged = false; if x == -1 { @@ -172,7 +172,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::notFoundEmpty()); + return Err(Exceptions::notFound); } nudged = false; if x == -1 { diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index b8f6c4e..c782a3f 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -67,10 +67,10 @@ impl ECIInput for MinimalECIInput { */ fn charAt(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBounds(index.to_string())); + return Err(Exceptions::indexOutOfBoundsWith(index.to_string())); } if self.isECI(index as u32)? { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "value at {index} is not a character but an ECI" ))); } @@ -103,13 +103,13 @@ impl ECIInput for MinimalECIInput { */ fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { if start > end || end > self.length() { - return Err(Exceptions::indexOutOfBoundsEmpty()); + return Err(Exceptions::indexOutOfBounds); } 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::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "value at {i} is not a character but an ECI" ))); } @@ -131,7 +131,7 @@ impl ECIInput for MinimalECIInput { */ fn isECI(&self, index: u32) -> Result { if index >= self.length() as u32 { - return Err(Exceptions::indexOutOfBoundsEmpty()); + return Err(Exceptions::indexOutOfBounds); } Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) } @@ -156,10 +156,10 @@ impl ECIInput for MinimalECIInput { */ fn getECIValue(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBoundsEmpty()); + return Err(Exceptions::indexOutOfBounds); } if !self.isECI(index as u32)? { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "value at {index} is not an ECI but a character" ))); } @@ -248,7 +248,7 @@ impl MinimalECIInput { */ pub fn isFNC1(&self, index: usize) -> Result { if index >= self.length() { - return Err(Exceptions::indexOutOfBoundsEmpty()); + return Err(Exceptions::indexOutOfBounds); } Ok(self.bytes[index] == 1000) } diff --git a/src/common/otsu_level_binarizer.rs b/src/common/otsu_level_binarizer.rs index a4f63ca..c4d4cf0 100644 --- a/src/common/otsu_level_binarizer.rs +++ b/src/common/otsu_level_binarizer.rs @@ -19,7 +19,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::illegalArgumentEmpty()) + return Err(Exceptions::illegalArgument) }; buff }; diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index 698fba5..3189216 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -133,7 +133,7 @@ impl GenericGF { */ pub fn log(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } // let pos: usize = a.try_into().unwrap(); Ok(self.logTable[a as usize]) @@ -144,7 +144,7 @@ impl GenericGF { */ pub fn inverse(&self, a: i32) -> Result { if a == 0 { - return Err(Exceptions::arithmeticEmpty()); + 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 2d334ad..42669e5 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -49,7 +49,9 @@ impl GenericGFPoly { */ pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { if coefficients.is_empty() { - return Err(Exceptions::illegalArgument("coefficients cannot be empty")); + return Err(Exceptions::illegalArgumentWith( + "coefficients cannot be empty", + )); } Ok(Self { field, @@ -138,7 +140,7 @@ impl GenericGFPoly { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "GenericGFPolys do not have same GenericGF field", )); } @@ -175,7 +177,7 @@ impl GenericGFPoly { pub fn multiply(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "GenericGFPolys do not have same GenericGF field", )); } @@ -250,12 +252,12 @@ impl GenericGFPoly { other: &GenericGFPoly, ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { if self.field != other.field { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "GenericGFPolys do not have same GenericGF field", )); } if other.isZero() { - return Err(Exceptions::illegalArgument("Divide by 0")); + return Err(Exceptions::illegalArgumentWith("Divide by 0")); } let mut quotient = self.getZero(); @@ -264,7 +266,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::illegalArgument("arithmetic issue")), + Err(_issue) => return Err(Exceptions::illegalArgumentWith("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 292b967..000ba99 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -77,7 +77,7 @@ impl ReedSolomonDecoder { return Ok(0); } let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else { - return Err(Exceptions::reedSolomonEmpty()); + return Err(Exceptions::reedSolomon); }; let sigmaOmega = self.runEuclideanAlgorithm( &GenericGF::buildMonomial(self.field, twoS as usize, 1), @@ -92,11 +92,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::reedSolomon("Bad error location")); + return Err(Exceptions::reedSolomonWith("Bad error location")); } let position: isize = received.len() as isize - 1 - log_value as isize; if position < 0 { - return Err(Exceptions::reedSolomon("Bad error location")); + return Err(Exceptions::reedSolomonWith("Bad error location")); } received[position as usize] = GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); @@ -134,7 +134,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::reedSolomon("r_{i-1} was zero")); + return Err(Exceptions::reedSolomonWith("r_{i-1} was zero")); } r = rLastLast; let mut q = r.getZero(); @@ -152,7 +152,7 @@ impl ReedSolomonDecoder { t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?; if r.getDegree() >= rLast.getDegree() { - return Err(Exceptions::reedSolomon(format!( + return Err(Exceptions::reedSolomonWith(format!( "Division algorithm failed to reduce polynomial? r: {r}, rLast: {rLast}" ))); } @@ -160,12 +160,12 @@ impl ReedSolomonDecoder { let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero")); + return Err(Exceptions::reedSolomonWith("sigmaTilde(0) was zero")); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, - Err(_err) => return Err(Exceptions::reedSolomon("ArithmetricException")), + Err(_err) => return Err(Exceptions::reedSolomonWith("ArithmetricException")), }; let sigma = t.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse); @@ -193,7 +193,7 @@ impl ReedSolomonDecoder { } } if e != numErrors { - return Err(Exceptions::reedSolomon( + return Err(Exceptions::reedSolomonWith( "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 1a6476e..ce0b2e3 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -73,11 +73,11 @@ impl ReedSolomonEncoder { pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<(), Exceptions> { if ec_bytes == 0 { - return Err(Exceptions::illegalArgument("No error correction bytes")); + return Err(Exceptions::illegalArgumentWith("No error correction bytes")); } let data_bytes = to_encode.len() - ec_bytes; if data_bytes == 0 { - return Err(Exceptions::illegalArgument("No data bytes provided")); + return Err(Exceptions::illegalArgumentWith("No data bytes provided")); } let fld = self.field; let generator = self.buildGenerator(ec_bytes); @@ -86,9 +86,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::reedSolomonEmpty())?)? - .1; + let remainder = &info.divide(generator.ok_or(Exceptions::reedSolomon)?)?.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 671ea3b..2b9d530 100644 --- a/src/datamatrix/data_matrix_reader.rs +++ b/src/datamatrix/data_matrix_reader.rs @@ -105,7 +105,7 @@ impl Reader for DataMatrixReader { DECODER.decode(&bits)? } } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); }; // decoderRXingResult = DECODER.decode(detectorRXingResult.getBits())?; @@ -181,10 +181,10 @@ impl DataMatrixReader { */ fn extractPureBits(&self, image: &BitMatrix) -> Result { let Some(leftTopBlack) = image.getTopLeftOnBit() else { - return Err(Exceptions::notFoundEmpty()) + return Err(Exceptions::notFound) }; let Some(rightBottomBlack) = image.getBottomRightOnBit()else { - return Err(Exceptions::notFoundEmpty()) + return Err(Exceptions::notFound) }; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -197,7 +197,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::notFoundEmpty()); + return Err(Exceptions::notFound); // throw NotFoundException.getNotFoundInstance(); } @@ -234,12 +234,12 @@ impl DataMatrixReader { x += 1; } if x == width { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let moduleSize = x - leftTopBlack[0]; if moduleSize == 0 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(moduleSize) diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index a86d301..926d8f2 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -60,17 +60,17 @@ impl Writer for DataMatrixWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument("Found empty contents")); + return Err(Exceptions::illegalArgumentWith("Found empty contents")); } if format != &BarcodeFormat::DATA_MATRIX { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Can only encode DATA_MATRIX, but got {format:?}" ))); } if width < 0 || height < 0 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested dimensions can't be negative: {width}x{height}" ))); } @@ -121,7 +121,7 @@ impl Writer for DataMatrixWriter { if hasEncodingHint { let Some(EncodeHintValue::CharacterSet(char_set_name)) = hints.get(&EncodeHintType::CHARACTER_SET) else { - return Err(Exceptions::illegalArgument("charset does not exist")) + return Err(Exceptions::illegalArgumentWith("charset does not exist")) }; charset = encoding::label::encoding_from_whatwg_label(char_set_name); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); @@ -155,7 +155,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::notFound("symbol info is bad")) + return Err(Exceptions::notFoundWith("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 635ea6b..2226779 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -34,7 +34,7 @@ impl BitMatrixParser { pub fn new(bitMatrix: &BitMatrix) -> Result { let dimension = bitMatrix.getHeight(); if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let version = Self::readVersion(bitMatrix)?; @@ -178,7 +178,7 @@ impl BitMatrixParser { } if resultOffset != self.version.getTotalCodewords() as usize { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } Ok(result) @@ -456,7 +456,7 @@ impl BitMatrixParser { let symbolSizeColumns = version.getSymbolSizeColumns(); if bitMatrix.getHeight() != symbolSizeRows { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "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 9e769d8..09d1a84 100644 --- a/src/datamatrix/decoder/data_block.rs +++ b/src/datamatrix/decoder/data_block.rs @@ -138,7 +138,7 @@ impl DataBlock { } if rawCodewordsOffset != rawCodewords.len() { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } Ok(result) diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index ab99204..74ff8b9 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 return Err(Exceptions::formatEmpty()), + _ => 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::formatEmpty()), + 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::parseEmpty())?); + 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::format( + return Err(Exceptions::formatWith( "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::formatEmpty()); + return Err(Exceptions::format); } } } @@ -385,25 +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::parseEmpty())?, + char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?, ); upperShift = false; } else { result.append_char(c40char); } } else { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } } 1 => { if upperShift { - result.append_char( - char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?, - ); + 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::parseEmpty())?); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?); } shift = 0; } @@ -412,8 +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::parseEmpty())?, + char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?, ); upperShift = false; } else { @@ -432,26 +428,22 @@ fn decodeC40Segment( upperShift = true } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } shift = 0; } 3 => { if upperShift { - result.append_char( - char::from_u32(cValue + 224).ok_or(Exceptions::parseEmpty())?, - ); + 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::parseEmpty())?, - ); + result.append_char(char::from_u32(cValue + 96).ok_or(Exceptions::parse)?); } shift = 0; } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } if bits.available() == 0 { @@ -500,25 +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::parseEmpty())?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, ); upperShift = false; } else { result.append_char(textChar); } } else { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } } 1 => { if upperShift { - result.append_char( - char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?, - ); + 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::parseEmpty())?); + result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?); } shift = 0; } @@ -529,8 +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::parseEmpty())?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, ); upperShift = false; } else { @@ -549,7 +537,7 @@ fn decodeTextSegment( upperShift = true } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } shift = 0; @@ -559,8 +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::parseEmpty())?, + char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?, ); upperShift = false; } else { @@ -568,11 +555,11 @@ fn decodeTextSegment( } shift = 0; } else { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } if bits.available() == 0 { @@ -638,16 +625,12 @@ fn decodeAnsiX12Segment( _ => { if cValue < 14 { // 0 - 9 - result.append_char( - char::from_u32(cValue + 44).ok_or(Exceptions::parseEmpty())?, - ); + 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::parseEmpty())?, - ); + result.append_char(char::from_u32(cValue + 51).ok_or(Exceptions::parse)?); } else { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } } } @@ -702,7 +685,7 @@ fn decodeEdifactSegment( // 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::parseEmpty())?); + result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::parse)?); } if bits.available() == 0 { @@ -747,7 +730,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::formatEmpty()); + return Err(Exceptions::format); } *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; codewordPosition += 1; @@ -755,7 +738,7 @@ fn decodeBase256Segment( result.append_string( &encoding::all::ISO_8859_1 .decode(&bytes, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parse(e))?, + .map_err(|e| Exceptions::parseWith(e))?, ); byteSegments.push(bytes); diff --git a/src/datamatrix/decoder/version.rs b/src/datamatrix/decoder/version.rs index b443bad..f5e147d 100644 --- a/src/datamatrix/decoder/version.rs +++ b/src/datamatrix/decoder/version.rs @@ -105,7 +105,7 @@ impl Version { numColumns: u32, ) -> Result<&'static Version, Exceptions> { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } for version in VERSIONS.iter() { @@ -114,7 +114,7 @@ impl Version { } } - Err(Exceptions::formatEmpty()) + Err(Exceptions::format) } /** diff --git a/src/datamatrix/detector/datamatrix_detector.rs b/src/datamatrix/detector/datamatrix_detector.rs index bf6b39f..0c7e5c7 100644 --- a/src/datamatrix/detector/datamatrix_detector.rs +++ b/src/datamatrix/detector/datamatrix_detector.rs @@ -53,7 +53,7 @@ impl<'a> Detector<'_> { if let Some(point) = self.correctTopRight(&points) { points[3] = point; } else { - return Err(Exceptions::notFound("point 4 unfound")); + return Err(Exceptions::notFoundWith("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 b0d5d49..564d1cd 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs @@ -254,7 +254,7 @@ fn Scan( )); } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } pub fn detect( @@ -359,6 +359,6 @@ pub fn detect( } // #ifndef __cpp_impl_coroutine - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) // #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 c26b0e1..3a64bab 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: &RXingResultPoint) -> Result<(), Exceptions> { if self.direction_inward == RXingResultPoint::default() { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } self.points.push(*p); if self.points.len() == 1 { @@ -241,7 +241,7 @@ impl DMRegressionLine { end: &RXingResultPoint, ) -> Result { if self.points.len() <= 3 { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } // re-evaluate and filter out all points too far away. required for the gapSizes calculation. @@ -264,14 +264,8 @@ impl DMRegressionLine { // calculate the (expected average) distance of two adjacent pixels let unitPixelDist = RXingResultPoint::length(RXingResultPoint::bresenhamDirection( - &(*self - .points - .last() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? - - *self - .points - .first() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?), + &(*self.points.last().ok_or(Exceptions::indexOutOfBounds)? + - *self.points.first().ok_or(Exceptions::indexOutOfBounds)?), )) as f64; // calculate the width of 2 modules (first black pixel to first black pixel) @@ -294,11 +288,7 @@ impl DMRegressionLine { sumFront + self.distance( end, - &self.project( - self.points - .last() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, - ), + &self.project(self.points.last().ok_or(Exceptions::indexOutOfBounds)?), ) as f64, ); modSizes[0] = 0.0; // the first element is an invalid sumBack value, would be pop_front() if vector supported this diff --git a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs index a7f717d..e254ed9 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs @@ -199,7 +199,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 == RXingResultPoint::centered(&pEdge) { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } self.p = RXingResultPoint::centered(&pEdge); @@ -277,7 +277,7 @@ impl<'a> EdgeTracer<'_> { .points() .first() .as_ref() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?), + .ok_or(Exceptions::indexOutOfBounds)?), ) { return Ok(false); } @@ -307,9 +307,9 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?) + .ok_or(Exceptions::indexOutOfBounds)?) { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } if !line.points().is_empty() && &&self.p @@ -317,7 +317,7 @@ impl<'a> EdgeTracer<'_> { .points() .last() .as_ref() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? { return Ok(false); } @@ -363,7 +363,7 @@ impl<'a> EdgeTracer<'_> { line.points() .last() .as_ref() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ), ) < 1.0 { @@ -376,11 +376,7 @@ impl<'a> EdgeTracer<'_> { } else { RXingResultPoint::dot( RXingResultPoint::mainDirection(self.d), - self.p - - line - .points() - .last() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + self.p - line.points().last().ok_or(Exceptions::indexOutOfBounds)?, ) }; line.add(&self.p)?; @@ -393,10 +389,7 @@ impl<'a> EdgeTracer<'_> { } if !self.updateDirectionFromOrigin( &(self.p - line.project(&self.p) - + *line - .points() - .first() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?), + + *line.points().first().ok_or(Exceptions::indexOutOfBounds)?), ) { return Ok(false); } diff --git a/src/datamatrix/detector/zxing_cpp_detector/util.rs b/src/datamatrix/detector/zxing_cpp_detector/util.rs index 3067631..37ddd1e 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/util.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/util.rs @@ -26,7 +26,7 @@ pub fn intersect( l2: &DMRegressionLine, ) -> Result { if !(l1.isValid() && l2.isValid()) { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } 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 ec7fd38..e078a9f 100644 --- a/src/datamatrix/encoder/ascii_encoder.rs +++ b/src/datamatrix/encoder/ascii_encoder.rs @@ -31,12 +31,12 @@ impl Encoder for ASCIIEncoder { .getMessage() .chars() .nth(context.pos as usize) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, context .getMessage() .chars() .nth(context.pos as usize + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, )? as u8); context.pos += 2; } else { @@ -73,7 +73,9 @@ impl Encoder for ASCIIEncoder { } _ => { - return Err(Exceptions::illegalState(format!("Illegal mode: {newMode}"))); + return Err(Exceptions::illegalStateWith(format!( + "Illegal mode: {newMode}" + ))); } } } else if high_level_encoder::isExtendedASCII(c) { @@ -102,7 +104,7 @@ impl ASCIIEncoder { let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); Ok((num + 130) as char) } else { - Err(Exceptions::illegalArgument(format!( + Err(Exceptions::illegalArgumentWith(format!( "not digits: {digit1}{digit2}" ))) } diff --git a/src/datamatrix/encoder/base256_encoder.rs b/src/datamatrix/encoder/base256_encoder.rs index bc73eb7..f302efe 100644 --- a/src/datamatrix/encoder/base256_encoder.rs +++ b/src/datamatrix/encoder/base256_encoder.rs @@ -53,7 +53,7 @@ impl Encoder for Base256Encoder { context.updateSymbolInfoWithLength(currentSize); let mustPad = (context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() - currentSize as u32) > 0; @@ -62,27 +62,26 @@ impl Encoder for Base256Encoder { buffer.replace_range( 0..1, &char::from_u32(dataCount as u32) - .ok_or(Exceptions::parseEmpty())? + .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::parseEmpty())? + .ok_or(Exceptions::parse)? .to_string(), ); let (ci_pos, _) = buffer .char_indices() .nth(1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; buffer.insert( ci_pos, - char::from_u32(dataCount as u32 % 250) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::indexOutOfBounds)?, ); } else { - return Err(Exceptions::illegalState(format!( + return Err(Exceptions::illegalStateWith(format!( "Message length not in valid ranges: {dataCount}" ))); } @@ -92,13 +91,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::indexOutOfBoundsEmpty())?, + buffer.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?, context.getCodewordCount() as u32 + 1, ) - .ok_or(Exceptions::parseEmpty())? 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 e3e6a45..98676e1 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -65,7 +65,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() as usize - curCodewordCount; @@ -140,7 +140,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() as usize - curCodewordCount; let rest = buffer.chars().count() % 3; @@ -182,7 +182,7 @@ impl C40Encoder { context: &mut EncoderContext, buffer: &mut String, ) -> Result<(), Exceptions> { - context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::formatEmpty())?); + context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::format)?); buffer.replace_range(0..3, ""); // buffer.delete(0, 3); Ok(()) @@ -205,7 +205,7 @@ impl C40Encoder { context.updateSymbolInfoWithLength(curCodewordCount); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() as usize - curCodewordCount; @@ -234,7 +234,9 @@ impl C40Encoder { context.writeCodeword(C40_UNLATCH); } } else { - return Err(Exceptions::illegalState("Unexpected case. Please report!")); + return Err(Exceptions::illegalStateWith( + "Unexpected case. Please report!", + )); } context.signalEncoderChange(ASCII_ENCODATION); diff --git a/src/datamatrix/encoder/default_placement.rs b/src/datamatrix/encoder/default_placement.rs index efebc72..b25d7f2 100644 --- a/src/datamatrix/encoder/default_placement.rs +++ b/src/datamatrix/encoder/default_placement.rs @@ -164,7 +164,7 @@ impl DefaultPlacement { .codewords .chars() .nth(pos) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32; + .ok_or(Exceptions::indexOutOfBounds)? 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 9ae75b5..82e1629 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -76,7 +76,7 @@ impl EdifactEncoder { context.updateSymbolInfo(); let mut available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() - context.getCodewordCount() as u32; let remaining = context.getRemainingCharacters(); @@ -85,7 +85,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + 1); available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() - context.getCodewordCount() as u32; } @@ -95,7 +95,7 @@ impl EdifactEncoder { } if count > 4 { - return Err(Exceptions::illegalState("Count must not exceed 4")); + return Err(Exceptions::illegalStateWith("Count must not exceed 4")); } let restChars = count - 1; let encoded = Self::encodeToCodewords(buffer)?; @@ -106,7 +106,7 @@ impl EdifactEncoder { context.updateSymbolInfoWithLength(context.getCodewordCount() + restChars); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() - context.getCodewordCount() as u32; if available >= 3 { @@ -147,30 +147,23 @@ impl EdifactEncoder { fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { - return Err(Exceptions::illegalState("StringBuilder must not be empty")); + return Err(Exceptions::illegalStateWith( + "StringBuilder must not be empty", + )); } - let c1 = sb - .chars() - .next() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + let c1 = sb.chars().next().ok_or(Exceptions::indexOutOfBounds)?; let c2 = if len >= 2 { - sb.chars() - .nth(1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + sb.chars().nth(1).ok_or(Exceptions::indexOutOfBounds)? } else { 0 as char }; let c3 = if len >= 3 { - sb.chars() - .nth(2) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + sb.chars().nth(2).ok_or(Exceptions::indexOutOfBounds)? } else { 0 as char }; let c4 = if len >= 4 { - sb.chars() - .nth(3) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + sb.chars().nth(3).ok_or(Exceptions::indexOutOfBounds)? } else { 0 as char }; @@ -180,12 +173,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::indexOutOfBoundsEmpty())?); + res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBounds)?); if len >= 2 { - res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBoundsEmpty())?); + res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBounds)?); } if len >= 3 { - res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBoundsEmpty())?); + res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBounds)?); } Ok(res) diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index 5d34815..f28bfc0 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -63,10 +63,10 @@ impl<'a> EncoderContext<'_> { ISO_8859_1_ENCODER .decode(&encoded_bytes, encoding::DecoderTrap::Strict) .map_err(|e| { - Exceptions::parse(format!("round trip decode should always work: {e}")) + Exceptions::parseWith(format!("round trip decode should always work: {e}")) })? } else { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "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 9e7a023..8f4e8ab 100644 --- a/src/datamatrix/encoder/error_correction.rs +++ b/src/datamatrix/encoder/error_correction.rs @@ -154,7 +154,7 @@ const ALOG: [u32; 255] = { */ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "The number of codewords does not match the selected symbol", )); } @@ -185,7 +185,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result Result Result Result 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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } 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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } 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 b89f4ee..51b66c9 100644 --- a/src/datamatrix/encoder/high_level_encoder.rs +++ b/src/datamatrix/encoder/high_level_encoder.rs @@ -221,18 +221,14 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( if forceC40 { c40Encoder.encodeMaximalC40(&mut context)?; - encodingMode = context - .getNewEncoding() - .ok_or(Exceptions::illegalStateEmpty())?; + encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?; context.resetEncoderSignal(); } while context.hasMoreCharacters() { encoders[encodingMode].encode(&mut context)?; if context.getNewEncoding().is_some() { - encodingMode = context - .getNewEncoding() - .ok_or(Exceptions::illegalStateEmpty())?; + encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?; context.resetEncoderSignal(); } } @@ -240,7 +236,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( context.updateSymbolInfo(); let capacity = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity(); if len < capacity as usize && encodingMode != ASCII_ENCODATION @@ -611,7 +607,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 { pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { // let hex = Integer.toHexString(c); // hex = "0000".substring(0, 4 - hex.length()) + hex; - Err(Exceptions::illegalArgument(format!( + Err(Exceptions::illegalArgumentWith(format!( "Illegal character: {c} (0x{c})" ))) } diff --git a/src/datamatrix/encoder/minimal_encoder.rs b/src/datamatrix/encoder/minimal_encoder.rs index b5e609b..c9e75d3 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<(), Ex if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() || edges[vertexIndex][edge.getEndMode()?.ordinal()] .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .cachedTotalSize > edge.cachedTotalSize { @@ -635,7 +635,7 @@ fn encodeMinimally(input: Rc) -> Result { } if minimalJ < 0 { - return Err(Exceptions::illegalState(format!( + return Err(Exceptions::illegalStateWith(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::formatEmpty()); + 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::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); }; 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 40df3f6..9ce0bef 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -128,7 +128,7 @@ impl SymbolInfo { 2 | 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::illegalState( + _ => Err(Exceptions::illegalStateWith( "Cannot handle this number of data regions", )), } @@ -140,7 +140,7 @@ impl SymbolInfo { 4 => Ok(2), 16 => Ok(4), 36 => Ok(6), - _ => Err(Exceptions::illegalState( + _ => Err(Exceptions::illegalStateWith( "Cannot handle this number of data regions", )), } @@ -310,7 +310,7 @@ impl<'a> SymbolInfoLookup<'a> { } } if fail { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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 3031d68..ee8adc3 100644 --- a/src/datamatrix/encoder/x12_encoder.rs +++ b/src/datamatrix/encoder/x12_encoder.rs @@ -81,7 +81,7 @@ impl X12Encoder { context.updateSymbolInfo(); let available = context .getSymbolInfo() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getDataCapacity() - context.getCodewordCount() as u32; let count = buffer.chars().count(); diff --git a/src/exceptions.rs b/src/exceptions.rs index 6b613d5..e33197a 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -22,110 +22,72 @@ pub enum Exceptions { ReaderDecodeException(), } +#[allow(non_upper_case_globals)] impl Exceptions { - pub fn illegalArgument>(x: I) -> Self { + pub const illegalArgument: Self = Self::IllegalArgumentException(None); + pub fn illegalArgumentWith>(x: I) -> Self { Self::IllegalArgumentException(Some(x.into())) } - pub fn illegalArgumentEmpty() -> Self { - Self::IllegalArgumentException(None) - } - - pub fn unsupportedOperation>(x: I) -> Self { + pub const unsupportedOperation: Self = Self::UnsupportedOperationException(None); + pub fn unsupportedOperationWith>(x: I) -> Self { Self::UnsupportedOperationException(Some(x.into())) } - pub fn unsupportedOperationEmpty() -> Self { - Self::UnsupportedOperationException(None) - } - - pub fn illegalState>(x: I) -> Self { + pub const illegalState: Self = Self::IllegalStateException(None); + pub fn illegalStateWith>(x: I) -> Self { Self::IllegalStateException(Some(x.into())) } - pub fn illegalStateEmpty() -> Self { - Self::IllegalStateException(None) - } - - pub fn arithmetic>(x: I) -> Self { + pub const arithmetic: Self = Self::ArithmeticException(None); + pub fn arithmeticWith>(x: I) -> Self { Self::ArithmeticException(Some(x.into())) } - pub fn arithmeticEmpty() -> Self { - Self::ArithmeticException(None) - } - - pub fn notFound>(x: I) -> Self { + pub const notFound: Self = Self::NotFoundException(None); + pub fn notFoundWith>(x: I) -> Self { Self::NotFoundException(Some(x.into())) } - pub fn notFoundEmpty() -> Self { - Self::NotFoundException(None) - } - - pub fn format>(x: I) -> Self { + pub const format: Self = Self::FormatException(None); + pub fn formatWith>(x: I) -> Self { Self::FormatException(Some(x.into())) } - pub fn formatEmpty() -> Self { - Self::FormatException(None) - } - - pub fn checksum>(x: I) -> Self { + pub const checksum: Self = Self::ChecksumException(None); + pub fn checksumWith>(x: I) -> Self { Self::ChecksumException(Some(x.into())) } - pub fn checksumEmpty() -> Self { - Self::ChecksumException(None) - } - - pub fn reader>(x: I) -> Self { + pub const reader: Self = Self::ReaderException(None); + pub fn readerWith>(x: I) -> Self { Self::ReaderException(Some(x.into())) } - pub fn readerEmpty() -> Self { - Self::ReaderException(None) - } - - pub fn writer>(x: I) -> Self { + pub const writer: Self = Self::WriterException(None); + pub fn writerWith>(x: I) -> Self { Self::WriterException(Some(x.into())) } - pub fn writerEmpty() -> Self { - Self::WriterException(None) - } - - pub fn reedSolomon>(x: I) -> Self { + pub const reedSolomon: Self = Self::ReedSolomonException(None); + pub fn reedSolomonWith>(x: I) -> Self { Self::ReedSolomonException(Some(x.into())) } - pub fn reedSolomonEmpty() -> Self { - Self::ReedSolomonException(None) - } - - pub fn indexOutOfBounds>(x: I) -> Self { + pub const indexOutOfBounds: Self = Self::IndexOutOfBoundsException(None); + pub fn indexOutOfBoundsWith>(x: I) -> Self { Self::IndexOutOfBoundsException(Some(x.into())) } - pub fn indexOutOfBoundsEmpty() -> Self { - Self::IndexOutOfBoundsException(None) - } - - pub fn runtime>(x: I) -> Self { + pub const runtime: Self = Self::RuntimeException(None); + pub fn runtimeWith>(x: I) -> Self { Self::RuntimeException(Some(x.into())) } - pub fn runtimeEmpty() -> Self { - Self::RuntimeException(None) - } - - pub fn parse>(x: I) -> Self { + pub const parse: Self = Self::ParseException(None); + pub fn parseWith>(x: I) -> Self { Self::ParseException(Some(x.into())) } - - pub fn parseEmpty() -> Self { - Self::ParseException(None) - } } impl fmt::Display for Exceptions { diff --git a/src/helpers.rs b/src/helpers.rs index 640391e..d1b9ef5 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -35,16 +35,16 @@ pub fn detect_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgument("file does not exist")); + return Err(Exceptions::illegalArgumentWith("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgument("file cannot be opened")); + return Err(Exceptions::illegalArgumentWith("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgument("file cannot be read")); + return Err(Exceptions::illegalArgumentWith("file cannot be read")); } let mut multi_format_reader = MultiFormatReader::default(); @@ -84,16 +84,16 @@ pub fn detect_multiple_in_svg_with_hints( let path = PathBuf::from(file_name); if !path.exists() { - return Err(Exceptions::illegalArgument("file does not exist")); + return Err(Exceptions::illegalArgumentWith("file does not exist")); } let Ok(mut file) = File::open(path) else { - return Err(Exceptions::illegalArgument("file cannot be opened")); + return Err(Exceptions::illegalArgumentWith("file cannot be opened")); }; let mut svg_data = Vec::new(); if file.read_to_end(&mut svg_data).is_err() { - return Err(Exceptions::illegalArgument("file cannot be read")); + return Err(Exceptions::illegalArgumentWith("file cannot be read")); } let multi_format_reader = MultiFormatReader::default(); @@ -126,7 +126,7 @@ pub fn detect_in_file_with_hints( hints: &mut DecodingHintDictionary, ) -> Result { let Ok(img) = image::open(file_name) else { - return Err(Exceptions::illegalArgument(format!("file '{file_name}' not found or cannot be opened"))); + return Err(Exceptions::illegalArgumentWith(format!("file '{file_name}' not found or cannot be opened"))); }; let mut multi_format_reader = MultiFormatReader::default(); @@ -160,7 +160,7 @@ pub fn detect_multiple_in_file_with_hints( hints: &mut DecodingHintDictionary, ) -> Result, Exceptions> { let img = image::open(file_name) - .map_err(|e| Exceptions::runtime(format!("couldn't read {file_name}: {e}")))?; + .map_err(|e| Exceptions::runtimeWith(format!("couldn't read {file_name}: {e}")))?; let multi_format_reader = MultiFormatReader::default(); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); @@ -247,7 +247,7 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Excepti let image: image::DynamicImage = bit_matrix.into(); match image.save(file_name) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::illegalArgument(format!( + Err(err) => Err(Exceptions::illegalArgumentWith(format!( "could not save file '{file_name}': {err}" ))), } @@ -259,7 +259,7 @@ pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exception match svg::save(file_name, &svg) { Ok(_) => Ok(()), - Err(err) => Err(Exceptions::illegalArgument(format!( + Err(err) => Err(Exceptions::illegalArgumentWith(format!( "could not save file '{}': {}", file_name, err ))), @@ -294,7 +294,7 @@ pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptio Ok(()) }() { Ok(_) => Ok(()), - Err(_) => Err(Exceptions::illegalArgument(format!( + Err(_) => Err(Exceptions::illegalArgumentWith(format!( "could not write to '{file_name}'" ))), } diff --git a/src/luma_luma_source.rs b/src/luma_luma_source.rs index 497844c..60387b3 100644 --- a/src/luma_luma_source.rs +++ b/src/luma_luma_source.rs @@ -95,7 +95,7 @@ impl LuminanceSource for Luma8LuminanceSource { } fn rotateCounterClockwise45(&self) -> Result, crate::Exceptions> { - Err(crate::Exceptions::unsupportedOperation( + Err(crate::Exceptions::unsupportedOperationWith( "This luminance source does not support rotation by 45 degrees.", )) } diff --git a/src/luminance_source.rs b/src/luminance_source.rs index 2c55378..b9cb0a8 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -91,7 +91,7 @@ pub trait LuminanceSource { _width: usize, _height: usize, ) -> Result, Exceptions> { - Err(Exceptions::unsupportedOperation( + Err(Exceptions::unsupportedOperationWith( "This luminance source does not support cropping.", )) } @@ -118,7 +118,7 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise(&self) -> Result, Exceptions> { - Err(Exceptions::unsupportedOperation( + Err(Exceptions::unsupportedOperationWith( "This luminance source does not support rotation by 90 degrees.", )) } @@ -130,7 +130,7 @@ pub trait LuminanceSource { * @return A rotated version of this object. */ fn rotateCounterClockwise45(&self) -> Result, Exceptions> { - Err(Exceptions::unsupportedOperation( + Err(Exceptions::unsupportedOperationWith( "This luminance source does not support rotation by 45 degrees.", )) } diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index c46ec43..6eb0714 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -86,7 +86,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::formatEmpty()); + 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 c43422f..cd46a15 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::notFoundEmpty()), + _ => return Err(Exceptions::notFound), } datawords[0..10].clone_from_slice(&codewords[0..10]); diff --git a/src/maxicode/detector.rs b/src/maxicode/detector.rs index 85eabc4..6e0ba50 100644 --- a/src/maxicode/detector.rs +++ b/src/maxicode/detector.rs @@ -318,7 +318,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::notFoundEmpty()); + return Err(Exceptions::notFound); }; // we should have an idea where the center is at this point, @@ -341,7 +341,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result Result Result std::cmp::Ordering { /// Read appropriate bits from a bitmatrix for the maxicode decoder pub fn read_bits(image: &BitMatrix) -> Result { - let enclosingRectangle = image - .getEnclosingRectangle() - .ok_or(Exceptions::notFoundEmpty())?; + let enclosingRectangle = image.getEnclosingRectangle().ok_or(Exceptions::notFound)?; 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 fd7041b..cda3284 100644 --- a/src/maxicode/maxi_code_reader.rs +++ b/src/maxicode/maxi_code_reader.rs @@ -126,10 +126,10 @@ impl MaxiCodeReader { fn extractPureBits(image: &BitMatrix) -> Result { let enclosingRectangleOption = image.getEnclosingRectangle(); if enclosingRectangleOption.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } - let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFoundEmpty())?; + let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFound)?; 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 b995a21..be4d91f 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::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(results) } diff --git a/src/multi/qrcode/detector/multi_detector.rs b/src/multi/qrcode/detector/multi_detector.rs index 0cf0dec..58697a7 100644 --- a/src/multi/qrcode/detector/multi_detector.rs +++ b/src/multi/qrcode/detector/multi_detector.rs @@ -53,7 +53,7 @@ impl<'a> MultiDetector<'_> { let infos = finder.findMulti(hints)?; if infos.is_empty() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } 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 43d9a7b..82913cb 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -93,7 +93,9 @@ impl<'a> MultiFinderPatternFinder<'_> { if size < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::notFound("Couldn't find enough finder patterns")); + return Err(Exceptions::notFoundWith( + "Couldn't find enough finder patterns", + )); } /* @@ -210,7 +212,7 @@ impl<'a> MultiFinderPatternFinder<'_> { if !results.is_empty() { Ok(results) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/multi/qrcode/qr_code_multi_reader.rs b/src/multi/qrcode/qr_code_multi_reader.rs index 3622614..031e01e 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::notFoundEmpty())); + return Err(output.err().unwrap_or(Exceptions::notFound)); } } diff --git a/src/multi_format_reader.rs b/src/multi_format_reader.rs index a19cbe0..cc1c4b1 100644 --- a/src/multi_format_reader.rs +++ b/src/multi_format_reader.rs @@ -192,6 +192,6 @@ impl MultiFormatReader { } } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/multi_format_writer.rs b/src/multi_format_writer.rs index 2de19ea..c99eb22 100644 --- a/src/multi_format_writer.rs +++ b/src/multi_format_writer.rs @@ -71,7 +71,7 @@ impl Writer for MultiFormatWriter { BarcodeFormat::DATA_MATRIX => Box::::default(), BarcodeFormat::AZTEC => Box::::default(), _ => { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "No encoder available for format {format:?}" ))) } diff --git a/src/oned/coda_bar_reader.rs b/src/oned/coda_bar_reader.rs index 2f0634f..8944b71 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::notFoundEmpty()); + return Err(Exceptions::notFound); } // 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::parseEmpty())?); + .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::notFoundEmpty()); + return Err(Exceptions::notFound); } self.validatePattern(startOffset)?; @@ -113,8 +113,7 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? - as usize] + .ok_or(Exceptions::indexOutOfBounds)? as usize] .to_string(), ); } @@ -123,23 +122,23 @@ impl OneDReader for CodaBarReader { .decodeRowRXingResult .chars() .next() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let endchar = self .decodeRowRXingResult .chars() .nth(self.decodeRowRXingResult.chars().count() - 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } // 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::notFoundEmpty()); + return Err(Exceptions::notFound); } if !matches!( @@ -243,7 +242,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? as usize]; for j in (0_usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -282,7 +281,7 @@ impl CodaBarReader { .decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? as usize]; for j in (0usize..=6).rev() { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for @@ -290,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::notFoundEmpty()); + return Err(Exceptions::notFound); } pattern >>= 1; } @@ -311,7 +310,7 @@ impl CodaBarReader { let mut i = row.getNextUnset(0); let end = row.getSize(); if i >= end { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut isWhite = true; let mut count = 0; @@ -363,7 +362,7 @@ impl CodaBarReader { i += 2; } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } 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 a773667..c79b005 100644 --- a/src/oned/coda_bar_writer.rs +++ b/src/oned/coda_bar_writer.rs @@ -43,12 +43,12 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let firstChar = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_ascii_uppercase(); let lastChar = contents .chars() .nth(contents.chars().count() - 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_ascii_uppercase(); let startsNormal = CodaBarReader::arrayContains(&START_END_CHARS, firstChar); let endsNormal = CodaBarReader::arrayContains(&START_END_CHARS, lastChar); @@ -56,7 +56,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar); if startsNormal { if !endsNormal { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Invalid start/end guards: {contents}" ))); } @@ -64,7 +64,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { contents.to_owned() } else if startsAlt { if !endsAlt { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Invalid start/end guards: {contents}" ))); } @@ -73,7 +73,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { } else { // Doesn't start with a guard if endsNormal || endsAlt { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Invalid start/end guards: {contents}" ))); } @@ -93,7 +93,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { ) { resultLength += 10; } else { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Cannot encode : '{ch}'" ))); } @@ -108,7 +108,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter { let mut c = contents .chars() .nth(index) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .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 f73d264..fd69040 100644 --- a/src/oned/code_128_reader.rs +++ b/src/oned/code_128_reader.rs @@ -50,7 +50,7 @@ impl OneDReader for Code128Reader { CODE_START_A => CODE_CODE_A, CODE_START_B => CODE_CODE_B, CODE_START_C => CODE_CODE_C, - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), }; let mut done = false; @@ -100,7 +100,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::formatEmpty()), + CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::format), _ => {} } @@ -294,21 +294,21 @@ impl OneDReader for Code128Reader { row.getSize().min(nextStart + (nextStart - lastStart) / 2), false, )? { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } // 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::checksumEmpty()); + 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::notFoundEmpty()); + return Err(Exceptions::notFound); } // Only bother if the result had at least one character, and if the checksum digit happened to @@ -329,7 +329,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::indexOutOfBoundsEmpty())?; + *rawByte = *rawCodes.get(i).ok_or(Exceptions::indexOutOfBounds)?; } let mut resultObject = RXingResult::new( &result, @@ -403,7 +403,7 @@ impl Code128Reader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn decodeCode( @@ -428,7 +428,7 @@ impl Code128Reader { if bestMatch >= 0 { Ok(bestMatch as u8) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } } diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index e8c0c6d..f12a011 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -99,7 +99,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result Result forcedCodeSet = CODE_CODE_A as i32, "B" => forcedCodeSet = CODE_CODE_B as i32, "C" => forcedCodeSet = CODE_CODE_C as i32, _ => { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Unsupported code set hint: {codeSetHint}" ))) } @@ -134,7 +134,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 127 { // no full Latin-1 character set available at the moment // shift and manual code change are not supported - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Bad character in input: ASCII value={c}" ))); } @@ -149,7 +149,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result 95 && c <= 127 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Bad character in input for forced code set A: ASCII value={c}" ))); } @@ -158,7 +158,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result Result Result, Exception while position < length { //Select code to use let newCodeSet = if forcedCodeSet == -1 { - chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalStateEmpty())? + chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalState)? } else { forcedCodeSet as usize // THIS IS RISKY }; @@ -208,7 +208,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception match contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? { ESCAPE_FNC_1 => patternIndex = CODE_FNC_1 as isize, ESCAPE_FNC_2 => patternIndex = CODE_FNC_2 as isize, @@ -228,7 +228,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? as isize - ' ' as isize; if patternIndex < 0 { @@ -240,7 +240,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception patternIndex = contents .chars() .nth(position) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? as isize - ' ' as isize } @@ -248,7 +248,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception // CODE_CODE_C if position + 1 == length { // this is the last character, but the encoding is C, which always encodes two characers - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Bad number of characters for digit only encoding.", )); } @@ -259,7 +259,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result, Exception .map(|(_u, c)| c) .collect(); patternIndex = s.parse::().map_err(|e| { - Exceptions::parse(format!("issue parsing {s}: {e}")) + Exceptions::parseWith(format!("issue parsing {s}: {e}")) })?; position += 1; } // Also incremented below @@ -535,7 +535,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; if contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? == ESCAPE_FNC_1 { addPattern( @@ -554,8 +554,9 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; .collect(); addPattern( &mut patterns, - s.parse::() - .map_err(|e| Exceptions::parse(format!("unable to parse {s} {e}")))?, + s.parse::().map_err(|e| { + Exceptions::parseWith(format!("unable to parse {s} {e}")) + })?, &mut checkSum, &mut checkWeight, i, @@ -570,7 +571,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; let mut patternIndex = match contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? { ESCAPE_FNC_1 => CODE_FNC_1 as isize, ESCAPE_FNC_2 => CODE_FNC_2 as isize, @@ -588,8 +589,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? - as isize + .ok_or(Exceptions::indexOutOfBounds)? as isize - ' ' as isize } }; @@ -680,7 +680,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; minPath: &mut Vec>, ) -> Result { if position >= contents.chars().count() { - return Err(Exceptions::illegalStateEmpty()); + return Err(Exceptions::illegalState); } let mCost = memoizedCost[charset.ordinal()][position]; if mCost > 0 { @@ -761,7 +761,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; } } if minCost == u32::MAX { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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 6a2d20c..d684bf3 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::notFoundEmpty()); + return Err(Exceptions::notFound); } 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::notFoundEmpty()); + return Err(Exceptions::notFound); } if self.usingCheckDigit { @@ -96,7 +96,7 @@ impl OneDReader for Code39Reader { self.decodeRowRXingResult .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { total += pos; } @@ -105,20 +105,20 @@ impl OneDReader for Code39Reader { .decodeRowRXingResult .chars() .nth(max) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? != Self::ALPHABET_STRING .chars() .nth(total % 43) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } self.decodeRowRXingResult.truncate(max); } if self.decodeRowRXingResult.chars().count() == 0 { // false positive - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let resultString = if self.extendedMode { @@ -246,7 +246,7 @@ impl Code39Reader { isWhite = !isWhite; } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } // 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::indexOutOfBoundsEmpty()); + .ok_or(Exceptions::indexOutOfBounds); } } if pattern == Self::ASTERISK_ENCODING { return Ok('*'); } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn decodeExtended(encoded: &str) -> Result { @@ -322,49 +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::indexOutOfBoundsEmpty())?; + let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; if c == '+' || c == '$' || c == '%' || c == '/' { let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; 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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } '$' => { // $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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } '%' => { // %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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else if ('F'..='J').contains(&next) { decodedChar = char::from_u32(next as u32 - 11) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else if ('K'..='O').contains(&next) { decodedChar = char::from_u32(next as u32 + 16) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else if ('P'..='T').contains(&next) { decodedChar = char::from_u32(next as u32 + 43) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else if next == 'U' { decodedChar = 0 as char; } else if next == 'V' { @@ -374,18 +371,18 @@ impl Code39Reader { } else if next == 'X' || next == 'Y' || next == 'Z' { decodedChar = 127 as char; } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } '/' => { // /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::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } _ => {} diff --git a/src/oned/code_39_writer.rs b/src/oned/code_39_writer.rs index a929ce7..7b75370 100644 --- a/src/oned/code_39_writer.rs +++ b/src/oned/code_39_writer.rs @@ -33,7 +33,7 @@ impl OneDimensionalCodeWriter for Code39Writer { let mut contents = contents.to_owned(); let mut length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested contents should be less than 80 digits long, but got {length}" ))); } @@ -47,14 +47,14 @@ impl OneDimensionalCodeWriter for Code39Writer { contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) .is_none() { contents = Self::tryToConvertToExtendedMode(&contents)?; length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgument(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)"))); + return Err(Exceptions::illegalArgumentWith(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)"))); } break; } @@ -70,7 +70,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::indexOutOfBoundsEmpty())?) else { + let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else { continue; }; Self::toIntArray( @@ -117,56 +117,56 @@ impl Code39Writer { extendedContent.push('$'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 1)) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character < ' ' { extendedContent.push('%'); extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 27)) - .ok_or(Exceptions::parseEmpty())?, + .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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character <= '9' { extendedContent.push( char::from_u32('0' as u32 + (character as u32 - 48)) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character <= '?' { extendedContent.push('%'); extendedContent.push( char::from_u32('F' as u32 + (character as u32 - 59)) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character <= 'Z' { extendedContent.push( char::from_u32('A' as u32 + (character as u32 - 65)) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character <= '_' { extendedContent.push('%'); extendedContent.push( char::from_u32('K' as u32 + (character as u32 - 91)) - .ok_or(Exceptions::parseEmpty())?, + .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::parseEmpty())?, + .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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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 ed7235f..11068b2 100644 --- a/src/oned/code_93_reader.rs +++ b/src/oned/code_93_reader.rs @@ -63,7 +63,7 @@ impl OneDReader for Code93Reader { one_d_reader::recordPattern(row, nextStart, &mut theCounters)?; let pattern = Self::toPattern(&theCounters); if pattern < 0 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } decodedChar = Self::patternToChar(pattern as u32)?; self.decodeRowRXingResult.push(decodedChar); @@ -92,12 +92,12 @@ impl OneDReader for Code93Reader { // Should be at least one more black module if nextStart == end || !row.get(nextStart) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } if self.decodeRowRXingResult.chars().count() < 2 { // false positive -- need at least 2 checksum digits - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Self::checkChecksums(&self.decodeRowRXingResult)?; @@ -191,7 +191,7 @@ impl Code93Reader { isWhite = !isWhite; } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn toPattern(counters: &[u32; 6]) -> i32 { @@ -221,7 +221,7 @@ impl Code93Reader { return Ok(Self::ALPHABET[i]); } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn decodeExtended(encoded: &str) -> Result { @@ -231,55 +231,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::indexOutOfBoundsEmpty())?; + let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; if ('a'..='d').contains(&c) { if i >= length - 1 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let next = encoded .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; 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::parseEmpty())?; + char::from_u32(next as u32 + 32).ok_or(Exceptions::parse)?; } else { - return Err(Exceptions::formatEmpty()); + 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::parseEmpty())?; + char::from_u32(next as u32 - 64).ok_or(Exceptions::parse)?; } else { - return Err(Exceptions::formatEmpty()); + 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::parseEmpty())?; + 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::parseEmpty())?; + 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::parseEmpty())?; + 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::parseEmpty())?; + char::from_u32(next as u32 + 43).ok_or(Exceptions::parse)?; } else if next == 'U' { // %U map to NUL decodedChar = '\0'; @@ -293,18 +290,18 @@ impl Code93Reader { // %X to %Z all map to DEL (127) decodedChar = 127 as char; } else { - return Err(Exceptions::formatEmpty()); + 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::parseEmpty())?; + char::from_u32(next as u32 - 32).ok_or(Exceptions::parse)?; } else if next == 'Z' { decodedChar = ':'; } else { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } } _ => {} @@ -338,12 +335,7 @@ impl Code93Reader { for i in (0..checkPosition).rev() { total += weight * Self::ALPHABET_STRING - .find( - result - .chars() - .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, - ) + .find(result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) .map_or_else(|| -1_i32, |v| v as i32); weight += 1; if weight > weightMax as i32 { @@ -353,10 +345,10 @@ impl Code93Reader { if result .chars() .nth(checkPosition) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? != Self::ALPHABET[(total as usize) % 47] { - Err(Exceptions::checksumEmpty()) + Err(Exceptions::checksum) } else { Ok(()) } diff --git a/src/oned/code_93_writer.rs b/src/oned/code_93_writer.rs index 06905c7..26dd987 100644 --- a/src/oned/code_93_writer.rs +++ b/src/oned/code_93_writer.rs @@ -35,7 +35,7 @@ impl OneDimensionalCodeWriter for Code93Writer { let mut contents = Self::convertToExtended(contents)?; let length = contents.chars().count(); if length > 80 { - return Err(Exceptions::illegalArgument(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" ))); + return Err(Exceptions::illegalArgumentWith(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 @@ -48,7 +48,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::indexOutOfBoundsEmpty())?) else {panic!("alphabet")}; + let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else {panic!("alphabet")}; pos += Self::appendPattern( &mut result, pos, @@ -65,7 +65,7 @@ impl OneDimensionalCodeWriter for Code93Writer { Code93Reader::ALPHABET_STRING .chars() .nth(check1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ); let check2 = Self::computeChecksumIndex(&contents, 15); @@ -156,15 +156,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::parseEmpty())?, + 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::parseEmpty())?, + char::from_u32('A' as u32 + character as u32 - 27).ok_or(Exceptions::parse)?, ); } else if character == ' ' || character == '$' || character == '%' || character == '+' { // space $ % + @@ -174,7 +172,7 @@ impl Code93Writer { extendedContent.push('c'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - '!' as u32) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character <= '9' { extendedContent.push(character); @@ -186,7 +184,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('F' as u32 + character as u32 - ';' as u32) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character == '@' { // @: (%)V @@ -199,7 +197,7 @@ impl Code93Writer { extendedContent.push('b'); extendedContent.push( char::from_u32('K' as u32 + character as u32 - '[' as u32) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else if character == '`' { // `: (%)W @@ -209,17 +207,17 @@ impl Code93Writer { extendedContent.push('d'); extendedContent.push( char::from_u32('A' as u32 + character as u32 - 'a' as u32) - .ok_or(Exceptions::parseEmpty())?, + .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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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 c5eaf3a..00b9fa0 100644 --- a/src/oned/ean_13_reader.rs +++ b/src/oned/ean_13_reader.rs @@ -64,10 +64,8 @@ impl UPCEANReader for EAN13Reader { rowOffset, &upc_ean_reader::L_AND_G_PATTERNS, )?; - resultString.push( - char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; @@ -89,9 +87,8 @@ impl UPCEANReader for EAN13Reader { while x < 6 && rowOffset < end { 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::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; @@ -153,11 +150,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::parseEmpty())?, + char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parse)?, ); return Ok(()); } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index 05c094a..1326f4b 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -45,11 +45,13 @@ impl OneDimensionalCodeWriter for EAN13Writer { } 13 => { if !reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgument("Contents do not pass checksum")); + return Err(Exceptions::illegalArgumentWith( + "Contents do not pass checksum", + )); } } _ => { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested contents should be 12 or 13 digits long, but got {length}" ))) } @@ -60,9 +62,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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; @@ -77,9 +79,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? as usize; + .ok_or(Exceptions::parse)? as usize; if (parities >> (6 - i) & 1) == 1 { digit += 10; } @@ -98,9 +100,9 @@ impl OneDimensionalCodeWriter for EAN13Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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 8d5e652..a17cd94 100644 --- a/src/oned/ean_8_reader.rs +++ b/src/oned/ean_8_reader.rs @@ -52,9 +52,8 @@ impl UPCEANReader for EAN8Reader { while x < 4 && rowOffset < end { 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::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; @@ -69,9 +68,8 @@ impl UPCEANReader for EAN8Reader { while x < 4 && rowOffset < end { 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::parseEmpty())?, - ); + resultString + .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 9857d35..7a25e44 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -55,11 +55,13 @@ impl OneDimensionalCodeWriter for EAN8Writer { } 8 => { if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? { - return Err(Exceptions::illegalArgument("Contents do not pass checksum")); + return Err(Exceptions::illegalArgumentWith( + "Contents do not pass checksum", + )); } } _ => { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested contents should be 7 or 8 digits long, but got {length}" ))) } @@ -78,9 +80,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize; + .ok_or(Exceptions::indexOutOfBounds)? as usize; pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], false) as usize; } @@ -93,9 +95,9 @@ impl OneDimensionalCodeWriter for EAN8Writer { let digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize; + .ok_or(Exceptions::indexOutOfBounds)? 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 cadaa45..eea61ed 100644 --- a/src/oned/itf_reader.rs +++ b/src/oned/itf_reader.rs @@ -140,7 +140,7 @@ impl OneDReader for ITFReader { lengthOK = true; } if !lengthOK { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let mut resultObject = RXingResult::new( @@ -195,11 +195,9 @@ impl ITFReader { } let mut bestMatch = self.decodeDigit(&counterBlack)?; - resultString - .push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parseEmpty())?); + 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::parseEmpty())?); + resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parse)?); payloadStart += counterDigitPair.iter().sum::() as usize; } @@ -260,7 +258,7 @@ impl ITFReader { if quietCount != 0 { // Unable to find the necessary number of quiet zone pixels. - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } else { Ok(()) } @@ -277,7 +275,7 @@ impl ITFReader { let width = row.getSize(); let endStart = row.getNextSet(0); if endStart == width { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(endStart) @@ -372,7 +370,7 @@ impl ITFReader { isWhite = !isWhite; } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** @@ -401,7 +399,7 @@ impl ITFReader { if bestMatch >= 0 { Ok(bestMatch as u32 % 10) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } } diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index ffd32b3..1fd9dcc 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -32,12 +32,12 @@ impl OneDimensionalCodeWriter for ITFWriter { fn encode_oned(&self, contents: &str) -> Result, Exceptions> { let length = contents.chars().count(); if length % 2 != 0 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "The length of the input should be even", )); } if length > 80 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested contents should be less than 80 digits long, but got {length}" ))); } @@ -51,15 +51,15 @@ impl OneDimensionalCodeWriter for ITFWriter { let one = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? as usize; + .ok_or(Exceptions::parse)? as usize; let two = contents .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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 5bdc70e..f2c02e4 100644 --- a/src/oned/multi_format_one_d_reader.rs +++ b/src/oned/multi_format_one_d_reader.rs @@ -46,7 +46,7 @@ impl OneDReader for MultiFormatOneDReader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } impl MultiFormatOneDReader { @@ -168,7 +168,7 @@ impl Reader for MultiFormatOneDReader { Ok(result) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/oned/multi_format_upc_ean_reader.rs b/src/oned/multi_format_upc_ean_reader.rs index 768d868..5e58d27 100644 --- a/src/oned/multi_format_upc_ean_reader.rs +++ b/src/oned/multi_format_upc_ean_reader.rs @@ -134,7 +134,7 @@ impl OneDReader for MultiFormatUPCEANReader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } @@ -200,7 +200,7 @@ impl Reader for MultiFormatUPCEANReader { Ok(result) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 315f54d..b3b144f 100644 --- a/src/oned/one_d_code_writer.rs +++ b/src/oned/one_d_code_writer.rs @@ -100,7 +100,7 @@ pub trait OneDimensionalCodeWriter: Writer { */ fn checkNumeric(contents: &str) -> Result<(), Exceptions> { if !NUMERIC.is_match(contents) { - Err(Exceptions::illegalArgument( + Err(Exceptions::illegalArgumentWith( "Input should only contain digits 0-9", )) } else { @@ -163,17 +163,17 @@ impl Writer for L { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument("Found empty contents")); + return Err(Exceptions::illegalArgumentWith("Found empty contents")); } if width < 0 || height < 0 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Negative size is not allowed. Input: {width}x{height}" ))); } if let Some(supportedFormats) = self.getSupportedWriteFormats() { if !supportedFormats.contains(format) { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Can only encode {supportedFormats:?}, but got {format:?}" ))); } @@ -181,9 +181,9 @@ 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::illegalArgument(format!("couldnt parse {margin}: {e}")))?; + sidesMargin = margin.parse::().map_err(|e| { + Exceptions::illegalArgumentWith(format!("couldnt parse {margin}: {e}")) + })?; } let code = self.encode_oned_with_hints(contents, hints)?; diff --git a/src/oned/one_d_reader.rs b/src/oned/one_d_reader.rs index ae96948..856d1ca 100644 --- a/src/oned/one_d_reader.rs +++ b/src/oned/one_d_reader.rs @@ -131,7 +131,7 @@ pub trait OneDReader: Reader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** @@ -218,7 +218,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu let end = row.getSize(); if start >= end { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut isWhite = !row.get(start); @@ -241,7 +241,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::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(()) } @@ -263,7 +263,7 @@ pub fn recordPatternInReverse( } } if numTransitionsLeft >= 0 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } recordPattern(row, start + 1, counters)?; diff --git a/src/oned/rss/abstract_rss_reader.rs b/src/oned/rss/abstract_rss_reader.rs index ec086e3..c7549ac 100644 --- a/src/oned/rss/abstract_rss_reader.rs +++ b/src/oned/rss/abstract_rss_reader.rs @@ -38,7 +38,7 @@ pub trait AbstractRSSReaderTrait: OneDReader { return Ok(value as u32); } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index 5493ef4..2631074 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -50,13 +50,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::parseEmpty())? != ' ' { - return Err(Exceptions::illegalState("space expected")); + if dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)? != ' ' { + return Err(Exceptions::illegalStateWith("space expected")); } continue; } - let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())?; + let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)?; if currentChar == 'X' || currentChar == 'x' { binary.set(counter); } @@ -78,12 +78,7 @@ pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result( _ => {} } - Err(Exceptions::illegalState(format!( + Err(Exceptions::illegalStateWith(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 e4026c0..72f4dcd 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::notFoundEmpty()); + return Err(crate::Exceptions::notFound); } 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 29dd58b..8ff0303 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::notFoundEmpty()); + return Err(crate::Exceptions::notFound); } 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 38138c9..c20a6aa 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::notFoundEmpty()); + return Err(crate::Exceptions::notFound); } 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 5058863..5ee7b29 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::notFoundEmpty()); + return Err(crate::Exceptions::notFound); } 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 8489133..34da6c2 100644 --- a/src/oned/rss/expanded/decoders/decoded_numeric.rs +++ b/src/oned/rss/expanded/decoders/decoded_numeric.rs @@ -51,7 +51,7 @@ impl DecodedNumeric { if /*firstDigit < 0 ||*/ firstDigit > 10 || /*secondDigit < 0 ||*/ secondDigit > 10 { - return Err(Exceptions::formatEmpty()); + 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 de5a4a0..8aecc12 100644 --- a/src/oned/rss/expanded/decoders/field_parser.rs +++ b/src/oned/rss/expanded/decoders/field_parser.rs @@ -145,7 +145,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result Result Result Result Result { if rawInformation.chars().count() < aiSize { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let ai: String = rawInformation.chars().take(aiSize).collect(); if rawInformation.chars().count() < aiSize + fieldSize { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } 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 e1aeabd..f7204a9 100644 --- a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs +++ b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs @@ -199,7 +199,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if let Some(r) = result.getDecodedInformation() { Ok(r.clone()) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } @@ -345,7 +345,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::parseEmpty())?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?, )); } @@ -354,14 +354,14 @@ impl<'a> GeneralAppIdDecoder<'_> { if (64..90).contains(&sevenBitValue) { return Ok(DecodedChar::new( pos + 7, - char::from_u32(sevenBitValue + 1).ok_or(Exceptions::parseEmpty())?, + 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::parseEmpty())?, + char::from_u32(sevenBitValue + 7).ok_or(Exceptions::parse)?, )); } @@ -388,7 +388,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 250 => '?', 251 => '_', 252 => ' ', - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), }; Ok(DecodedChar::new(pos + 8, c)) @@ -423,7 +423,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::parseEmpty())?, + char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?, )); } @@ -432,7 +432,7 @@ impl<'a> GeneralAppIdDecoder<'_> { if (32..58).contains(&sixBitValue) { return Ok(DecodedChar::new( pos + 6, - char::from_u32(sixBitValue + 33).ok_or(Exceptions::parseEmpty())?, + char::from_u32(sixBitValue + 33).ok_or(Exceptions::parse)?, )); } @@ -443,7 +443,7 @@ impl<'a> GeneralAppIdDecoder<'_> { 61 => '.', 62 => '/', _ => { - return Err(Exceptions::illegalState(format!( + return Err(Exceptions::illegalStateWith(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 d0f48b7..180aee9 100644 --- a/src/oned/rss/expanded/rss_expanded_reader.rs +++ b/src/oned/rss/expanded/rss_expanded_reader.rs @@ -227,7 +227,7 @@ impl Reader for RSSExpandedReader { Ok(result) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } } @@ -297,7 +297,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::illegalStateEmpty())); + return Err(to_add_res.err().unwrap_or(Exceptions::illegalState)); } else { // exit this loop when retrieveNextPair() fails and throws done = true; @@ -329,7 +329,7 @@ impl RSSExpandedReader { // } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn checkRows(&mut self, reverse: bool) -> Option> { @@ -373,10 +373,7 @@ impl RSSExpandedReader { ) -> Result, Exceptions> { for i in currentRow..self.rows.len() { // for (int i = currentRow; i < rows.size(); i++) { - let row = self - .rows - .get(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + let row = self.rows.get(i).ok_or(Exceptions::indexOutOfBounds)?; self.pairs.clear(); for collectedRow in &collectedRows.clone() { // for (ExpandedRow collectedRow : collectedRows) { @@ -404,7 +401,7 @@ impl RSSExpandedReader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /// Whether the pairs form a valid find pattern sequence, @@ -534,25 +531,25 @@ 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::illegalStateEmpty())?; + let binary = + bit_array_builder::buildBitArray(&pairs.to_vec()).ok_or(Exceptions::illegalState)?; let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?; let resultingString = decoder.parseInformation()?; let firstPoints = pairs .get(0) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getRXingResultPoints(); let lastPoints = pairs .last() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getRXingResultPoints(); let mut result = RXingResult::new( @@ -651,7 +648,7 @@ impl RSSExpandedReader { let leftChar = self.decodeDataCharacter( row, - pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?, + pattern.as_ref().ok_or(Exceptions::notFound)?, isOddPattern, true, )?; @@ -659,16 +656,16 @@ impl RSSExpandedReader { if !previousPairs.is_empty() && previousPairs .last() - .ok_or(Exceptions::notFoundEmpty())? + .ok_or(Exceptions::notFound)? .mustBeLast() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let rightChar = self .decodeDataCharacter( row, - pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?, + pattern.as_ref().ok_or(Exceptions::notFound)?, isOddPattern, false, ) @@ -698,13 +695,11 @@ impl RSSExpandedReader { } else if previousPairs.is_empty() { rowOffset = 0; } else { - let lastPair = previousPairs - .last() - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + let lastPair = previousPairs.last().ok_or(Exceptions::indexOutOfBounds)?; rowOffset = lastPair .getFinderPattern() .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getStartEnd()[1] as i32; } let mut searchingEvenPair = previousPairs.len() % 2 != 0; @@ -756,7 +751,7 @@ impl RSSExpandedReader { isWhite = !isWhite; } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn reverseCounters(counters: &mut [u32]) { @@ -853,7 +848,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::notFoundEmpty()); + return Err(Exceptions::notFound); } for (i, counter) in counters.iter().enumerate() { @@ -862,12 +857,12 @@ impl RSSExpandedReader { let mut count = (value + 0.5) as i32; // Round if count < 1 { if value < 0.3 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } count = 1; } else if count > 8 { if value > 8.7 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } count = 8; } @@ -907,7 +902,7 @@ impl RSSExpandedReader { let checksumPortion = oddChecksumPortion + evenChecksumPortion; if (oddSum & 0x01) != 0 || !(4..=13).contains(&oddSum) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let group = ((13 - oddSum) / 2) as usize; @@ -955,12 +950,12 @@ impl RSSExpandedReader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } decrementEven = true; } @@ -968,12 +963,12 @@ impl RSSExpandedReader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } incrementEven = true; } @@ -981,7 +976,7 @@ impl RSSExpandedReader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } // Both bad if oddSum < evenSum { @@ -992,16 +987,16 @@ impl RSSExpandedReader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } - _ => return Err(Exceptions::notFoundEmpty()), + _ => return Err(Exceptions::notFound), } if incrementOdd { if decrementOdd { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -1010,7 +1005,7 @@ impl RSSExpandedReader { } if incrementEven { if decrementEven { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } 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 5adddd4..910c8f3 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::illegalStateEmpty()); + .ok_or(Exceptions::illegalState); } } } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } impl Reader for RSS14Reader { @@ -126,7 +126,7 @@ impl Reader for RSS14Reader { Ok(result) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } } @@ -343,7 +343,7 @@ impl RSS14Reader { if outsideChar { if (oddSum & 0x01) != 0 || !(4..=12).contains(&oddSum) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let group = ((12 - oddSum) / 2) as usize; let oddWidest = Self::OUTSIDE_ODD_WIDEST[group]; @@ -358,7 +358,7 @@ impl RSS14Reader { )) } else { if (evenSum & 0x01) != 0 || !(4..=10).contains(&evenSum) { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let group = ((10 - evenSum) / 2) as usize; let oddWidest = Self::INSIDE_ODD_WIDEST[group]; @@ -417,7 +417,7 @@ impl RSS14Reader { isWhite = !isWhite; } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } fn parseFoundFinderPattern( @@ -518,12 +518,12 @@ impl RSS14Reader { 1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } decrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } decrementEven = true; } @@ -531,12 +531,12 @@ impl RSS14Reader { -1 => { if oddParityBad { if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } incrementOdd = true; } else { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } incrementEven = true; } @@ -544,7 +544,7 @@ impl RSS14Reader { 0 => { if oddParityBad { if !evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } // Both bad if oddSum < evenSum { @@ -555,15 +555,15 @@ impl RSS14Reader { incrementEven = true; } } else if evenParityBad { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } } - _ => return Err(Exceptions::notFoundEmpty()), + _ => return Err(Exceptions::notFound), } if incrementOdd { if decrementOdd { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Self::increment(&mut self.oddCounts, &self.oddRoundingErrors); } @@ -572,7 +572,7 @@ impl RSS14Reader { } if incrementEven { if decrementEven { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Self::increment(&mut self.evenCounts, &self.evenRoundingErrors); } diff --git a/src/oned/upc_a_reader.rs b/src/oned/upc_a_reader.rs index f0e7d1c..7f72ed5 100644 --- a/src/oned/upc_a_reader.rs +++ b/src/oned/upc_a_reader.rs @@ -104,7 +104,7 @@ impl UPCAReader { Ok(upcaRXingResult) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } } diff --git a/src/oned/upc_a_writer.rs b/src/oned/upc_a_writer.rs index 487f327..18dec94 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::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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 82173b9..d6eed28 100644 --- a/src/oned/upc_e_reader.rs +++ b/src/oned/upc_e_reader.rs @@ -49,10 +49,8 @@ impl UPCEANReader for UPCEReader { let mut x = 0; 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::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; if bestMatch >= 10 { @@ -68,9 +66,7 @@ impl UPCEANReader for UPCEReader { } fn checkChecksum(&self, s: &str) -> Result { - self.checkStandardUPCEANChecksum( - &convertUPCEtoUPCA(s).ok_or(Exceptions::illegalArgumentEmpty())?, - ) + self.checkStandardUPCEANChecksum(&convertUPCEtoUPCA(s).ok_or(Exceptions::illegalArgument)?) } fn decodeEnd( @@ -132,17 +128,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::parseEmpty())?, - ); - resultString.push( - char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parseEmpty())?, + 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)?); return Ok(()); } } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index 90cf4af..45532c4 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -46,20 +46,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::illegalArgumentEmpty())?, + .ok_or(Exceptions::illegalArgument)?, )?; contents.push_str(&check.to_string()); } 8 => { if !reader.checkStandardUPCEANChecksum( &upc_e_reader::convertUPCEtoUPCA(&contents) - .ok_or(Exceptions::illegalArgumentEmpty())?, + .ok_or(Exceptions::illegalArgument)?, )? { - return Err(Exceptions::illegalArgument("Contents do not pass checksum")); + return Err(Exceptions::illegalArgumentWith( + "Contents do not pass checksum", + )); } } _ => { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Requested contents should be 7 or 8 digits long, but got {length}" ))) } @@ -70,19 +72,21 @@ impl OneDimensionalCodeWriter for UPCEWriter { let firstDigit = contents .chars() .next() - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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::illegalArgument("Number system must be 0 or 1")); + return Err(Exceptions::illegalArgumentWith( + "Number system must be 0 or 1", + )); } let checkDigit = contents .chars() .nth(7) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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]; @@ -94,9 +98,9 @@ impl OneDimensionalCodeWriter for UPCEWriter { let mut digit = contents .chars() .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? .to_digit(10) - .ok_or(Exceptions::parseEmpty())? 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 28c5ca6..6bd1bfb 100644 --- a/src/oned/upc_ean_extension_2_support.rs +++ b/src/oned/upc_ean_extension_2_support.rs @@ -86,10 +86,8 @@ impl UPCEANExtension2Support { rowOffset, &upc_ean_reader::L_AND_G_PATTERNS, )?; - resultString.push( - char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; @@ -105,16 +103,16 @@ impl UPCEANExtension2Support { } if resultString.chars().count() != 2 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } if resultString .parse::() - .map_err(|e| Exceptions::parse(format!("could not parse {resultString}: {e}")))? + .map_err(|e| Exceptions::parseWith(format!("could not parse {resultString}: {e}")))? % 4 != checkParity { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } 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 a314e2e..ae5f6bc 100644 --- a/src/oned/upc_ean_extension_5_support.rs +++ b/src/oned/upc_ean_extension_5_support.rs @@ -85,10 +85,8 @@ impl UPCEANExtension5Support { rowOffset, &upc_ean_reader::L_AND_G_PATTERNS, )?; - resultString.push( - char::from_u32('0' as u32 + bestMatch as u32 % 10) - .ok_or(Exceptions::parseEmpty())?, - ); + resultString + .push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?); rowOffset += counters.iter().sum::() as usize; @@ -105,14 +103,14 @@ impl UPCEANExtension5Support { } if resultString.chars().count() != 5 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let checkDigit = Self::determineCheckDigit(lgPatternFound)?; - if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgumentEmpty())? + if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgument)? != checkDigit as u32 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(rowOffset as u32) @@ -147,7 +145,7 @@ impl UPCEANExtension5Support { return Ok(d); } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** diff --git a/src/oned/upc_ean_reader.rs b/src/oned/upc_ean_reader.rs index 806304b..f11119b 100644 --- a/src/oned/upc_ean_reader.rs +++ b/src/oned/upc_ean_reader.rs @@ -182,18 +182,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::notFoundEmpty()); + return Err(Exceptions::notFound); } let resultString = result; // UPC/EAN should never be less than 8 chars anyway if resultString.chars().count() < 8 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } if !self.checkChecksum(&resultString)? { - return Err(Exceptions::checksumEmpty()); + 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::notFoundEmpty()); + return Err(Exceptions::notFound); } } @@ -292,7 +292,7 @@ pub trait UPCEANReader: OneDReader { let char_in_question = s .chars() .nth(length - 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + .ok_or(Exceptions::indexOutOfBounds)?; let check = char_in_question.is_ascii_digit(); let check_against = &s[..length - 1]; //s.subSequence(0, length - 1); @@ -300,9 +300,7 @@ pub trait UPCEANReader: OneDReader { Ok(calculated_checksum == if check { - char_in_question - .to_digit(10) - .ok_or(Exceptions::parseEmpty())? + char_in_question.to_digit(10).ok_or(Exceptions::parse)? } else { u32::MAX }) @@ -317,10 +315,10 @@ pub trait UPCEANReader: OneDReader { let digit = (s .chars() .nth(i as usize) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32) + .ok_or(Exceptions::indexOutOfBounds)? as i32) - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } sum += digit; @@ -333,10 +331,10 @@ pub trait UPCEANReader: OneDReader { let digit = (s .chars() .nth(i as usize) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32) + .ok_or(Exceptions::indexOutOfBounds)? as i32) - ('0' as i32); if !(0..=9).contains(&digit) { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } sum += digit; @@ -423,7 +421,7 @@ pub trait UPCEANReader: OneDReader { } } - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** @@ -460,7 +458,7 @@ pub trait UPCEANReader: OneDReader { if bestMatch >= 0 { Ok(bestMatch as usize) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/pdf417/decoder/bounding_box.rs b/src/pdf417/decoder/bounding_box.rs index 05622a4..802b48a 100644 --- a/src/pdf417/decoder/bounding_box.rs +++ b/src/pdf417/decoder/bounding_box.rs @@ -44,7 +44,7 @@ impl BoundingBox { let leftUnspecified = topLeft.is_none() || bottomLeft.is_none(); let rightUnspecified = topRight.is_none() || bottomRight.is_none(); if leftUnspecified && rightUnspecified { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let newTopLeft; @@ -53,21 +53,21 @@ impl BoundingBox { let newBottomRight; if leftUnspecified { - newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?; - newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?; + newTopRight = topRight.ok_or(Exceptions::illegalState)?; + newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?; newTopLeft = RXingResultPoint::new(0.0, newTopRight.getY()); newBottomLeft = RXingResultPoint::new(0.0, newBottomRight.getY()); } else if rightUnspecified { - newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?; - newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?; + newTopLeft = topLeft.ok_or(Exceptions::illegalState)?; + newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?; newTopRight = RXingResultPoint::new(image.getWidth() as f32 - 1.0, newTopLeft.getY()); newBottomRight = RXingResultPoint::new(image.getWidth() as f32 - 1.0, newBottomLeft.getY()); } else { - newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?; - newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?; - newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?; - newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?; + newTopLeft = topLeft.ok_or(Exceptions::illegalState)?; + newTopRight = topRight.ok_or(Exceptions::illegalState)?; + newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?; + newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?; } Ok(BoundingBox { @@ -102,19 +102,13 @@ impl BoundingBox { rightBox: Option, ) -> Result { if leftBox.is_none() { - return Ok(rightBox - .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? - .clone()); + return Ok(rightBox.as_ref().ok_or(Exceptions::illegalState)?.clone()); } if rightBox.is_none() { - return Ok(leftBox - .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? - .clone()); + return Ok(leftBox.as_ref().ok_or(Exceptions::illegalState)?.clone()); } - let leftBox = leftBox.ok_or(Exceptions::illegalStateEmpty())?; - let rightBox = rightBox.ok_or(Exceptions::illegalStateEmpty())?; + let leftBox = leftBox.ok_or(Exceptions::illegalState)?; + let rightBox = rightBox.ok_or(Exceptions::illegalState)?; 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 522e3d2..3ce53f5 100644 --- a/src/pdf417/decoder/decoded_bit_stream_parser.rs +++ b/src/pdf417/decoder/decoded_bit_stream_parser.rs @@ -121,9 +121,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { - result.append_char( - char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parseEmpty())?, - ); + result.append_char(char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parse)?); codeIndex += 1; } NUMERIC_COMPACTION_MODE_LATCH => { @@ -149,7 +147,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result // Should not see these outside a macro block { - return Err(Exceptions::formatEmpty()) + return Err(Exceptions::format) } _ => { // Default to text compaction. During testing numerous barcodes @@ -164,7 +162,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result codewords[0] as usize { // we must have at least two bytes left for the segment index - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS]; for seq in segmentIndexArray @@ -204,7 +202,7 @@ pub fn decodeMacroBlock( resultMetadata.setSegmentIndex(parsed_int); } else { // too large; bad input? - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } // Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec @@ -221,7 +219,7 @@ pub fn decodeMacroBlock( } if fileId.chars().count() == 0 { // at least one fileId codeword is required (Annex H.2) - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } resultMetadata.setFileId(fileId); @@ -258,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::formatEmpty()); + return Err(Exceptions::format); }; resultMetadata.setSegmentCount(parsed_segment_count); } @@ -267,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::formatEmpty()); + return Err(Exceptions::format); }; resultMetadata.setTimestamp(parsed_timestamp); } @@ -276,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::formatEmpty()); + return Err(Exceptions::format); }; resultMetadata.setChecksum(parsed_checksum); } @@ -285,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::formatEmpty()); + return Err(Exceptions::format); }; resultMetadata.setFileSize(parsed_file_size); } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } MACRO_PDF417_TERMINATOR => { codeIndex += 1; resultMetadata.setLastSegment(true); } - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } @@ -388,7 +386,7 @@ fn textCompaction( result, subMode, ) - .ok_or(Exceptions::illegalStateEmpty())?; + .ok_or(Exceptions::illegalState)?; result.appendECI(codewords[codeIndex])?; codeIndex += 1; textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; @@ -770,16 +768,14 @@ fn numericCompaction( Remove leading 1 => RXingResult is 000213298174000 */ fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result { - let mut result = 0.to_biguint().ok_or(Exceptions::arithmeticEmpty())?; + let mut result = 0.to_biguint().ok_or(Exceptions::arithmetic)?; for i in 0..count { - result += &EXP900[count - i - 1] - * (codewords[i] - .to_biguint() - .ok_or(Exceptions::arithmeticEmpty())?); + result += + &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::formatEmpty()); + 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 15fb758..a19e6a8 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -103,7 +103,7 @@ pub fn decode( // 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::checksum(file!())); + return Err(Exceptions::checksumWith(file!())); } received[position as usize] = field.subtract(received[position as usize], errorMagnitudes[i]); @@ -140,7 +140,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::checksum(file!())); + return Err(Exceptions::checksumWith(file!())); } r = rLastLast; let mut q = ModulusPoly::getZero(field); //field.getZero(); @@ -162,7 +162,7 @@ fn runEuclideanAlgorithm( let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(Exceptions::checksum(file!())); + return Err(Exceptions::checksumWith(file!())); } let inverse = field.inverse(sigmaTildeAtZero)?; @@ -190,7 +190,7 @@ fn findErrorLocations( i += 1; } if e != numErrors { - return Err(Exceptions::checksum(file!())); + return Err(Exceptions::checksumWith(file!())); } Ok(result) } diff --git a/src/pdf417/decoder/ec/modulus_gf.rs b/src/pdf417/decoder/ec/modulus_gf.rs index f891dbb..0d5b1c4 100644 --- a/src/pdf417/decoder/ec/modulus_gf.rs +++ b/src/pdf417/decoder/ec/modulus_gf.rs @@ -77,7 +77,7 @@ impl ModulusGF { pub fn log(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::arithmeticEmpty()) + Err(Exceptions::arithmetic) } else { Ok(self.logTable[a as usize]) } @@ -85,7 +85,7 @@ impl ModulusGF { pub fn inverse(&self, a: u32) -> Result { if a == 0 { - Err(Exceptions::arithmeticEmpty()) + 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 693c4bd..458d843 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -36,7 +36,7 @@ impl ModulusPoly { coefficients: Vec, ) -> Result { if coefficients.is_empty() { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } let orig_coefs = coefficients.clone(); let mut coefficients = coefficients; @@ -126,7 +126,7 @@ impl ModulusPoly { pub fn add(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "ModulusPolys do not have same ModulusGF field", )); } @@ -160,7 +160,7 @@ impl ModulusPoly { pub fn subtract(&self, other: Rc) -> Result, Exceptions> { if self.field != other.field { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "ModulusPolys do not have same ModulusGF field", )); } @@ -172,7 +172,7 @@ impl ModulusPoly { pub fn multiply(&self, other: Rc) -> Result, Exceptions> { if !(self.field == other.field) { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "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 8198ae8..8b0fff7 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::notFoundEmpty()); + return Err(Exceptions::notFound); } // 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::illegalStateEmpty())? as i32; + .ok_or(Exceptions::illegalState)? 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::notFoundEmpty()); + return Err(Exceptions::notFound); } barcodeMatrix01.setValue(calculatedNumberOfCodewords); } else if numberOfCodewords[0] != calculatedNumberOfCodewords @@ -508,7 +508,7 @@ fn createDecoderRXingResultFromAmbiguousValues( // // // } if ambiguousIndexCount.is_empty() { - return Err(Exceptions::checksumEmpty()); + 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::checksumEmpty()); + return Err(Exceptions::checksum); } } } tries -= 1; } - Err(Exceptions::checksumEmpty()) + 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::formatEmpty()); + 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::checksumEmpty()); + 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::formatEmpty()); + 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::formatEmpty()); + 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::formatEmpty()); + return Err(Exceptions::format); } } Ok(()) diff --git a/src/pdf417/detector/pdf_417_detector.rs b/src/pdf417/detector/pdf_417_detector.rs index bd49234..d4fc159 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::notFoundEmpty())?; + let barcodeCoordinates = detect(multiple, &bitMatrix).ok_or(Exceptions::notFound)?; 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 3000a7d..8de3364 100644 --- a/src/pdf417/encoder/compaction.rs +++ b/src/pdf417/encoder/compaction.rs @@ -40,7 +40,7 @@ impl TryFrom<&String> for Compaction { _ => {} } } - Err(Exceptions::format(format!( + Err(Exceptions::formatWith(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 e502971..d5903b2 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -161,7 +161,7 @@ impl PDF417 { pattern = CODEWORD_TABLE[cluster][fullCodewords .chars() .nth(idx) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? as usize]; Self::encodeChar(pattern, 17, logic.getCurrentRowMut()); idx += 1; @@ -226,17 +226,17 @@ impl PDF417 { //2. step: construct data codewords if sourceCodeWords + errorCorrectionCodeWords + 1 > 929 { // +1 for symbol length CW - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(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::parseEmpty())?); + 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::parseEmpty())?); + sb.push(char::from_u32(900).ok_or(Exceptions::parse)?); //PAD characters } let dataCodewords = sb; @@ -315,7 +315,7 @@ impl PDF417 { } } - dimension.ok_or(Exceptions::writer("Unable to fit message in columns")) + dimension.ok_or(Exceptions::writerWith("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 a24d6e0..26dfc66 100644 --- a/src/pdf417/encoder/pdf_417_error_correction.rs +++ b/src/pdf417/encoder/pdf_417_error_correction.rs @@ -119,7 +119,7 @@ static EC_COEFFICIENTS: Lazy<[Vec; 9]> = Lazy::new(|| { */ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { if errorCorrectionLevel > 8 { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Error correction level must be between 0 and 8!", )); } @@ -135,7 +135,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result Result { if n == 0 { - Err(Exceptions::illegalArgument("n must be > 0")) + Err(Exceptions::illegalArgumentWith("n must be > 0")) } else if n <= 40 { Ok(2) } else if n <= 160 { @@ -145,7 +145,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result= 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::parseEmpty())?; + 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::parseEmpty())?; + 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::parseEmpty())?; + 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 2066dd5..5360456 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::writer("Empty message not allowed")); + return Err(Exceptions::writerWith("Empty message not allowed")); } if encoding.is_none() && !autoECI { for ch in msg.chars() { if ch as u32 > 255 { - return Err(Exceptions::writer(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch))); + 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))); } } } @@ -200,14 +200,11 @@ pub fn encodeHighLevel( if encoding.is_none() { encoding = Some(DEFAULT_ENCODING); } else if DEFAULT_ENCODING.name() - != encoding - .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? - .name() + != encoding.as_ref().ok_or(Exceptions::illegalState)?.name() { - if let Some(eci) = CharacterSetECI::getCharacterSetECI( - encoding.ok_or(Exceptions::illegalStateEmpty())?, - ) { + if let Some(eci) = + CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::illegalState)?) + { encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?; } } @@ -228,7 +225,7 @@ pub fn encodeHighLevel( Compaction::BYTE => { let msgBytes = encoding .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .encode(&input.to_string(), encoding::EncoderTrap::Strict) .unwrap_or_default(); //input.to_string().getBytes(encoding); encodeBinary( @@ -240,7 +237,7 @@ pub fn encodeHighLevel( )?; } Compaction::NUMERIC => { - sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parse)?); encodeNumeric(&input, p, len as u32, &mut sb)?; } _ => { @@ -255,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::parseEmpty())?); + 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)?; @@ -264,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::parseEmpty())?); + sb.push(char::from_u32(LATCH_TO_TEXT).ok_or(Exceptions::parse)?); encodingMode = TEXT_COMPACTION; textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch } @@ -288,7 +285,7 @@ pub fn encodeHighLevel( .collect::(); if let Ok(enc_str) = encoding .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .encode(&str, encoding::EncoderTrap::Strict) { Some(enc_str) @@ -304,7 +301,7 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, 1, TEXT_COMPACTION, &mut sb)?; } else { encodeBinary( - bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?, + bytes.as_ref().ok_or(Exceptions::illegalState)?, 0, 1, TEXT_COMPACTION, @@ -317,10 +314,9 @@ pub fn encodeHighLevel( encodeMultiECIBinary(&input, p, p + b, encodingMode, &mut sb)?; } else { encodeBinary( - bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?, + bytes.as_ref().ok_or(Exceptions::illegalState)?, 0, - bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?.len() - as u32, + bytes.as_ref().ok_or(Exceptions::illegalState)?.len() as u32, encodingMode, &mut sb, )?; @@ -371,9 +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::parseEmpty())?, - ); + tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::parse)?); } } else if isAlphaLower(ch) { submode = SUBMODE_LOWER; @@ -387,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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } } @@ -397,13 +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::parseEmpty())?, - ); + 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::parseEmpty())?); + 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; @@ -413,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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } } @@ -421,8 +413,7 @@ fn encodeText( SUBMODE_MIXED => { if isMixed(ch) { tmp.push( - char::from_u32(MIXED[ch as usize] as u32) - .ok_or(Exceptions::parseEmpty())?, + char::from_u32(MIXED[ch as usize] as u32).ok_or(Exceptions::parse)?, ); } else if isAlphaUpper(ch) { submode = SUBMODE_ALPHA; @@ -444,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::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } } @@ -454,7 +445,7 @@ fn encodeText( if isPunctuation(ch) { tmp.push( char::from_u32(PUNCTUATION[ch as usize] as u32) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); } else { submode = SUBMODE_ALPHA; @@ -475,23 +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::indexOutOfBoundsEmpty())? as u32, + (h as u32 * 30) + tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32, ) - .ok_or(Exceptions::parseEmpty())?; + .ok_or(Exceptions::parse)?; sb.push(h); } else { - h = tmp - .chars() - .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?; + h = tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?; } } if (len % 2) != 0 { - sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::parseEmpty())?); + sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::parse)?); //ps } Ok(submode) @@ -583,11 +567,11 @@ fn encodeBinary( sb: &mut String, ) -> Result<(), Exceptions> { if count == 1 && startmode == TEXT_COMPACTION { - sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::parseEmpty())?); + 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::parseEmpty())?); + 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::parseEmpty())?); + sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::parse)?); } let mut idx = startpos; @@ -601,7 +585,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::parseEmpty())?; + *ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::parse)?; t /= 900; } sb.push_str(&chars.into_iter().rev().collect::()); @@ -645,13 +629,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::parse(format!("issue parsing {part}: {e}")))?; // part.parse().map_err(|_| Exceptions::parseEmpty())?; + .map_err(|e| Exceptions::parseWith(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::parse(format!("erorr converting {bigint} to u32: {e}")) + Exceptions::parseWith(format!("erorr converting {bigint} to u32: {e}")) })?) - .ok_or(Exceptions::parseEmpty())?, + .ok_or(Exceptions::parse)?, ); bigint /= &NUM900; @@ -797,10 +781,10 @@ fn determineConsecutiveBinaryCount( if !can_encode { if TypeId::of::() != TypeId::of::() { - return Err(Exceptions::illegalState("expected NoECIInput type")); + return Err(Exceptions::illegalStateWith("expected NoECIInput type")); } let ch = input.charAt(idx)?; - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "Non-encodable character detected: {} (Unicode: {})", ch, ch as u32 ))); @@ -813,17 +797,17 @@ fn determineConsecutiveBinaryCount( fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> { if (0..900).contains(&eci) { - sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::parseEmpty())?); - sb.push(char::from_u32(eci as u32).ok_or(Exceptions::parseEmpty())?); + 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::parseEmpty())?); - sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::parseEmpty())?); - sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::parseEmpty())?); + 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::parseEmpty())?); - sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::parseEmpty())?); + 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::writer(format!( + return Err(Exceptions::writerWith(format!( "ECI number not in valid range from 0..811799, but was {eci}" ))); } @@ -840,7 +824,7 @@ impl ECIInput for NoECIInput { self.0 .chars() .nth(index) - .ok_or(Exceptions::indexOutOfBoundsEmpty()) + .ok_or(Exceptions::indexOutOfBounds) } fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { diff --git a/src/pdf417/pdf_417_reader.rs b/src/pdf417/pdf_417_reader.rs index 353f9a4..c2a6071 100644 --- a/src/pdf417/pdf_417_reader.rs +++ b/src/pdf417/pdf_417_reader.rs @@ -57,7 +57,7 @@ impl Reader for PDF417Reader { ) -> Result { let result = Self::decode(image, hints, false)?; if result.is_empty() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } Ok(result[0].clone()) } @@ -127,7 +127,7 @@ impl PDF417Reader { pdf417RXingResultMetadata .clone() .downcast::() - .map_err(|_| Exceptions::illegalStateEmpty())?, + .map_err(|_| Exceptions::illegalState)?, ); result.putMetadata(RXingResultMetadataType::PDF417_EXTRA_METADATA, data); } diff --git a/src/pdf417/pdf_417_writer.rs b/src/pdf417/pdf_417_writer.rs index e047898..b12c2e2 100644 --- a/src/pdf417/pdf_417_writer.rs +++ b/src/pdf417/pdf_417_writer.rs @@ -59,7 +59,7 @@ impl Writer for PDF417Writer { hints: &crate::EncodingHintDictionary, ) -> Result { if format != &BarcodeFormat::PDF_417 { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Can only encode PDF_417, but got {format}" ))); } @@ -149,7 +149,7 @@ impl PDF417Writer { let mut originalScale = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getScaledMatrix(1, aspectRatio); let mut rotated = false; if (height > width) != (originalScale[0].len() < originalScale.len()) { @@ -165,16 +165,16 @@ impl PDF417Writer { let mut scaledMatrix = encoder .getBarcodeMatrix() .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .getScaledMatrix(scale, scale * aspectRatio); if rotated { scaledMatrix = Self::rotateArray(&scaledMatrix); } return Self::bitMatrixFromBitArray(&scaledMatrix, margin) - .ok_or(Exceptions::illegalStateEmpty()); + .ok_or(Exceptions::illegalState); } - Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::illegalStateEmpty()) + Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::illegalState) } /** diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index 653e50b..ffd7c36 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -166,7 +166,7 @@ impl PlanarYUVLuminanceSource { inverted: bool, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Crop rectangle does not fit within image data.", )); } @@ -328,7 +328,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { self.invert, ) { Ok(new) => Ok(Box::new(new)), - Err(_err) => Err(Exceptions::unsupportedOperationEmpty()), + Err(_err) => Err(Exceptions::unsupportedOperation), } } diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index 5dcd990..294fc24 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -36,7 +36,7 @@ impl BitMatrixParser { pub fn new(bit_matrix: BitMatrix) -> Result { let dimension = bit_matrix.getHeight(); if dimension < 21 || (dimension & 0x03) != 1 { - Err(Exceptions::format(format!( + Err(Exceptions::formatWith(format!( "{dimension} < 21 || ({dimension} % 0x03) != 1" ))) } else { @@ -58,10 +58,7 @@ impl BitMatrixParser { */ pub fn readFormatInformation(&mut self) -> Result<&FormatInformation, Exceptions> { if self.parsedFormatInfo.is_some() { - return self - .parsedFormatInfo - .as_ref() - .ok_or(Exceptions::parseEmpty()); + return self.parsedFormatInfo.as_ref().ok_or(Exceptions::parse); } // Read top-left format info bits @@ -92,9 +89,7 @@ impl BitMatrixParser { self.parsedFormatInfo = FormatInformation::decodeFormatInformation(formatInfoBits1, formatInfoBits2); - self.parsedFormatInfo - .as_ref() - .ok_or(Exceptions::formatEmpty()) + self.parsedFormatInfo.as_ref().ok_or(Exceptions::format) } /** @@ -146,7 +141,7 @@ impl BitMatrixParser { return Ok(theParsedVersion); } } - Err(Exceptions::formatEmpty()) + Err(Exceptions::format) } fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 { @@ -227,7 +222,7 @@ impl BitMatrixParser { } if resultOffset != version.getTotalCodewords() as usize { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } Ok(result) } diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index 5bc3066..6ca5d4c 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -55,7 +55,7 @@ impl DataBlock { ecLevel: ErrorCorrectionLevel, ) -> Result, Exceptions> { if rawCodewords.len() as u32 != version.getTotalCodewords() { - return Err(Exceptions::illegalArgumentEmpty()); + return Err(Exceptions::illegalArgument); } // 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 5f89774..6d8a284 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::illegalArgument(format!( + _ => Err(Exceptions::illegalArgumentWith(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 635a63d..604e480 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::format(format!( + return Err(Exceptions::formatWith(format!( "Mode::Structured append expected bits.available() < 16, found bits of {}", bits.available() ))); @@ -93,7 +93,9 @@ pub fn decode( let value = parseECIValue(&mut bits)?; currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value).ok(); if currentCharacterSetECI.is_none() { - return Err(Exceptions::format(format!("Value of {value} not valid"))); + return Err(Exceptions::formatWith(format!( + "Value of {value} not valid" + ))); } } Mode::HANZI => { @@ -130,7 +132,7 @@ pub fn decode( currentCharacterSetECI, hints, )?, - _ => return Err(Exceptions::formatEmpty()), + _ => return Err(Exceptions::format), } } } @@ -179,7 +181,7 @@ fn decodeHanziSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -206,10 +208,10 @@ fn decodeHanziSegment( } let gb_encoder = - encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalStateEmpty())?; + encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalState)?; let encode_string = gb_encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parse(format!("unable to decode buffer {buffer:?}: {e}")))?; + .map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); Ok(()) } @@ -223,7 +225,7 @@ fn decodeKanjiSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -252,7 +254,7 @@ fn decodeKanjiSegment( let encoder = { let _ = currentCharacterSetECI; let _ = hints; - encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::formatEmpty())? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)? }; #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -265,12 +267,12 @@ fn decodeKanjiSegment( encoding::all::ISO_8859_1 } } else { - encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::formatEmpty())? + encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)? }; let encode_string = encoder .decode(&buffer, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parse(format!("unable to decode buffer {buffer:?}: {e}")))?; + .map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?; result.push_str(&encode_string); @@ -287,7 +289,7 @@ fn decodeByteSegment( ) -> Result<(), Exceptions> { // Don't crash trying to read more bits than we have available. if 8 * count > bits.available() { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let mut readBytes = vec![0u8; count]; @@ -303,7 +305,7 @@ fn decodeByteSegment( // give a hint. { #[cfg(not(feature = "allow_forced_iso_ied_18004_compliance"))] - StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalStateEmpty())? + StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalState)? } #[cfg(feature = "allow_forced_iso_ied_18004_compliance")] @@ -318,14 +320,14 @@ fn decodeByteSegment( CharacterSetECI::getCharset( currentCharacterSetECI .as_ref() - .ok_or(Exceptions::illegalStateEmpty())?, + .ok_or(Exceptions::illegalState)?, ) }; let encode_string = if currentCharacterSetECI.is_some() && currentCharacterSetECI .as_ref() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? == &CharacterSetECI::Cp437 { { @@ -337,7 +339,9 @@ fn decodeByteSegment( } else { encoding .decode(&readBytes, encoding::DecoderTrap::Strict) - .map_err(|e| Exceptions::parse(format!("unable to decode buffer {readBytes:?}: {e}")))? + .map_err(|e| { + Exceptions::parseWith(format!("unable to decode buffer {readBytes:?}: {e}")) + })? }; result.push_str(&encode_string); @@ -348,13 +352,13 @@ fn decodeByteSegment( fn toAlphaNumericChar(value: u32) -> Result { if value as usize >= ALPHANUMERIC_CHARS.len() { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } ALPHANUMERIC_CHARS .chars() .nth(value as usize) - .ok_or(Exceptions::formatEmpty()) + .ok_or(Exceptions::format) } fn decodeAlphanumericSegment( @@ -368,7 +372,7 @@ fn decodeAlphanumericSegment( let mut count = count; while count > 1 { if bits.available() < 11 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let nextTwoCharsBits = bits.readBits(11)?; result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?); @@ -378,7 +382,7 @@ fn decodeAlphanumericSegment( if count == 1 { // special case: one character left if bits.available() < 6 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } result.push(toAlphaNumericChar(bits.readBits(6)?)?); } @@ -386,17 +390,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::indexOutOfBoundsEmpty())? - == '%' - { + if result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? == '%' { if i < result.len() - 1 && result .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? + .ok_or(Exceptions::indexOutOfBounds)? == '%' { // %% is rendered as % @@ -422,11 +421,11 @@ fn decodeNumericSegment( while count >= 3 { // Each 10 bits encodes three digits if bits.available() < 10 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let threeDigitsBits = bits.readBits(10)?; if threeDigitsBits >= 1000 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } result.push(toAlphaNumericChar(threeDigitsBits / 100)?); result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?); @@ -436,22 +435,22 @@ fn decodeNumericSegment( if count == 2 { // Two digits left over to read, encoded in 7 bits if bits.available() < 7 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } let twoDigitsBits = bits.readBits(7)?; if twoDigitsBits >= 100 { - return Err(Exceptions::formatEmpty()); + 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::formatEmpty()); + return Err(Exceptions::format); } let digitBits = bits.readBits(4)?; if digitBits >= 10 { - return Err(Exceptions::formatEmpty()); + return Err(Exceptions::format); } result.push(toAlphaNumericChar(digitBits)?); } @@ -476,5 +475,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result { return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes); } - Err(Exceptions::formatEmpty()) + Err(Exceptions::format) } diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index b9137e8..7fdfcce 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -47,7 +47,7 @@ impl ErrorCorrectionLevel { 1 => Ok(Self::L), 2 => Ok(Self::H), 3 => Ok(Self::Q), - _ => Err(Exceptions::illegalArgument(format!( + _ => Err(Exceptions::illegalArgumentWith(format!( "{bits} is not a valid bit selection" ))), } @@ -109,7 +109,7 @@ impl FromStr for ErrorCorrectionLevel { return number_possible.try_into(); } - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "could not parse {s} into an ec level" ))); } diff --git a/src/qrcode/decoder/mode.rs b/src/qrcode/decoder/mode.rs index 9790f43..9a82354 100644 --- a/src/qrcode/decoder/mode.rs +++ b/src/qrcode/decoder/mode.rs @@ -68,7 +68,9 @@ impl Mode { { Ok(Self::HANZI) } - _ => Err(Exceptions::illegalArgument(format!("{bits} is not valid"))), + _ => Err(Exceptions::illegalArgumentWith(format!( + "{bits} is not valid" + ))), } } diff --git a/src/qrcode/decoder/qrcode_decoder.rs b/src/qrcode/decoder/qrcode_decoder.rs index b7b10ab..921fcae 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::checksumEmpty())) + Err(ce.unwrap_or(Exceptions::checksum)) } } _ => Err(er), diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index a1fc8ec..1314dba 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -101,14 +101,14 @@ impl Version { dimension: u32, ) -> Result<&'static Version, Exceptions> { if dimension % 4 != 1 { - return Err(Exceptions::format("dimension incorrect")); + return Err(Exceptions::formatWith("dimension incorrect")); } Self::getVersionForNumber((dimension - 17) / 4) } pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> { if !(1..=40).contains(&versionNumber) { - return Err(Exceptions::illegalArgument("version out of spec")); + return Err(Exceptions::illegalArgumentWith("version out of spec")); } Ok(&VERSIONS[versionNumber as usize - 1]) } @@ -136,7 +136,7 @@ impl Version { return Self::getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } /** diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index 5619b3e..6af2228 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -161,9 +161,9 @@ impl AlignmentPatternFinder { Ok(*(self .possibleCenters .get(0) - .ok_or(Exceptions::indexOutOfBoundsEmpty()))?) + .ok_or(Exceptions::indexOutOfBounds))?) } else { - Err(Exceptions::notFoundEmpty()) + Err(Exceptions::notFound) } } diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 2c0ef0c..48b3bd0 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -696,7 +696,7 @@ impl<'a> FinderPatternFinder<'_> { let startSize = self.possibleCenters.len(); if startSize < 3 { // Couldn't find enough finder patterns - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } self.possibleCenters @@ -713,19 +713,19 @@ impl<'a> FinderPatternFinder<'_> { for i in 0..self.possibleCenters.len() { let Some(fpi) = self.possibleCenters.get(i) else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); }; let minModuleSize = fpi.getEstimatedModuleSize(); for j in (i + 1)..(self.possibleCenters.len() - 1) { let Some(fpj) = self.possibleCenters.get(j) else { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); }; 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::notFoundEmpty()); + return Err(Exceptions::notFound); }; let maxModuleSize = fpk.getEstimatedModuleSize(); if maxModuleSize > minModuleSize * 1.4 { @@ -777,16 +777,16 @@ impl<'a> FinderPatternFinder<'_> { } if distortion == f64::MAX { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } if bestPatterns[0].is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } - let p1 = bestPatterns[0].ok_or(Exceptions::notFoundEmpty())?; - let p2 = bestPatterns[1].ok_or(Exceptions::notFoundEmpty())?; - let p3 = bestPatterns[2].ok_or(Exceptions::notFoundEmpty())?; + let p1 = bestPatterns[0].ok_or(Exceptions::notFound)?; + let p2 = bestPatterns[1].ok_or(Exceptions::notFound)?; + let p3 = bestPatterns[2].ok_or(Exceptions::notFound)?; Ok([p1, p2, p3]) } diff --git a/src/qrcode/detector/qrcode_detector.rs b/src/qrcode/detector/qrcode_detector.rs index 9010000..8b19979 100644 --- a/src/qrcode/detector/qrcode_detector.rs +++ b/src/qrcode/detector/qrcode_detector.rs @@ -105,7 +105,7 @@ impl<'a> Detector<'_> { let moduleSize = self.calculateModuleSize(topLeft, topRight, bottomLeft); if moduleSize < 1.0 { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } let dimension = Self::computeDimension(topLeft, topRight, bottomLeft, moduleSize)?; let provisionalVersion = Version::getProvisionalVersionForDimension(dimension)?; @@ -147,7 +147,7 @@ impl<'a> Detector<'_> { alignmentPattern.as_ref(), dimension, ) - .ok_or(Exceptions::notFoundEmpty())?; + .ok_or(Exceptions::notFound)?; let bits = Detector::sampleGrid(self.image, &transform, dimension)?; @@ -160,7 +160,7 @@ impl<'a> Detector<'_> { if alignmentPattern.is_some() { points.push( alignmentPattern - .ok_or(Exceptions::notFoundEmpty())? + .ok_or(Exceptions::notFound)? .into_rxing_result_point(), ) } @@ -241,7 +241,7 @@ impl<'a> Detector<'_> { match dimension & 0x03 { 0 => dimension += 1, 2 => dimension -= 1, - 3 => return Err(Exceptions::notFoundEmpty()), + 3 => return Err(Exceptions::notFound), _ => {} } Ok(dimension as u32) @@ -428,13 +428,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::notFoundEmpty()); + return Err(Exceptions::notFound); } 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::notFoundEmpty()); + return Err(Exceptions::notFound); } let mut alignmentFinder = AlignmentPatternFinder::new( diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index e6c4a22..5796fd0 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -174,7 +174,7 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "Invalid mask pattern: {maskPattern}" ))) } diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index 1368b3c..57ec345 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -278,7 +278,7 @@ pub fn embedDataBits( } // All bits should be consumed. if bitIndex != dataBits.getSize() { - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "Not all bits consumed: {}/{}", bitIndex, dataBits.getSize() @@ -323,7 +323,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::illegalArgument("0 polynomial")); + return Err(Exceptions::illegalArgumentWith("0 polynomial")); } let mut value = value; // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 @@ -347,7 +347,7 @@ pub fn makeTypeInfoBits( bits: &mut BitArray, ) -> Result<(), Exceptions> { if !QRCode::isValidMaskPattern(maskPattern as i32) { - return Err(Exceptions::writer("Invalid mask pattern")); + return Err(Exceptions::writerWith("Invalid mask pattern")); } let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern; bits.appendBits(typeInfo, 5)?; @@ -361,7 +361,7 @@ pub fn makeTypeInfoBits( if bits.getSize() != 15 { // Just in case. - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "should not happen but we got: {}", bits.getSize() ))); @@ -378,7 +378,7 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(), if bits.getSize() != 18 { // Just in case. - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "should not happen but we got: {}", bits.getSize() ))); @@ -411,7 +411,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) { // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<(), Exceptions> { if matrix.get(8, matrix.getHeight() - 8) == 0 { - return Err(Exceptions::writerEmpty()); + return Err(Exceptions::writer); } matrix.set(8, matrix.getHeight() - 8, 1); Ok(()) @@ -424,7 +424,7 @@ pub fn embedHorizontalSeparationPattern( ) -> Result<(), Exceptions> { for x in 0..8 { if !isEmpty(matrix.get(xStart + x, yStart)) { - return Err(Exceptions::writerEmpty()); + return Err(Exceptions::writer); } matrix.set(xStart + x, yStart, 0); } @@ -438,7 +438,7 @@ pub fn embedVerticalSeparationPattern( ) -> Result<(), Exceptions> { for y in 0..7 { if !isEmpty(matrix.get(xStart, yStart + y)) { - return Err(Exceptions::writerEmpty()); + 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 d7c16ca..f10c95a 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::writer(format!( + return Err(Exceptions::writerWith(format!( "Data too big for version {version}" ))); } @@ -186,7 +186,7 @@ impl MinimalEncoder { } } if smallestRXingResult < 0 { - return Err(Exceptions::writer("Data too big for any version")); + return Err(Exceptions::writerWith("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::illegalArgument(format!( + _ => Err(Exceptions::illegalArgumentWith(format!( "Illegal mode {mode:?}" ))), } @@ -259,27 +259,19 @@ impl MinimalEncoder { position: usize, edge: Option>, ) -> Result<(), Exceptions> { - let vertexIndex = position - + edge - .as_ref() - .ok_or(Exceptions::formatEmpty())? - .characterLength as usize; - let modeEdges = &mut edges[vertexIndex][edge - .as_ref() - .ok_or(Exceptions::formatEmpty())? - .charsetEncoderIndex]; + let vertexIndex = + position + edge.as_ref().ok_or(Exceptions::format)?.characterLength as usize; + let modeEdges = + &mut edges[vertexIndex][edge.as_ref().ok_or(Exceptions::format)?.charsetEncoderIndex]; let modeOrdinal = - Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::formatEmpty())?.mode))? + Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::format)?.mode))? as usize; if modeEdges[modeOrdinal].is_none() || modeEdges[modeOrdinal] .as_ref() - .ok_or(Exceptions::formatEmpty())? + .ok_or(Exceptions::format)? .cachedTotalSize - > edge - .as_ref() - .ok_or(Exceptions::formatEmpty())? - .cachedTotalSize + > edge.as_ref().ok_or(Exceptions::format)?.cachedTotalSize { modeEdges[modeOrdinal] = edge; } @@ -302,12 +294,12 @@ impl MinimalEncoder { .encoders .canEncode( &self.stringToEncode[from], - priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?, + priorityEncoderIndex.ok_or(Exceptions::format)?, ) - .ok_or(Exceptions::formatEmpty())? + .ok_or(Exceptions::format)? { - start = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?; - end = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())? + 1; + start = priorityEncoderIndex.ok_or(Exceptions::format)?; + end = priorityEncoderIndex.ok_or(Exceptions::format)? + 1; } for i in start..end { @@ -316,10 +308,10 @@ impl MinimalEncoder { .canEncode( self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, i, ) - .ok_or(Exceptions::formatEmpty())? + .ok_or(Exceptions::format)? { self.addEdge( edges, @@ -335,7 +327,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writerEmpty())?, + .ok_or(Exceptions::writer)?, )), )?; } @@ -343,9 +335,7 @@ impl MinimalEncoder { if self.canEncode( &Mode::KANJI, - self.stringToEncode - .get(from) - .ok_or(Exceptions::formatEmpty())?, + self.stringToEncode.get(from).ok_or(Exceptions::format)?, ) { self.addEdge( edges, @@ -361,7 +351,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writerEmpty())?, + .ok_or(Exceptions::writer)?, )), )?; } @@ -371,7 +361,7 @@ impl MinimalEncoder { &Mode::ALPHANUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { self.addEdge( edges, @@ -386,7 +376,7 @@ impl MinimalEncoder { &Mode::ALPHANUMERIC, self.stringToEncode .get(from + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { 1 @@ -398,7 +388,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writerEmpty())?, + .ok_or(Exceptions::writer)?, )), )?; } @@ -407,7 +397,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { self.addEdge( edges, @@ -422,7 +412,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { 1 @@ -431,7 +421,7 @@ impl MinimalEncoder { &Mode::NUMERIC, self.stringToEncode .get(from + 2) - .ok_or(Exceptions::indexOutOfBoundsEmpty())?, + .ok_or(Exceptions::indexOutOfBounds)?, ) { 2 @@ -443,7 +433,7 @@ impl MinimalEncoder { self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writerEmpty())?, + .ok_or(Exceptions::writer)?, )), )?; } @@ -606,16 +596,16 @@ impl MinimalEncoder { version, edges[inputLength][minJ][minK] .as_ref() - .ok_or(Exceptions::writerEmpty())? + .ok_or(Exceptions::writer)? .clone(), self.isGS1, &self.ecLevel, self.encoders.clone(), self.stringToEncode.clone(), ) - .ok_or(Exceptions::writerEmpty())?) + .ok_or(Exceptions::writer)?) } else { - Err(Exceptions::writer(format!( + Err(Exceptions::writerWith(format!( r#"Internal error: failed to encode "{}"#, self.stringToEncode .iter() @@ -1031,7 +1021,7 @@ impl RXingResultNode { bits, self.encoders .getCharset(self.charsetEncoderIndex) - .ok_or(Exceptions::writerEmpty())?, + .ok_or(Exceptions::writer)?, )?; } Ok(()) diff --git a/src/qrcode/encoder/qrcode_encoder.rs b/src/qrcode/encoder/qrcode_encoder.rs index 723d714..dfdb21e 100644 --- a/src/qrcode/encoder/qrcode_encoder.rs +++ b/src/qrcode/encoder/qrcode_encoder.rs @@ -100,9 +100,8 @@ pub fn encode_with_hints( let mut has_encoding_hint = hints.contains_key(&EncodeHintType::CHARACTER_SET); 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::writerEmpty())?, - ) + encoding = + Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writer)?) } } @@ -180,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::writer("Data too big for requested version")); + return Err(Exceptions::writerWith("Data too big for requested version")); } } else { version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?; @@ -388,7 +387,7 @@ fn chooseVersion( return Ok(version); } } - Err(Exceptions::writer(format!( + Err(Exceptions::writerWith(format!( "data too big {numInputBits}/{ecLevel:?}" ))) } @@ -416,7 +415,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> { let capacity = num_data_bytes * 8; if bits.getSize() > capacity as usize { - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "data bits cannot fit in the QR Code{capacity} > " ))); } @@ -444,7 +443,7 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?; } if bits.getSize() != capacity as usize { - return Err(Exceptions::writer("Bits size does not equal capacity")); + return Err(Exceptions::writerWith("Bits size does not equal capacity")); } Ok(()) } @@ -463,7 +462,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // numECBytesInBlock: &mut [u32], ) -> Result<(u32, u32), Exceptions> { if block_id >= num_rsblocks { - return Err(Exceptions::writer("Block ID too large")); + return Err(Exceptions::writerWith("Block ID too large")); } // numRsBlocksInGroup2 = 196 % 5 = 1 let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks; @@ -484,18 +483,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( // Sanity checks. // 26 = 26 if num_ec_bytes_in_group1 != numEcBytesInGroup2 { - return Err(Exceptions::writer("EC bytes mismatch")); + return Err(Exceptions::writerWith("EC bytes mismatch")); } // 5 = 4 + 1. if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 { - return Err(Exceptions::writer("RS blocks mismatch")); + return Err(Exceptions::writerWith("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::writer("total bytes mismatch")); + return Err(Exceptions::writerWith("total bytes mismatch")); } Ok(if block_id < num_rs_blocks_in_group1 { @@ -517,7 +516,7 @@ pub fn interleaveWithECBytes( ) -> Result { // "bits" must have "getNumDataBytes" bytes of data. if bits.getSizeInBytes() as u32 != num_data_bytes { - return Err(Exceptions::writer( + return Err(Exceptions::writerWith( "Number of bits and data bytes does not match", )); } @@ -552,7 +551,7 @@ pub fn interleaveWithECBytes( data_bytes_offset += numDataBytesInBlock as usize; } if num_data_bytes != data_bytes_offset as u32 { - return Err(Exceptions::writer("Data bytes does not match offset")); + return Err(Exceptions::writerWith("Data bytes does not match offset")); } let mut result = BitArray::new(); @@ -577,7 +576,7 @@ pub fn interleaveWithECBytes( } if num_total_bytes != result.getSizeInBytes() as u32 { // Should be same. - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "Interleaving error: {} and {} differ.", num_total_bytes, result.getSizeInBytes() @@ -627,7 +626,7 @@ pub fn appendLengthInfo( ) -> Result<(), Exceptions> { let numBits = mode.getCharacterCountBits(version); if num_letters >= (1 << numBits) { - return Err(Exceptions::writer(format!( + return Err(Exceptions::writerWith(format!( "{} is bigger than {}", num_letters, ((1 << numBits) - 1) @@ -650,7 +649,7 @@ pub fn appendBytes( Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits), Mode::BYTE => append8BitBytes(content, bits, encoding), Mode::KANJI => appendKanjiBytes(content, bits), - _ => Err(Exceptions::writer(format!("Invalid mode: {mode:?}"))), + _ => Err(Exceptions::writerWith(format!("Invalid mode: {mode:?}"))), } } @@ -658,22 +657,18 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce let length = content.len(); let mut i = 0; while i < length { - let num1 = content - .chars() - .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 - - b'0'; + let num1 = content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? 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::indexOutOfBoundsEmpty())? as u8 + .ok_or(Exceptions::indexOutOfBounds)? as u8 - b'0'; let num3 = content .chars() .nth(i + 2) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 + .ok_or(Exceptions::indexOutOfBounds)? as u8 - b'0'; bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?; i += 3; @@ -682,7 +677,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce let num2 = content .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8 + .ok_or(Exceptions::indexOutOfBounds)? as u8 - b'0'; bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?; i += 2; @@ -699,24 +694,20 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(), let length = content.len(); let mut i = 0; while i < length { - let code1 = getAlphanumericCode( - content - .chars() - .nth(i) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32, - ); + let code1 = + getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32); if code1 == -1 { - return Err(Exceptions::writerEmpty()); + return Err(Exceptions::writer); } if i + 1 < length { let code2 = getAlphanumericCode( content .chars() .nth(i + 1) - .ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32, + .ok_or(Exceptions::indexOutOfBounds)? as u32, ); if code2 == -1 { - return Err(Exceptions::writerEmpty()); + return Err(Exceptions::writer); } // Encode two alphanumeric letters in 11 bits. bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?; @@ -737,7 +728,7 @@ pub fn append8BitBytes( ) -> Result<(), Exceptions> { let bytes = encoding .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::writer(format!("error {e}")))?; + .map_err(|e| Exceptions::writerWith(format!("error {e}")))?; for b in bytes { bits.appendBits(b as u32, 8)?; } @@ -749,9 +740,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except let bytes = sjis .encode(content, encoding::EncoderTrap::Strict) - .map_err(|e| Exceptions::writer(format!("error {e}")))?; + .map_err(|e| Exceptions::writerWith(format!("error {e}")))?; if bytes.len() % 2 != 0 { - return Err(Exceptions::writer("Kanji byte size not even")); + return Err(Exceptions::writerWith("Kanji byte size not even")); } let max_i = bytes.len() - 1; // bytes.length must be even let mut i = 0; @@ -766,7 +757,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except subtracted = code as i32 - 0xc140; } if subtracted == -1 { - return Err(Exceptions::writer("Invalid byte sequence")); + return Err(Exceptions::writerWith("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 d641b7e..08acead 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -83,7 +83,7 @@ impl Reader for QRCodeReader { // if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) { other .downcast_ref::() - .ok_or(Exceptions::illegalStateEmpty())? + .ok_or(Exceptions::illegalState)? .applyMirroredCorrection(&mut points); } } @@ -153,11 +153,11 @@ impl QRCodeReader { let leftTopBlack = image.getTopLeftOnBit(); let rightBottomBlack = image.getBottomRightOnBit(); if leftTopBlack.is_none() || rightBottomBlack.is_none() { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } - let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBoundsEmpty())?; - let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBoundsEmpty())?; + let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBounds)?; + let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBounds)?; let moduleSize = Self::moduleSize(&leftTopBlack, image)?; @@ -168,7 +168,7 @@ impl QRCodeReader { // Sanity check! if left >= right || top >= bottom { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } if bottom - top != right - left { @@ -177,17 +177,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::notFoundEmpty()); + return Err(Exceptions::notFound); } } 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::notFoundEmpty()); + return Err(Exceptions::notFound); } if matrixHeight != matrixWidth { // Only possibly decode square regions - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } // Push in the "border" by half the module width so that we start @@ -205,7 +205,7 @@ impl QRCodeReader { if nudgedTooFarRight > 0 { if nudgedTooFarRight > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } left -= nudgedTooFarRight; } @@ -214,7 +214,7 @@ impl QRCodeReader { if nudgedTooFarDown > 0 { if nudgedTooFarDown > nudge as i32 { // Neither way fits; abort - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } top -= nudgedTooFarDown; } @@ -251,7 +251,7 @@ impl QRCodeReader { y += 1; } if x == width || y == height { - return Err(Exceptions::notFoundEmpty()); + return Err(Exceptions::notFound); } 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 e9707e6..340862e 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -58,18 +58,18 @@ impl Writer for QRCodeWriter { hints: &crate::EncodingHintDictionary, ) -> Result { if contents.is_empty() { - return Err(Exceptions::illegalArgument("found empty contents")); + return Err(Exceptions::illegalArgumentWith("found empty contents")); } if format != &BarcodeFormat::QR_CODE { - return Err(Exceptions::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(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::illegalArgument(format!( + return Err(Exceptions::illegalArgumentWith(format!( "requested dimensions are too small: {width}x{height}" ))); } @@ -86,7 +86,7 @@ impl Writer for QRCodeWriter { if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) { margin .parse::() - .map_err(|e| Exceptions::parse(format!("could not parse {margin}: {e}")))? + .map_err(|e| Exceptions::parseWith(format!("could not parse {margin}: {e}")))? } else { QUIET_ZONE_SIZE }; @@ -108,10 +108,10 @@ impl QRCodeWriter { ) -> Result { let input = code.getMatrix(); if input.is_none() { - return Err(Exceptions::illegalState("matrix is empty")); + return Err(Exceptions::illegalStateWith("matrix is empty")); } - let input = input.as_ref().ok_or(Exceptions::illegalStateEmpty())?; + let input = input.as_ref().ok_or(Exceptions::illegalState)?; 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 2201910..cd20f1c 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -127,7 +127,7 @@ impl LuminanceSource for RGBLuminanceSource { height, ) { Ok(crop) => Ok(Box::new(crop)), - Err(_error) => Err(Exceptions::unsupportedOperationEmpty()), + Err(_error) => Err(Exceptions::unsupportedOperation), } } @@ -179,7 +179,7 @@ impl RGBLuminanceSource { height: usize, ) -> Result { if left + width > data_width || top + height > data_height { - return Err(Exceptions::illegalArgument( + return Err(Exceptions::illegalArgumentWith( "Crop rectangle does not fit within image data.", )); } diff --git a/src/svg_luminance_source.rs b/src/svg_luminance_source.rs index 5490ce7..e960ee9 100644 --- a/src/svg_luminance_source.rs +++ b/src/svg_luminance_source.rs @@ -56,11 +56,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::format(format!("could not parse svg data: {}", "err"))); + return Err(Exceptions::formatWith(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::format("could not create pixmap")); + return Err(Exceptions::formatWith("could not create pixmap")); }; resvg::render( @@ -71,7 +71,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::format("could not create image buffer")); + return Err(Exceptions::formatWith("could not create image buffer")); }; // let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else {