diff --git a/src/aztec/aztec_reader.rs b/src/aztec/aztec_reader.rs index 043b208..d03f0cb 100644 --- a/src/aztec/aztec_reader.rs +++ b/src/aztec/aztec_reader.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use crate::{ - common::{DecoderRXingResult, DetectorRXingResult}, + common::{DecoderRXingResult, DetectorRXingResult, Result}, exceptions::Exceptions, BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, Reader, @@ -41,7 +41,7 @@ impl Reader for AztecReader { * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded */ - fn decode(&mut self, image: &mut BinaryBitmap) -> Result { + fn decode(&mut self, image: &mut BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -49,7 +49,7 @@ impl Reader for AztecReader { &mut self, image: &mut BinaryBitmap, hints: &HashMap, - ) -> Result { + ) -> Result { // let notFoundException = None; // let formatException = None; let mut detector = Detector::new(image.getBlackMatrix()); diff --git a/src/aztec/aztec_writer.rs b/src/aztec/aztec_writer.rs index 0994120..0a32ad7 100644 --- a/src/aztec/aztec_writer.rs +++ b/src/aztec/aztec_writer.rs @@ -19,8 +19,9 @@ use std::collections::HashMap; use encoding::EncodingRef; use crate::{ - common::BitMatrix, exceptions::Exceptions, BarcodeFormat, EncodeHintType, EncodeHintValue, - Writer, + common::{BitMatrix, Result}, + exceptions::Exceptions, + BarcodeFormat, EncodeHintType, EncodeHintValue, Writer, }; use super::encoder::{aztec_encoder, AztecCode}; @@ -38,7 +39,7 @@ impl Writer for AztecWriter { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -49,7 +50,7 @@ impl Writer for AztecWriter { width: i32, height: i32, hints: &std::collections::HashMap, - ) -> Result { + ) -> Result { let mut charset = None; // Do not add any ECI code by default let mut ecc_percent = aztec_encoder::DEFAULT_EC_PERCENT; let mut layers = aztec_encoder::DEFAULT_AZTEC_LAYERS; @@ -93,7 +94,7 @@ fn encode( charset: Option, ecc_percent: u32, layers: i32, -) -> Result { +) -> Result { if format != BarcodeFormat::AZTEC { return Err(Exceptions::IllegalArgumentException(Some(format!( "can only encode AZTEC, but got {format:?}" @@ -108,7 +109,7 @@ fn encode( renderRXingResult(&aztec, width, height) } -fn renderRXingResult(code: &AztecCode, width: u32, height: u32) -> Result { +fn renderRXingResult(code: &AztecCode, width: u32, height: u32) -> Result { let input = code.getMatrix(); let input_width = input.getWidth(); diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index 98d6af5..895f2ae 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -19,7 +19,7 @@ use crate::{ reedsolomon::{ get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonDecoder, }, - BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult, + BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult, Result, }, exceptions::Exceptions, }; @@ -73,9 +73,7 @@ const DIGIT_TABLE: [&str; 16] = [ // private AztecDetectorRXingResult ddata; -pub fn decode( - detectorRXingResult: &AztecDetectorRXingResult, -) -> Result { +pub fn decode(detectorRXingResult: &AztecDetectorRXingResult) -> Result { //let mut detectorRXingResult = detectorRXingResult.clone(); let matrix = detectorRXingResult.getBits(); let rawbits = extract_bits(detectorRXingResult, matrix); @@ -94,7 +92,7 @@ pub fn decode( } /// This method is used for testing the high-level encoder -pub fn highLevelDecode(correctedBits: &[bool]) -> Result { +pub fn highLevelDecode(correctedBits: &[bool]) -> Result { get_encoded_data(correctedBits) } @@ -103,7 +101,7 @@ pub fn highLevelDecode(correctedBits: &[bool]) -> Result { * * @return the decoded string */ -fn get_encoded_data(corrected_bits: &[bool]) -> Result { +fn get_encoded_data(corrected_bits: &[bool]) -> Result { let end_index = corrected_bits.len(); let mut latch_table = Table::Upper; // table most recently latched to let mut shift_table = Table::Upper; // table to use for the next read @@ -288,7 +286,7 @@ fn getTable(t: char) -> Table { * @param table the table used * @param code the code of the character */ -fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { +fn get_character(table: Table, code: u32) -> Result<&'static str> { match table { Table::Upper => Ok(UPPER_TABLE[code as usize]), Table::Lower => Ok(LOWER_TABLE[code as usize]), @@ -337,7 +335,7 @@ impl CorrectedBitsRXingResult { fn correct_bits( ddata: &AztecDetectorRXingResult, rawbits: &[bool], -) -> Result { +) -> Result { let gf: GenericGFRef; let codeword_size; diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index 007ea5d..9445288 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -20,7 +20,7 @@ use crate::{ common::{ detector::{MathUtils, WhiteRectangleDetector}, reedsolomon::{self, ReedSolomonDecoder}, - BitMatrix, DefaultGridSampler, GridSampler, + BitMatrix, DefaultGridSampler, GridSampler, Result, }, exceptions::Exceptions, RXingResultPoint, ResultPoint, @@ -64,7 +64,7 @@ impl<'a> Detector<'_> { } } - pub fn detect_false(&mut self) -> Result { + pub fn detect_false(&mut self) -> Result { self.detect(false) } @@ -75,7 +75,7 @@ impl<'a> Detector<'_> { * @return {@link AztecDetectorRXingResult} encapsulating results of detecting an Aztec Code * @throws NotFoundException if no Aztec Code can be found */ - pub fn detect(&mut self, is_mirror: bool) -> Result { + pub fn detect(&mut self, is_mirror: bool) -> Result { // dbg!(self.image.to_string()); // 1. Get the center of the aztec matrix let p_center = self.get_matrix_center(); @@ -118,10 +118,7 @@ impl<'a> Detector<'_> { * @param bullsEyeCorners the array of bull's eye corners * @throws NotFoundException in case of too many errors or invalid parameters */ - fn extractParameters( - &mut self, - bulls_eye_corners: &[RXingResultPoint], - ) -> Result<(), Exceptions> { + fn extractParameters(&mut self, bulls_eye_corners: &[RXingResultPoint]) -> Result<()> { if !self.is_valid(&bulls_eye_corners[0]) || !self.is_valid(&bulls_eye_corners[1]) || !self.is_valid(&bulls_eye_corners[2]) @@ -179,7 +176,7 @@ impl<'a> Detector<'_> { Ok(()) } - fn get_rotation(sides: &[u32], length: u32) -> Result { + fn get_rotation(sides: &[u32], length: u32) -> Result { // In a normal pattern, we expect to See // ** .* D A // * * @@ -222,7 +219,7 @@ impl<'a> Detector<'_> { * @param compact true if this is a compact Aztec code * @throws NotFoundException if the array contains too many errors */ - fn get_corrected_parameter_data(parameterData: u64, compact: bool) -> Result { + fn get_corrected_parameter_data(parameterData: u64, compact: bool) -> Result { let mut parameter_data = parameterData; let num_codewords: i32; @@ -269,10 +266,7 @@ impl<'a> Detector<'_> { * @return The corners of the bull-eye * @throws NotFoundException If no valid bull-eye can be found */ - fn get_bulls_eye_corners( - &mut self, - pCenter: Point, - ) -> Result<[RXingResultPoint; 4], Exceptions> { + fn get_bulls_eye_corners(&mut self, pCenter: Point) -> Result<[RXingResultPoint; 4]> { let mut pina = pCenter; let mut pinb = pCenter; let mut pinc = pCenter; @@ -504,7 +498,7 @@ impl<'a> Detector<'_> { top_right: &RXingResultPoint, bottom_right: &RXingResultPoint, bottom_left: &RXingResultPoint, - ) -> Result { + ) -> Result { let sampler = DefaultGridSampler::default(); let dimension = self.get_dimension(); diff --git a/src/aztec/encoder/aztec_encoder.rs b/src/aztec/encoder/aztec_encoder.rs index e63d5ba..6c8ea51 100644 --- a/src/aztec/encoder/aztec_encoder.rs +++ b/src/aztec/encoder/aztec_encoder.rs @@ -21,7 +21,7 @@ use crate::{ reedsolomon::{ get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder, }, - BitArray, BitMatrix, + BitArray, BitMatrix, Result, }, exceptions::Exceptions, }; @@ -50,7 +50,7 @@ pub const WORD_SIZE: [u32; 33] = [ * @param data input data string; must be encodable as ISO/IEC 8859-1 (Latin-1) * @return Aztec symbol matrix with metadata */ -pub fn encode_simple(data: &str) -> Result { +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")))); @@ -67,11 +67,7 @@ pub fn encode_simple(data: &str) -> Result { * @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers * @return Aztec symbol matrix with metadata */ -pub fn encode( - data: &str, - minECCPercent: u32, - userSpecifiedLayers: i32, -) -> Result { +pub fn encode(data: &str, minECCPercent: u32, userSpecifiedLayers: i32) -> Result { if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) { encode_bytes(&bytes, minECCPercent, userSpecifiedLayers) } else { @@ -98,7 +94,7 @@ pub fn encode_with_charset( minECCPercent: u32, userSpecifiedLayers: i32, charset: encoding::EncodingRef, -) -> Result { +) -> Result { if let Ok(bytes) = charset.encode(data, encoding::EncoderTrap::Strict) { encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset) } else { @@ -114,7 +110,7 @@ pub fn encode_with_charset( * @param data input data string * @return Aztec symbol matrix with metadata */ -pub fn encode_bytes_simple(data: &[u8]) -> Result { +pub fn encode_bytes_simple(data: &[u8]) -> Result { encode_bytes(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS) } @@ -131,7 +127,7 @@ pub fn encode_bytes( data: &[u8], minECCPercent: u32, userSpecifiedLayers: i32, -) -> Result { +) -> Result { encode_bytes_with_charset( data, minECCPercent, @@ -156,7 +152,7 @@ pub fn encode_bytes_with_charset( min_eccpercent: u32, user_specified_layers: i32, charset: encoding::EncodingRef, -) -> Result { +) -> Result { // High-level encode let bits = HighLevelEncoder::with_charset(data.into(), charset).encode()?; @@ -378,7 +374,7 @@ pub fn generateModeMessage( compact: bool, layers: u32, messageSizeInWords: u32, -) -> Result { +) -> Result { let mut mode_message = BitArray::new(); if compact { mode_message.appendBits(layers - 1, 2)?; @@ -431,11 +427,7 @@ fn drawModeMessage(matrix: &mut BitMatrix, compact: bool, matrixSize: u32, modeM } } -fn generateCheckWords( - bitArray: &BitArray, - totalBits: usize, - wordSize: usize, -) -> Result { +fn generateCheckWords(bitArray: &BitArray, totalBits: usize, wordSize: usize) -> Result { // bitArray is guaranteed to be a multiple of the wordSize, so no padding needed let message_size_in_words = bitArray.getSize() / wordSize; let mut rs = ReedSolomonEncoder::new(getGF(wordSize)?)?; @@ -475,7 +467,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve message } -fn getGF(wordSize: usize) -> Result { +fn getGF(wordSize: usize) -> Result { match wordSize { 4 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecParam)), 6 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData6)), @@ -488,7 +480,7 @@ fn getGF(wordSize: usize) -> Result { } } -pub fn stuffBits(bits: &BitArray, word_size: usize) -> Result { +pub fn stuffBits(bits: &BitArray, word_size: usize) -> Result { let mut out = BitArray::new(); let n = bits.getSize() as isize; diff --git a/src/aztec/encoder/binary_shift_token.rs b/src/aztec/encoder/binary_shift_token.rs index a8b8333..7bb24a3 100644 --- a/src/aztec/encoder/binary_shift_token.rs +++ b/src/aztec/encoder/binary_shift_token.rs @@ -16,7 +16,7 @@ use std::fmt; -use crate::{common::BitArray, Exceptions}; +use crate::common::{BitArray, Result}; #[derive(Debug, PartialEq, Eq, Clone)] pub struct BinaryShiftToken { @@ -32,7 +32,7 @@ impl BinaryShiftToken { } } - pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<(), Exceptions> { + pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<()> { let bsbc = self.binary_shift_byte_count as usize; for i in 0..bsbc { // for (int i = 0; i < bsbc; i++) { diff --git a/src/aztec/encoder/high_level_encoder.rs b/src/aztec/encoder/high_level_encoder.rs index feaf12c..b61098e 100644 --- a/src/aztec/encoder/high_level_encoder.rs +++ b/src/aztec/encoder/high_level_encoder.rs @@ -15,7 +15,7 @@ */ use crate::{ - common::{BitArray, CharacterSetECI}, + common::{BitArray, CharacterSetECI, Result}, exceptions::Exceptions, }; @@ -240,7 +240,7 @@ impl HighLevelEncoder { /** * @return text represented by this encoder encoded as a {@link BitArray} */ - pub fn encode(&self) -> Result { + pub fn encode(&self) -> Result { let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0); if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) { if eci != CharacterSetECI::ISO8859_1 { diff --git a/src/aztec/encoder/simple_token.rs b/src/aztec/encoder/simple_token.rs index 3846a02..a939e8e 100644 --- a/src/aztec/encoder/simple_token.rs +++ b/src/aztec/encoder/simple_token.rs @@ -16,7 +16,7 @@ use std::fmt; -use crate::{common::BitArray, Exceptions}; +use crate::common::{BitArray, Result}; #[derive(Debug, PartialEq, Eq, Clone)] pub struct SimpleToken { @@ -33,7 +33,7 @@ impl SimpleToken { } } - pub fn appendTo(&self, bit_array: &mut BitArray, _text: &[u8]) -> Result<(), Exceptions> { + pub fn appendTo(&self, bit_array: &mut BitArray, _text: &[u8]) -> Result<()> { bit_array.appendBits(self.value as u32, self.bit_count as usize) } diff --git a/src/aztec/encoder/state.rs b/src/aztec/encoder/state.rs index de84926..067a9eb 100644 --- a/src/aztec/encoder/state.rs +++ b/src/aztec/encoder/state.rs @@ -18,7 +18,10 @@ use std::fmt; use encoding::Encoding; -use crate::{common::BitArray, exceptions::Exceptions}; +use crate::{ + common::{BitArray, Result}, + exceptions::Exceptions, +}; use super::{HighLevelEncoder, Token}; @@ -70,7 +73,7 @@ impl State { self.bit_count } - pub fn appendFLGn(self, eci: u32) -> Result { + pub fn appendFLGn(self, eci: u32) -> Result { let bit_count = self.bit_count; let mode = self.mode; let result = self.shiftAndAppend(HighLevelEncoder::MODE_PUNCT as u32, 0); // 0: FLG(n) @@ -207,7 +210,7 @@ impl State { new_mode_bit_count <= other.bit_count } - pub fn toBitArray(self, text: &[u8]) -> Result { + pub fn toBitArray(self, text: &[u8]) -> Result { let mut symbols = Vec::new(); let tok = self.endBinaryShift(text.len() as u32).token; for tkn in tok.into_iter() { diff --git a/src/aztec/encoder/token.rs b/src/aztec/encoder/token.rs index e798774..125e996 100644 --- a/src/aztec/encoder/token.rs +++ b/src/aztec/encoder/token.rs @@ -14,7 +14,10 @@ * limitations under the License. */ -use crate::{common::BitArray, Exceptions}; +use crate::{ + common::{BitArray, Result}, + Exceptions, +}; use super::{BinaryShiftToken, SimpleToken}; @@ -26,7 +29,7 @@ pub enum TokenType { } impl TokenType { - pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<(), Exceptions> { + pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<()> { // let token = &self.tokens[self.current_pointer]; match self { TokenType::Simple(a) => a.appendTo(bit_array, text), diff --git a/src/binarizer.rs b/src/binarizer.rs index 60e372e..7d73c46 100644 --- a/src/binarizer.rs +++ b/src/binarizer.rs @@ -19,8 +19,8 @@ use std::{borrow::Cow, rc::Rc}; use crate::{ - common::{BitArray, BitMatrix}, - Exceptions, LuminanceSource, + common::{BitArray, BitMatrix, Result}, + LuminanceSource, }; /** @@ -51,7 +51,7 @@ pub trait Binarizer { * @return The array of bits for this row (true means black). * @throws NotFoundException if row can't be binarized */ - fn getBlackRow(&self, y: usize) -> Result, Exceptions>; + fn getBlackRow(&self, y: usize) -> Result>; /** * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive @@ -62,7 +62,7 @@ pub trait Binarizer { * @return The 2D array of bits for the image (true means black). * @throws NotFoundException if image can't be binarized to make a matrix */ - fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions>; + fn getBlackMatrix(&self) -> Result<&BitMatrix>; /** * Creates a new object with the same type as this Binarizer implementation, but with pristine diff --git a/src/binary_bitmap.rs b/src/binary_bitmap.rs index 2a737dc..4a9f7d4 100644 --- a/src/binary_bitmap.rs +++ b/src/binary_bitmap.rs @@ -19,8 +19,8 @@ use std::{borrow::Cow, fmt, rc::Rc}; use crate::{ - common::{BitArray, BitMatrix}, - Binarizer, Exceptions, + common::{BitArray, BitMatrix, Result}, + Binarizer, }; /** @@ -68,7 +68,7 @@ impl BinaryBitmap { * @return The array of bits for this row (true means black). * @throws NotFoundException if row can't be binarized */ - pub fn getBlackRow(&self, y: usize) -> Result, Exceptions> { + pub fn getBlackRow(&self, y: usize) -> Result> { self.binarizer.getBlackRow(y) } diff --git a/src/buffered_image_luminance_source.rs b/src/buffered_image_luminance_source.rs index 15851c3..585ebfc 100644 --- a/src/buffered_image_luminance_source.rs +++ b/src/buffered_image_luminance_source.rs @@ -19,6 +19,7 @@ use std::rc::Rc; use image::{DynamicImage, ImageBuffer, Luma}; use imageproc::geometric_transformations::rotate_about_center; +use crate::common::Result; use crate::LuminanceSource; // const MINUS_45_IN_RADIANS: f32 = -0.7853981633974483; // Math.toRadians(-45.0) @@ -164,7 +165,7 @@ impl LuminanceSource for BufferedImageLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, crate::exceptions::Exceptions> { + ) -> Result> { Ok(Box::new(Self { image: self.image.clone(), width, @@ -178,9 +179,7 @@ impl LuminanceSource for BufferedImageLuminanceSource { true } - fn rotateCounterClockwise( - &self, - ) -> Result, crate::exceptions::Exceptions> { + fn rotateCounterClockwise(&self) -> Result> { let img = self.image.rotate270(); Ok(Box::new(Self { width: img.width() as usize, @@ -191,9 +190,7 @@ impl LuminanceSource for BufferedImageLuminanceSource { })) } - fn rotateCounterClockwise45( - &self, - ) -> Result, crate::exceptions::Exceptions> { + fn rotateCounterClockwise45(&self) -> Result> { let img = rotate_about_center( &self.image.to_luma8(), MINUS_45_IN_RADIANS, diff --git a/src/client/result/AddressBookParsedResult.rs b/src/client/result/AddressBookParsedResult.rs index cfcaffe..fd71bd1 100644 --- a/src/client/result/AddressBookParsedResult.rs +++ b/src/client/result/AddressBookParsedResult.rs @@ -16,6 +16,7 @@ // package com.google.zxing.client.result; +use crate::common::Result; use crate::exceptions::Exceptions; use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser}; @@ -79,7 +80,7 @@ impl AddressBookParsedRXingResult { email_types: Vec, addresses: Vec, address_types: Vec, - ) -> Result { + ) -> Result { Self::with_details( names, Vec::new(), @@ -118,7 +119,7 @@ impl AddressBookParsedRXingResult { title: String, urls: Vec, geo: Vec, - ) -> Result { + ) -> Result { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { return Err(Exceptions::IllegalArgumentException(Some( "Phone numbers and types lengths differ".to_owned(), diff --git a/src/client/result/CalendarParsedResult.rs b/src/client/result/CalendarParsedResult.rs index 5363b52..cc50f4f 100644 --- a/src/client/result/CalendarParsedResult.rs +++ b/src/client/result/CalendarParsedResult.rs @@ -32,6 +32,7 @@ use chrono_tz::Tz; use once_cell::sync::Lazy; use regex::Regex; +use crate::common::Result; use crate::exceptions::Exceptions; use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType}; @@ -109,7 +110,7 @@ impl CalendarParsedRXingResult { description: String, latitude: f64, longitude: f64, - ) -> Result { + ) -> Result { let start = Self::parseDate(startString.clone())?; let end = if endString.is_empty() { let durationMS = Self::parseDurationMS(&durationString)?; @@ -164,7 +165,7 @@ impl CalendarParsedRXingResult { * @param when The string to parse * @throws ParseException if not able to parse as a date */ - fn parseDate(when: String) -> Result { + fn parseDate(when: String) -> Result { if !DATE_TIME.is_match(&when) { return Err(Exceptions::ParseException(Some(when))); } @@ -243,7 +244,7 @@ impl CalendarParsedRXingResult { } } - fn parseDurationMS(durationString: &str) -> Result { + fn parseDurationMS(durationString: &str) -> Result { if durationString.is_empty() { return Ok(-1); } @@ -279,7 +280,7 @@ impl CalendarParsedRXingResult { // return durationMS; } - fn parseDateTimeString(dateTimeString: &str) -> Result { + fn parseDateTimeString(dateTimeString: &str) -> Result { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { Ok(dtm.timestamp()) } else { diff --git a/src/client/result/ResultParser.rs b/src/client/result/ResultParser.rs index 26880da..eb84d2a 100644 --- a/src/client/result/ResultParser.rs +++ b/src/client/result/ResultParser.rs @@ -33,7 +33,7 @@ use urlencoding::decode; use once_cell::sync::Lazy; -use crate::{exceptions::Exceptions, RXingResult}; +use crate::{common::Result, exceptions::Exceptions, RXingResult}; use super::{ AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser, @@ -296,7 +296,7 @@ pub fn appendKeyValue(keyValue: &str, result: &mut HashMap) { // } } -pub fn urlDecode(encoded: &str) -> Result { +pub fn urlDecode(encoded: &str) -> Result { if let Ok(decoded) = decode(encoded) { Ok(decoded.to_string()) } else { diff --git a/src/client/result/VINResultParser.rs b/src/client/result/VINResultParser.rs index f35493d..e6feafa 100644 --- a/src/client/result/VINResultParser.rs +++ b/src/client/result/VINResultParser.rs @@ -17,7 +17,8 @@ use regex::Regex; use crate::{ - client::result::VINParsedRXingResult, exceptions::Exceptions, BarcodeFormat, RXingResult, + client::result::VINParsedRXingResult, common::Result, exceptions::Exceptions, BarcodeFormat, + RXingResult, }; use super::ParsedClientResult; @@ -67,7 +68,7 @@ pub fn parse(result: &RXingResult) -> Option { const IOQ: &str = "[IOQ]"; const AZ09: &str = "[A-Z0-9]{17}"; -fn check_checksum(vin: &str) -> Result { +fn check_checksum(vin: &str) -> Result { let mut sum = 0; for i in 0..vin.len() { sum += vin_position_weight(i + 1)? as u32 @@ -85,7 +86,7 @@ fn check_checksum(vin: &str) -> Result { Ok(check_to_char == expected_check_char) } -fn vin_char_value(c: char) -> Result { +fn vin_char_value(c: char) -> Result { match c { 'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1), 'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1), @@ -97,7 +98,7 @@ fn vin_char_value(c: char) -> Result { } } -fn vin_position_weight(position: usize) -> Result { +fn vin_position_weight(position: usize) -> Result { match position { 1..=7 => Ok(9 - position), 8 => Ok(10), @@ -109,7 +110,7 @@ fn vin_position_weight(position: usize) -> Result { } } -fn check_char(remainder: u8) -> Result { +fn check_char(remainder: u8) -> Result { match remainder { 0..=9 => Ok((b'0' + remainder) as char), 10 => Ok('X'), @@ -119,7 +120,7 @@ fn check_char(remainder: u8) -> Result { } } -fn model_year(c: char) -> Result { +fn model_year(c: char) -> Result { match c { 'E'..='H' => Ok((c as u8 as u32 - b'E' as u32) + 1984), 'J'..='N' => Ok((c as u8 as u32 - b'J' as u32) + 1988), diff --git a/src/common/bit_array.rs b/src/common/bit_array.rs index 9466a6a..d20f59e 100644 --- a/src/common/bit_array.rs +++ b/src/common/bit_array.rs @@ -20,6 +20,7 @@ use std::{cmp, fmt}; +use crate::common::Result; use crate::Exceptions; static LOAD_FACTOR: f32 = 0.75f32; @@ -165,7 +166,7 @@ impl BitArray { * @param start start of range, inclusive. * @param end end of range, exclusive */ - pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { + pub fn setRange(&mut self, start: usize, end: usize) -> Result<()> { let mut end = end; if end < start || end > self.size { return Err(Exceptions::IllegalArgumentException(None)); @@ -208,7 +209,7 @@ impl BitArray { * @return true iff all bits are set or not set in range, according to value argument * @throws IllegalArgumentException if end is less than start or the range is not contained in the array */ - pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result { + 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)); @@ -251,7 +252,7 @@ impl BitArray { * @param value {@code int} containing bits to append * @param numBits bits from value to append */ - pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { + pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<()> { if num_bits > 32 { return Err(Exceptions::IllegalArgumentException(Some( "num bits must be between 0 and 32".to_owned(), @@ -284,7 +285,7 @@ impl BitArray { } } - pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { + pub fn xor(&mut self, other: &BitArray) -> Result<()> { if self.size != other.size { return Err(Exceptions::IllegalArgumentException(Some( "Sizes don't match".to_owned(), diff --git a/src/common/bit_matrix.rs b/src/common/bit_matrix.rs index 5bda954..3e734c7 100644 --- a/src/common/bit_matrix.rs +++ b/src/common/bit_matrix.rs @@ -20,6 +20,7 @@ use std::fmt; +use crate::common::Result; use crate::{Exceptions, RXingResultPoint}; use super::BitArray; @@ -53,7 +54,7 @@ impl BitMatrix { * * @param dimension height and width */ - pub fn with_single_dimension(dimension: u32) -> Result { + pub fn with_single_dimension(dimension: u32) -> Result { Self::new(dimension, dimension) } @@ -63,7 +64,7 @@ impl BitMatrix { * @param width bit matrix width * @param height bit matrix height */ - pub fn new(width: u32, height: u32) -> Result { + pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { return Err(Exceptions::IllegalArgumentException(Some( "Both dimensions must be greater than 0".to_owned(), @@ -120,7 +121,7 @@ impl BitMatrix { string_representation: &str, set_string: &str, unset_string: &str, - ) -> Result { + ) -> Result { // cannot pass nulls in rust // if (stringRepresentation == null) { // throw new IllegalArgumentException(); @@ -308,7 +309,7 @@ impl BitMatrix { * * @param mask XOR mask */ - pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { + pub fn xor(&mut self, mask: &BitMatrix) -> Result<()> { if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size { return Err(Exceptions::IllegalArgumentException(Some( @@ -350,13 +351,7 @@ impl BitMatrix { * @param width The width of the region * @param height The height of the region */ - pub fn setRegion( - &mut self, - left: u32, - top: u32, - width: u32, - height: u32, - ) -> Result<(), Exceptions> { + pub fn setRegion(&mut self, left: u32, top: u32, width: u32, height: u32) -> Result<()> { // if top < 0 || left < 0 { // return Err(Exceptions::IllegalArgumentException( // "Left and top must be nonnegative".to_owned(), @@ -428,7 +423,7 @@ impl BitMatrix { * * @param degrees number of degrees to rotate through counter-clockwise (0, 90, 180, 270) */ - pub fn rotate(&mut self, degrees: u32) -> Result<(), Exceptions> { + pub fn rotate(&mut self, degrees: u32) -> Result<()> { match degrees % 360 { 0 => Ok(()), 90 => { diff --git a/src/common/bit_source.rs b/src/common/bit_source.rs index 1c64f84..968329e 100644 --- a/src/common/bit_source.rs +++ b/src/common/bit_source.rs @@ -18,6 +18,7 @@ use std::cmp; +use crate::common::Result; use crate::Exceptions; /** @@ -68,7 +69,7 @@ impl BitSource { * bits of the int * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available */ - pub fn readBits(&mut self, numBits: usize) -> Result { + pub fn readBits(&mut self, numBits: usize) -> Result { if !(1..=32).contains(&numBits) || numBits > self.available() { return Err(Exceptions::IllegalArgumentException(Some( numBits.to_string(), diff --git a/src/common/character_set_eci.rs b/src/common/character_set_eci.rs index 6276b46..87a149c 100644 --- a/src/common/character_set_eci.rs +++ b/src/common/character_set_eci.rs @@ -25,6 +25,7 @@ use encoding::EncodingRef; +use crate::common::Result; use crate::Exceptions; /** @@ -215,7 +216,7 @@ impl CharacterSetECI { * unsupported * @throws FormatException if ECI value is invalid */ - pub fn getCharacterSetECIByValue(value: u32) -> Result { + pub fn getCharacterSetECIByValue(value: u32) -> Result { match value { 0 | 2 => Ok(CharacterSetECI::Cp437), 1 | 3 => Ok(CharacterSetECI::ISO8859_1), diff --git a/src/common/default_grid_sampler.rs b/src/common/default_grid_sampler.rs index a4013e2..fd77a35 100644 --- a/src/common/default_grid_sampler.rs +++ b/src/common/default_grid_sampler.rs @@ -18,6 +18,7 @@ // import com.google.zxing.NotFoundException; +use crate::common::Result; use crate::Exceptions; use super::{BitMatrix, GridSampler, PerspectiveTransform}; @@ -50,7 +51,7 @@ impl GridSampler for DefaultGridSampler { p3FromY: f32, p4FromX: f32, p4FromY: f32, - ) -> Result { + ) -> Result { let transform = PerspectiveTransform::quadrilateralToQuadrilateral( p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY, @@ -65,7 +66,7 @@ impl GridSampler for DefaultGridSampler { dimensionX: u32, dimensionY: u32, transform: &PerspectiveTransform, - ) -> Result { + ) -> Result { if dimensionX == 0 || dimensionY == 0 { return Err(Exceptions::NotFoundException(None)); } diff --git a/src/common/detector/monochrome_rectangle_detector.rs b/src/common/detector/monochrome_rectangle_detector.rs index 640af79..16d297d 100644 --- a/src/common/detector/monochrome_rectangle_detector.rs +++ b/src/common/detector/monochrome_rectangle_detector.rs @@ -17,7 +17,10 @@ //package com.google.zxing.common.detector; -use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, RXingResultPoint, ResultPoint, +}; /** *

A somewhat generic detector that looks for a barcode-like rectangular region within an image. @@ -48,7 +51,7 @@ impl<'a> MonochromeRectangleDetector<'_> { * third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ - pub fn detect(&self) -> Result<[RXingResultPoint; 4], Exceptions> { + pub fn detect(&self) -> Result<[RXingResultPoint; 4]> { let height = self.image.getHeight() as i32; let width = self.image.getWidth() as i32; let halfHeight = height / 2; @@ -155,7 +158,7 @@ impl<'a> MonochromeRectangleDetector<'_> { top: i32, bottom: i32, maxWhiteRun: i32, - ) -> Result { + ) -> Result { let mut lastRange_z: Option<[i32; 2]> = None; let mut y: i32 = centerY; let mut x: i32 = centerX; diff --git a/src/common/detector/white_rectangle_detector.rs b/src/common/detector/white_rectangle_detector.rs index eaef17a..23782be 100644 --- a/src/common/detector/white_rectangle_detector.rs +++ b/src/common/detector/white_rectangle_detector.rs @@ -16,7 +16,10 @@ //package com.google.zxing.common.detector; -use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, RXingResultPoint, ResultPoint, +}; use super::MathUtils; @@ -43,7 +46,7 @@ pub struct WhiteRectangleDetector<'a> { } impl<'a> WhiteRectangleDetector<'_> { - pub fn new_from_image(image: &'a BitMatrix) -> Result, Exceptions> { + pub fn new_from_image(image: &'a BitMatrix) -> Result> { WhiteRectangleDetector::new( image, INIT_SIZE, @@ -64,7 +67,7 @@ impl<'a> WhiteRectangleDetector<'_> { initSize: i32, x: i32, y: i32, - ) -> Result, Exceptions> { + ) -> Result> { let halfsize = initSize / 2; let leftInit = x - halfsize; @@ -105,7 +108,7 @@ impl<'a> WhiteRectangleDetector<'_> { * leftmost and the third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ - pub fn detect(&self) -> Result<[RXingResultPoint; 4], Exceptions> { + pub fn detect(&self) -> Result<[RXingResultPoint; 4]> { let mut left: i32 = self.leftInit; let mut right: i32 = self.rightInit; let mut up: i32 = self.upInit; diff --git a/src/common/eci_input.rs b/src/common/eci_input.rs index 6592dab..8e9e773 100644 --- a/src/common/eci_input.rs +++ b/src/common/eci_input.rs @@ -18,7 +18,7 @@ use std::fmt::Display; -use crate::Exceptions; +use crate::common::Result; /** * Interface to navigate a sequence of ECIs and bytes. @@ -50,7 +50,7 @@ pub trait ECIInput: Display { * @throws IllegalArgumentException * if the value at the {@code index} argument is an ECI (@see #isECI) */ - fn charAt(&self, index: usize) -> Result; + fn charAt(&self, index: usize) -> Result; /** * Returns a {@code CharSequence} that is a subsequence of this sequence. @@ -72,7 +72,7 @@ pub trait ECIInput: Display { * @throws IllegalArgumentException * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI) */ - fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions>; + fn subSequence(&self, start: usize, end: usize) -> Result>; /** * Determines if a value is an ECI @@ -85,7 +85,7 @@ pub trait ECIInput: Display { * if the {@code index} argument is negative or not less than * {@code length()} */ - fn isECI(&self, index: u32) -> Result; + fn isECI(&self, index: u32) -> Result; /** * Returns the {@code int} ECI value at the specified index. An index ranges from zero @@ -105,6 +105,6 @@ pub trait ECIInput: Display { * @throws IllegalArgumentException * if the value at the {@code index} argument is not an ECI (@see #isECI) */ - fn getECIValue(&self, index: usize) -> Result; - fn haveNCharacters(&self, index: usize, n: usize) -> Result; + fn getECIValue(&self, index: usize) -> Result; + fn haveNCharacters(&self, index: usize, n: usize) -> Result; } diff --git a/src/common/eci_string_builder.rs b/src/common/eci_string_builder.rs index 1ccc3e6..7f338a8 100644 --- a/src/common/eci_string_builder.rs +++ b/src/common/eci_string_builder.rs @@ -25,7 +25,7 @@ use std::fmt; use encoding::{Encoding, EncodingRef}; -use crate::Exceptions; +use crate::common::Result; use super::CharacterSetECI; @@ -103,7 +103,7 @@ impl ECIStringBuilder { * @param value ECI value to append, as an int * @throws FormatException on invalid ECI value */ - pub fn appendECI(&mut self, value: u32) -> Result<(), Exceptions> { + pub fn appendECI(&mut self, value: u32) -> Result<()> { self.encodeCurrentBytesIfAny(); if let Ok(character_set_eci) = CharacterSetECI::getCharacterSetECIByValue(value) { diff --git a/src/common/global_histogram_binarizer.rs b/src/common/global_histogram_binarizer.rs index b0839a4..a8757ba 100644 --- a/src/common/global_histogram_binarizer.rs +++ b/src/common/global_histogram_binarizer.rs @@ -24,6 +24,7 @@ use std::{borrow::Cow, rc::Rc}; use once_cell::unsync::OnceCell; +use crate::common::Result; use crate::{Binarizer, Exceptions, LuminanceSource}; use super::{BitArray, BitMatrix}; @@ -54,7 +55,7 @@ impl Binarizer for GlobalHistogramBinarizer { } // Applies simple sharpening to the row data to improve performance of the 1D Readers. - fn getBlackRow(&self, y: usize) -> Result, Exceptions> { + fn getBlackRow(&self, y: usize) -> Result> { let row = self.black_row_cache[y].get_or_try_init(|| { let source = self.getLuminanceSource(); let width = source.getWidth(); @@ -101,7 +102,7 @@ impl Binarizer for GlobalHistogramBinarizer { } // Does not sharpen the data, as this call is intended to only be used by 2D Readers. - fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> { + fn getBlackMatrix(&self) -> Result<&BitMatrix> { let matrix = self .black_matrix .get_or_try_init(|| Self::build_black_matrix(&self.source))?; @@ -138,7 +139,7 @@ impl GlobalHistogramBinarizer { } } - fn build_black_matrix(source: &Box) -> Result { + fn build_black_matrix(source: &Box) -> Result { // let source = source.getLuminanceSource(); let width = source.getWidth(); let height = source.getHeight(); @@ -192,7 +193,7 @@ impl GlobalHistogramBinarizer { // // } // } - fn estimateBlackPoint(buckets: &[u32]) -> Result { + fn estimateBlackPoint(buckets: &[u32]) -> Result { // Find the tallest peak in the histogram. let numBuckets = buckets.len(); let mut maxBucketCount = 0; diff --git a/src/common/grid_sampler.rs b/src/common/grid_sampler.rs index b015e59..9bf7f47 100644 --- a/src/common/grid_sampler.rs +++ b/src/common/grid_sampler.rs @@ -18,6 +18,7 @@ // import com.google.zxing.NotFoundException; +use crate::common::Result; use crate::Exceptions; use super::{BitMatrix, PerspectiveTransform}; @@ -108,7 +109,7 @@ pub trait GridSampler { p3FromY: f32, p4FromX: f32, p4FromY: f32, - ) -> Result; + ) -> Result; fn sample_grid( &self, @@ -116,7 +117,7 @@ pub trait GridSampler { dimensionX: u32, dimensionY: u32, transform: &PerspectiveTransform, - ) -> Result; + ) -> Result; /** *

Checks a set of points that have been transformed to sample points on an image against @@ -133,7 +134,7 @@ pub trait GridSampler { * @param points actual points in x1,y1,...,xn,yn form * @throws NotFoundException if an endpoint is lies outside the image boundaries */ - fn checkAndNudgePoints(&self, image: &BitMatrix, points: &mut [f32]) -> Result<(), Exceptions> { + fn checkAndNudgePoints(&self, image: &BitMatrix, points: &mut [f32]) -> Result<()> { let width = image.getWidth(); let height = image.getHeight(); // Check and nudge points from start until we see some that are OK: diff --git a/src/common/hybrid_binarizer.rs b/src/common/hybrid_binarizer.rs index ff86589..48f62e3 100644 --- a/src/common/hybrid_binarizer.rs +++ b/src/common/hybrid_binarizer.rs @@ -24,7 +24,8 @@ use std::{borrow::Cow, rc::Rc}; use once_cell::unsync::OnceCell; -use crate::{Binarizer, Exceptions, LuminanceSource}; +use crate::common::Result; +use crate::{Binarizer, LuminanceSource}; use super::{BitArray, BitMatrix, GlobalHistogramBinarizer}; @@ -57,7 +58,7 @@ impl Binarizer for HybridBinarizer { self.ghb.getLuminanceSource() } - fn getBlackRow(&self, y: usize) -> Result, Exceptions> { + fn getBlackRow(&self, y: usize) -> Result> { self.ghb.getBlackRow(y) } @@ -66,7 +67,7 @@ impl Binarizer for HybridBinarizer { * constructor instead, but there are some advantages to doing it lazily, such as making * profiling easier, and not doing heavy lifting when callers don't expect it. */ - fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> { + fn getBlackMatrix(&self) -> Result<&BitMatrix> { let matrix = self .black_matrix .get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?; @@ -102,7 +103,7 @@ impl HybridBinarizer { } } - fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result { + fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result { // let matrix; let source = ghb.getLuminanceSource(); let width = source.getWidth(); diff --git a/src/common/minimal_eci_input.rs b/src/common/minimal_eci_input.rs index cd21d34..1acbef9 100644 --- a/src/common/minimal_eci_input.rs +++ b/src/common/minimal_eci_input.rs @@ -19,6 +19,7 @@ use std::{fmt, rc::Rc}; use encoding::EncodingRef; use unicode_segmentation::UnicodeSegmentation; +use crate::common::Result; use crate::Exceptions; use super::{ECIEncoderSet, ECIInput}; @@ -65,7 +66,7 @@ impl ECIInput for MinimalECIInput { * @throws IllegalArgumentException * if the value at the {@code index} argument is an ECI (@see #isECI) */ - fn charAt(&self, index: usize) -> Result { + fn charAt(&self, index: usize) -> Result { if index >= self.length() { return Err(Exceptions::IndexOutOfBoundsException(Some( index.to_string(), @@ -103,7 +104,7 @@ impl ECIInput for MinimalECIInput { * @throws IllegalArgumentException * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI) */ - fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { + fn subSequence(&self, start: usize, end: usize) -> Result> { if start > end || end > self.length() { return Err(Exceptions::IndexOutOfBoundsException(None)); } @@ -131,7 +132,7 @@ impl ECIInput for MinimalECIInput { * if the {@code index} argument is negative or not less than * {@code length()} */ - fn isECI(&self, index: u32) -> Result { + fn isECI(&self, index: u32) -> Result { if index >= self.length() as u32 { return Err(Exceptions::IndexOutOfBoundsException(None)); } @@ -156,7 +157,7 @@ impl ECIInput for MinimalECIInput { * @throws IllegalArgumentException * if the value at the {@code index} argument is not an ECI (@see #isECI) */ - fn getECIValue(&self, index: usize) -> Result { + fn getECIValue(&self, index: usize) -> Result { if index >= self.length() { return Err(Exceptions::IndexOutOfBoundsException(None)); } @@ -168,7 +169,7 @@ impl ECIInput for MinimalECIInput { Ok((self.bytes[index] as u32 - 256) as i32) } - fn haveNCharacters(&self, index: usize, n: usize) -> Result { + fn haveNCharacters(&self, index: usize, n: usize) -> Result { if index + n > self.bytes.len() { return Ok(false); } @@ -248,7 +249,7 @@ impl MinimalECIInput { * if the {@code index} argument is negative or not less than * {@code length()} */ - pub fn isFNC1(&self, index: usize) -> Result { + pub fn isFNC1(&self, index: usize) -> Result { if index >= self.length() { return Err(Exceptions::IndexOutOfBoundsException(None)); } diff --git a/src/common/mod.rs b/src/common/mod.rs index ae20d58..4b3b080 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -24,6 +24,8 @@ pub use string_utils::*; mod bit_array; pub use bit_array::*; +pub type Result = std::result::Result; + /* * Copyright 2007 ZXing authors * diff --git a/src/common/otsu_level_binarizer.rs b/src/common/otsu_level_binarizer.rs index b6ac08c..35757ac 100644 --- a/src/common/otsu_level_binarizer.rs +++ b/src/common/otsu_level_binarizer.rs @@ -3,6 +3,7 @@ use std::{borrow::Cow, rc::Rc}; use image::{DynamicImage, ImageBuffer, Luma}; use once_cell::sync::OnceCell; +use crate::common::Result; use crate::{Binarizer, Exceptions, LuminanceSource}; use super::{BitArray, BitMatrix}; @@ -16,7 +17,7 @@ pub struct OtsuLevelBinarizer { } impl OtsuLevelBinarizer { - fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result { + 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)) @@ -49,10 +50,7 @@ impl Binarizer for OtsuLevelBinarizer { &self.source } - fn getBlackRow( - &self, - y: usize, - ) -> Result, crate::Exceptions> { + fn getBlackRow(&self, y: usize) -> Result> { let row = self.black_row_cache[y].get_or_try_init(|| { let matrix = self.getBlackMatrix()?; Ok(matrix.getRow(y as u32)) @@ -61,7 +59,7 @@ impl Binarizer for OtsuLevelBinarizer { Ok(Cow::Borrowed(row)) } - fn getBlackMatrix(&self) -> Result<&super::BitMatrix, crate::Exceptions> { + fn getBlackMatrix(&self) -> Result<&super::BitMatrix> { let matrix = self .black_matrix .get_or_try_init(|| Self::generate_threshold_matrix(self.source.as_ref()))?; diff --git a/src/common/reedsolomon/generic_gf.rs b/src/common/reedsolomon/generic_gf.rs index 576c2f5..1759ab7 100644 --- a/src/common/reedsolomon/generic_gf.rs +++ b/src/common/reedsolomon/generic_gf.rs @@ -1,5 +1,6 @@ use std::fmt; +use crate::common::Result; use crate::Exceptions; use super::{GenericGFPoly, GenericGFRef}; @@ -131,7 +132,7 @@ impl GenericGF { /** * @return base 2 log of a in GF(size) */ - pub fn log(&self, a: i32) -> Result { + pub fn log(&self, a: i32) -> Result { if a == 0 { return Err(Exceptions::IllegalArgumentException(None)); } @@ -142,7 +143,7 @@ impl GenericGF { /** * @return multiplicative inverse of a */ - pub fn inverse(&self, a: i32) -> Result { + pub fn inverse(&self, a: i32) -> Result { if a == 0 { return Err(Exceptions::ArithmeticException(None)); } diff --git a/src/common/reedsolomon/generic_gf_poly.rs b/src/common/reedsolomon/generic_gf_poly.rs index 26041fe..1583ea7 100644 --- a/src/common/reedsolomon/generic_gf_poly.rs +++ b/src/common/reedsolomon/generic_gf_poly.rs @@ -18,6 +18,7 @@ use std::fmt; +use crate::common::Result; use crate::Exceptions; use super::{GenericGF, GenericGFRef}; @@ -47,7 +48,7 @@ impl GenericGFPoly { * or if leading coefficient is 0 and this is not a * constant polynomial (that is, it is not the monomial "0") */ - pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { + pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result { if coefficients.is_empty() { return Err(Exceptions::IllegalArgumentException(Some(String::from( "coefficients cannot be empty", @@ -138,7 +139,7 @@ impl GenericGFPoly { result } - pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { + pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { return Err(Exceptions::IllegalArgumentException(Some( "GenericGFPolys do not have same GenericGF field".to_owned(), @@ -174,7 +175,7 @@ impl GenericGFPoly { GenericGFPoly::new(self.field, &sumDiff) } - pub fn multiply(&self, other: &GenericGFPoly) -> Result { + pub fn multiply(&self, other: &GenericGFPoly) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { return Err(Exceptions::IllegalArgumentException(Some( @@ -229,11 +230,7 @@ impl GenericGFPoly { GenericGFPoly::new(self.field, &[1]).unwrap() } - pub fn multiply_by_monomial( - &self, - degree: usize, - coefficient: i32, - ) -> Result { + pub fn multiply_by_monomial(&self, degree: usize, coefficient: i32) -> Result { if coefficient == 0 { return Ok(self.getZero()); } @@ -247,10 +244,7 @@ impl GenericGFPoly { GenericGFPoly::new(self.field, &product) } - pub fn divide( - &self, - other: &GenericGFPoly, - ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { + pub fn divide(&self, other: &GenericGFPoly) -> Result<(GenericGFPoly, GenericGFPoly)> { if self.field != other.field { return Err(Exceptions::IllegalArgumentException(Some( "GenericGFPolys do not have same GenericGF field".to_owned(), diff --git a/src/common/reedsolomon/reedsolomon_decoder.rs b/src/common/reedsolomon/reedsolomon_decoder.rs index 6f62140..354f7fd 100644 --- a/src/common/reedsolomon/reedsolomon_decoder.rs +++ b/src/common/reedsolomon/reedsolomon_decoder.rs @@ -16,6 +16,7 @@ //package com.google.zxing.common.reedsolomon; +use crate::common::Result; use crate::Exceptions; use super::{GenericGF, GenericGFPoly, GenericGFRef}; @@ -60,7 +61,7 @@ impl ReedSolomonDecoder { * @param twoS number of error-correction codewords available * @throws ReedSolomonException if decoding fails for any reason */ - pub fn decode(&self, received: &mut Vec, twoS: i32) -> Result { + pub fn decode(&self, received: &mut Vec, twoS: i32) -> Result { let poly = GenericGFPoly::new(self.field, received)?; let mut syndromeCoefficients = vec![0; twoS as usize]; let mut noError = true; @@ -113,7 +114,7 @@ impl ReedSolomonDecoder { a: &GenericGFPoly, b: &GenericGFPoly, R: usize, - ) -> Result, Exceptions> { + ) -> Result> { // Assume a's degree is >= b's let mut a = a.clone(); let mut b = b.clone(); @@ -184,7 +185,7 @@ impl ReedSolomonDecoder { Ok(vec![sigma, omega]) } - fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result, Exceptions> { + fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result> { // This is a direct application of Chien's search let numErrors = errorLocator.getDegree(); if numErrors == 1 { @@ -216,7 +217,7 @@ impl ReedSolomonDecoder { &self, errorEvaluator: &GenericGFPoly, errorLocations: &Vec, - ) -> Result, Exceptions> { + ) -> Result> { // This is directly applying Forney's Formula let s = errorLocations.len(); let mut result = vec![0; s]; diff --git a/src/common/reedsolomon/reedsolomon_encoder.rs b/src/common/reedsolomon/reedsolomon_encoder.rs index f155a60..097caba 100644 --- a/src/common/reedsolomon/reedsolomon_encoder.rs +++ b/src/common/reedsolomon/reedsolomon_encoder.rs @@ -19,6 +19,7 @@ //import java.util.ArrayList; //import java.util.List; +use crate::common::Result; use crate::Exceptions; use super::{GenericGFPoly, GenericGFRef}; @@ -35,7 +36,7 @@ pub struct ReedSolomonEncoder { } impl ReedSolomonEncoder { - pub fn new(field: GenericGFRef) -> Result { + pub fn new(field: GenericGFRef) -> Result { let n = field; Ok(Self { cachedGenerators: vec![GenericGFPoly::new(n, &[1])?], @@ -71,7 +72,7 @@ impl ReedSolomonEncoder { Some(rv) } - pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<(), Exceptions> { + pub fn encode(&mut self, to_encode: &mut Vec, ec_bytes: usize) -> Result<()> { if ec_bytes == 0 { return Err(Exceptions::IllegalArgumentException(Some( "No error correction bytes".to_owned(), diff --git a/src/datamatrix/data_matrix_reader.rs b/src/datamatrix/data_matrix_reader.rs index 5e24893..9a9adf2 100644 --- a/src/datamatrix/data_matrix_reader.rs +++ b/src/datamatrix/data_matrix_reader.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use crate::{ - common::{BitMatrix, DecoderRXingResult, DetectorRXingResult}, + common::{BitMatrix, DecoderRXingResult, DetectorRXingResult, Result}, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, Reader, }; @@ -52,10 +52,7 @@ impl Reader for DataMatrixReader { * @throws FormatException if a Data Matrix code cannot be decoded * @throws ChecksumException if error correction fails */ - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -71,7 +68,7 @@ impl Reader for DataMatrixReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let try_harder = matches!( hints.get(&DecodeHintType::TRY_HARDER), Some(DecodeHintValue::TryHarder(true)) @@ -84,7 +81,7 @@ impl Reader for DataMatrixReader { points.clear(); } else { //Result - decoderRXingResult = if let Ok(fnd) = || -> Result { + decoderRXingResult = if let Ok(fnd) = || -> Result { let detectorRXingResult = zxing_cpp_detector::detect(image.getBlackMatrix(), try_harder, true)?; let decoded = DECODER.decode(detectorRXingResult.getBits())?; @@ -93,7 +90,7 @@ impl Reader for DataMatrixReader { }() { fnd } else if try_harder { - if let Ok(fnd) = || -> Result { + if let Ok(fnd) = || -> Result { let detectorRXingResult = Detector::new(image.getBlackMatrix())?.detect()?; let decoded = DECODER.decode(detectorRXingResult.getBits())?; points = detectorRXingResult.getPoints().to_vec(); @@ -179,7 +176,7 @@ impl DataMatrixReader { * around it. This is a specialized method that works exceptionally fast in this special * case. */ - fn extractPureBits(&self, image: &BitMatrix) -> Result { + fn extractPureBits(&self, image: &BitMatrix) -> Result { let Some(leftTopBlack) = image.getTopLeftOnBit() else { return Err(Exceptions::NotFoundException(None)) }; @@ -226,7 +223,7 @@ impl DataMatrixReader { Ok(bits) } - fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result { + fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result { let width = image.getWidth(); let mut x = leftTopBlack[0]; let y = leftTopBlack[1]; diff --git a/src/datamatrix/data_matrix_writer.rs b/src/datamatrix/data_matrix_writer.rs index 936caba..520ce2f 100644 --- a/src/datamatrix/data_matrix_writer.rs +++ b/src/datamatrix/data_matrix_writer.rs @@ -20,8 +20,9 @@ use std::collections::HashMap; use encoding::EncodingRef; use crate::{ - common::BitMatrix, qrcode::encoder::ByteMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, - Exceptions, Writer, + common::{BitMatrix, Result}, + qrcode::encoder::ByteMatrix, + BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, }; use super::encoder::{ @@ -47,7 +48,7 @@ impl Writer for DataMatrixWriter { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -58,7 +59,7 @@ impl Writer for DataMatrixWriter { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { if contents.is_empty() { return Err(Exceptions::IllegalArgumentException(Some( "Found empty contents".to_owned(), @@ -189,7 +190,7 @@ impl DataMatrixWriter { symbolInfo: &SymbolInfo, width: u32, height: u32, - ) -> Result { + ) -> Result { let symbolWidth = symbolInfo.getSymbolDataWidth()?; let symbolHeight = symbolInfo.getSymbolDataHeight()?; @@ -255,7 +256,7 @@ impl DataMatrixWriter { matrix: &ByteMatrix, reqWidth: u32, reqHeight: u32, - ) -> Result { + ) -> Result { let matrixWidth = matrix.getWidth(); let matrixHeight = matrix.getHeight(); let outputWidth = reqWidth.max(matrixWidth); diff --git a/src/datamatrix/decoder/bit_matrix_parser.rs b/src/datamatrix/decoder/bit_matrix_parser.rs index 478c935..44b26c8 100644 --- a/src/datamatrix/decoder/bit_matrix_parser.rs +++ b/src/datamatrix/decoder/bit_matrix_parser.rs @@ -14,7 +14,10 @@ * limitations under the License. */ -use crate::{common::BitMatrix, Exceptions}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, +}; use super::{Version, VersionRef}; @@ -31,7 +34,7 @@ impl BitMatrixParser { * @param bitMatrix {@link BitMatrix} to parse * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2 */ - pub fn new(bitMatrix: &BitMatrix) -> Result { + pub fn new(bitMatrix: &BitMatrix) -> Result { let dimension = bitMatrix.getHeight(); if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { return Err(Exceptions::FormatException(None)); @@ -64,7 +67,7 @@ impl BitMatrixParser { * @throws FormatException if the dimensions of the mapping matrix are not valid * Data Matrix dimensions. */ - fn readVersion(bitMatrix: &BitMatrix) -> Result { + fn readVersion(bitMatrix: &BitMatrix) -> Result { let numRows = bitMatrix.getHeight(); let numColumns = bitMatrix.getWidth(); Version::getVersionForDimensions(numRows, numColumns) @@ -78,7 +81,7 @@ impl BitMatrixParser { * @return bytes encoded within the Data Matrix Code * @throws FormatException if the exact number of bytes expected is not read */ - pub fn readCodewords(&mut self) -> Result, Exceptions> { + pub fn readCodewords(&mut self) -> Result> { let mut result = vec![0u8; self.version.getTotalCodewords() as usize]; let mut resultOffset = 0; @@ -447,10 +450,7 @@ impl BitMatrixParser { * @param bitMatrix Original {@link BitMatrix} with alignment patterns * @return BitMatrix that has the alignment patterns removed */ - fn extractDataRegion( - bitMatrix: &BitMatrix, - version: VersionRef, - ) -> Result { + fn extractDataRegion(bitMatrix: &BitMatrix, version: VersionRef) -> Result { // dbg!(bitMatrix.to_string()); let symbolSizeRows = version.getSymbolSizeRows(); let symbolSizeColumns = version.getSymbolSizeColumns(); diff --git a/src/datamatrix/decoder/data_block.rs b/src/datamatrix/decoder/data_block.rs index eeed3f3..c58d020 100644 --- a/src/datamatrix/decoder/data_block.rs +++ b/src/datamatrix/decoder/data_block.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::Version; @@ -52,7 +53,7 @@ impl DataBlock { rawCodewords: &[u8], version: &Version, fix259: bool, - ) -> Result, Exceptions> { + ) -> Result> { // Figure out the number and size of data blocks used by this version let ecBlocks = version.getECBlocks(); diff --git a/src/datamatrix/decoder/datamatrix_decoder.rs b/src/datamatrix/decoder/datamatrix_decoder.rs index b1f4eef..584fd2a 100644 --- a/src/datamatrix/decoder/datamatrix_decoder.rs +++ b/src/datamatrix/decoder/datamatrix_decoder.rs @@ -14,12 +14,9 @@ * limitations under the License. */ -use crate::{ - common::{ - reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder}, - BitMatrix, DecoderRXingResult, - }, - Exceptions, +use crate::common::{ + reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder}, + BitMatrix, DecoderRXingResult, Result, }; use super::{decoded_bit_stream_parser, BitMatrixParser, DataBlock}; @@ -49,7 +46,7 @@ impl Decoder { * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ - pub fn decode(&self, bits: &BitMatrix) -> Result { + pub fn decode(&self, bits: &BitMatrix) -> Result { let decoded = self.perform_decode(bits, false, false); if decoded.is_ok() { return decoded; @@ -58,7 +55,7 @@ impl Decoder { self.perform_decode(&Self::flip_bitmatrix(bits)?, false, true) } - fn flip_bitmatrix(bits: &BitMatrix) -> Result { + fn flip_bitmatrix(bits: &BitMatrix) -> Result { let mut res = BitMatrix::new(bits.getHeight(), bits.getWidth())?; for y in 0..res.getHeight() { for x in 0..res.getWidth() { @@ -84,7 +81,7 @@ impl Decoder { * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ - pub fn decode_bools(&self, image: &Vec>) -> Result { + pub fn decode_bools(&self, image: &Vec>) -> Result { self.perform_decode(&BitMatrix::parse_bools(image), false, false) } @@ -102,7 +99,7 @@ impl Decoder { bits: &BitMatrix, fix259: bool, is_flipped: bool, - ) -> Result { + ) -> Result { // Construct a parser and read version, error-correction level let mut parser = BitMatrixParser::new(bits)?; @@ -153,11 +150,7 @@ impl Decoder { * @param numDataCodewords number of codewords that are data bytes * @throws ChecksumException if error correction fails */ - fn correctErrors( - &self, - codewordBytes: &mut [u8], - numDataCodewords: u32, - ) -> Result<(), Exceptions> { + fn correctErrors(&self, codewordBytes: &mut [u8], numDataCodewords: u32) -> Result<()> { let _numCodewords = codewordBytes.len(); // First read into an array of ints // let codewordsInts = vec![0i32;numCodewords]; diff --git a/src/datamatrix/decoder/decoded_bit_stream_parser.rs b/src/datamatrix/decoder/decoded_bit_stream_parser.rs index ca1b5ee..f542575 100644 --- a/src/datamatrix/decoder/decoded_bit_stream_parser.rs +++ b/src/datamatrix/decoder/decoded_bit_stream_parser.rs @@ -17,7 +17,7 @@ use encoding::Encoding; use crate::{ - common::{BitSource, DecoderRXingResult, ECIStringBuilder}, + common::{BitSource, DecoderRXingResult, ECIStringBuilder, Result}, Exceptions, }; @@ -110,7 +110,7 @@ const INSERT_STRING_CONST: &str = "\u{001E}\u{0004}"; const VALUE_236: &str = "[)>\u{001E}05\u{001D}"; const VALUE_237: &str = "[)>\u{001E}06\u{001D}"; -pub fn decode(bytes: &[u8], is_flipped: bool) -> Result { +pub fn decode(bytes: &[u8], is_flipped: bool) -> Result { let mut bits = BitSource::new(bytes.to_vec()); let mut result = ECIStringBuilder::with_capacity(100); let mut resultTrailer = String::new(); @@ -217,7 +217,7 @@ fn decodeAsciiSegment( resultTrailer: &mut String, fnc1positions: &mut Vec, is_gs1: &mut bool, -) -> Result { +) -> Result { let mut upperShift = false; let mut firstFNC1Position = 1; let mut firstCodeword = true; @@ -353,7 +353,7 @@ fn decodeC40Segment( bits: &mut BitSource, result: &mut ECIStringBuilder, fnc1positions: &mut Vec, -) -> Result<(), Exceptions> { +) -> Result<()> { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time @@ -472,7 +472,7 @@ fn decodeTextSegment( bits: &mut BitSource, result: &mut ECIStringBuilder, fnc1positions: &mut Vec, -) -> Result<(), Exceptions> { +) -> Result<()> { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time @@ -592,10 +592,7 @@ fn decodeTextSegment( /** * See ISO 16022:2006, 5.2.7 */ -fn decodeAnsiX12Segment( - bits: &mut BitSource, - result: &mut ECIStringBuilder, -) -> Result<(), Exceptions> { +fn decodeAnsiX12Segment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<()> { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 @@ -679,10 +676,7 @@ fn parseTwoBytes(firstByte: u32, secondByte: u32, result: &mut [u32]) { /** * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 */ -fn decodeEdifactSegment( - bits: &mut BitSource, - result: &mut ECIStringBuilder, -) -> Result<(), Exceptions> { +fn decodeEdifactSegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<()> { loop { // If there is only two or less bytes left then it will be encoded as ASCII if bits.available() <= 16 { @@ -727,7 +721,7 @@ fn decodeBase256Segment( bits: &mut BitSource, result: &mut ECIStringBuilder, byteSegments: &mut Vec>, -) -> Result<(), Exceptions> { +) -> Result<()> { // Figure out how long the Base 256 Segment is. let mut codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed let d1 = unrandomize255State(bits.readBits(8)?, codewordPosition); @@ -772,10 +766,7 @@ fn decodeBase256Segment( /** * See ISO 16022:2007, 5.4.1 */ -fn decodeECISegment( - bits: &mut BitSource, - result: &mut ECIStringBuilder, -) -> Result { +fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result { let firstByte = bits.readBits(8)?; if firstByte <= 127 { result.appendECI(firstByte - 1)?; @@ -797,10 +788,7 @@ fn decodeECISegment( /** * See ISO 16022:2006, 5.6 */ -fn parse_structured_append( - bits: &mut BitSource, - sai: &mut StructuredAppendInfo, -) -> Result<(), Exceptions> { +fn parse_structured_append(bits: &mut BitSource, sai: &mut StructuredAppendInfo) -> Result<()> { // 5.6.2 Table 8 let symbolSequenceIndicator = bits.readBits(8)?; sai.index = (symbolSequenceIndicator >> 4) as i32; diff --git a/src/datamatrix/decoder/version.rs b/src/datamatrix/decoder/version.rs index 16b126c..2eb9b8f 100644 --- a/src/datamatrix/decoder/version.rs +++ b/src/datamatrix/decoder/version.rs @@ -17,6 +17,7 @@ use core::fmt; use once_cell::sync::Lazy; +use crate::common::Result; use crate::Exceptions; static VERSIONS: Lazy> = Lazy::new(Version::buildVersions); @@ -100,10 +101,7 @@ impl Version { * @return Version for a Data Matrix Code of those dimensions * @throws FormatException if dimensions do correspond to a valid Data Matrix size */ - pub fn getVersionForDimensions( - numRows: u32, - numColumns: u32, - ) -> Result<&'static Version, Exceptions> { + pub fn getVersionForDimensions(numRows: u32, numColumns: u32) -> Result<&'static Version> { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { return Err(Exceptions::FormatException(None)); } diff --git a/src/datamatrix/detector/datamatrix_detector.rs b/src/datamatrix/detector/datamatrix_detector.rs index 89e1f39..fca85d8 100644 --- a/src/datamatrix/detector/datamatrix_detector.rs +++ b/src/datamatrix/detector/datamatrix_detector.rs @@ -15,7 +15,9 @@ */ use crate::{ - common::{detector::WhiteRectangleDetector, BitMatrix, DefaultGridSampler, GridSampler}, + common::{ + detector::WhiteRectangleDetector, BitMatrix, DefaultGridSampler, GridSampler, Result, + }, Exceptions, RXingResultPoint, ResultPoint, }; @@ -32,7 +34,7 @@ pub struct Detector<'a> { rectangleDetector: WhiteRectangleDetector<'a>, } impl<'a> Detector<'_> { - pub fn new(image: &'a BitMatrix) -> Result, Exceptions> { + pub fn new(image: &'a BitMatrix) -> Result> { Ok(Detector { rectangleDetector: WhiteRectangleDetector::new_from_image(image)?, image, @@ -45,7 +47,7 @@ impl<'a> Detector<'_> { * @return {@link DetectorRXingResult} encapsulating results of detecting a Data Matrix Code * @throws NotFoundException if no Data Matrix Code can be found */ - pub fn detect(&self) -> Result { + pub fn detect(&self) -> Result { let cornerPoints = self.rectangleDetector.detect()?; let mut points = self.detectSolid1(cornerPoints); @@ -331,7 +333,7 @@ impl<'a> Detector<'_> { topRight: &RXingResultPoint, dimensionX: u32, dimensionY: u32, - ) -> Result { + ) -> Result { let sampler = DefaultGridSampler::default(); sampler.sample_grid_detailed( 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..b57f643 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs @@ -14,7 +14,7 @@ macro_rules! CHECK { use std::{cell::RefCell, rc::Rc}; use crate::{ - common::{BitMatrix, DefaultGridSampler, GridSampler}, + common::{BitMatrix, DefaultGridSampler, GridSampler, Result}, datamatrix::detector::{ zxing_cpp_detector::{util::intersect, BitMatrixCursor, Quadrilateral, RegressionLine}, DatamatrixDetectorResult, @@ -37,7 +37,7 @@ use super::{DMRegressionLine, EdgeTracer}; fn Scan( startTracer: &mut EdgeTracer, lines: &mut [DMRegressionLine; 4], -) -> Result { +) -> Result { while startTracer.step(None) { //log(startTracer.p); @@ -261,7 +261,7 @@ pub fn detect( image: &BitMatrix, tryHarder: bool, tryRotate: bool, -) -> Result { +) -> Result { // #ifdef PRINT_DEBUG // LogMatrixWriter lmw(log, image, 1, "dm-log.pnm"); // // tryRotate = tryHarder = false; 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..9b38048 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/dm_regression_line.rs @@ -1,3 +1,4 @@ +use crate::common::Result; use crate::{Exceptions, RXingResultPoint}; use super::{ @@ -74,7 +75,7 @@ impl RegressionLine for DMRegressionLine { self.c = f32::NAN; } - fn add(&mut self, p: &RXingResultPoint) -> Result<(), Exceptions> { + fn add(&mut self, p: &RXingResultPoint) -> Result<()> { if self.direction_inward == RXingResultPoint::default() { return Err(Exceptions::IllegalStateException(None)); } @@ -235,11 +236,7 @@ impl DMRegressionLine { self.points.reverse(); } - pub fn modules( - &mut self, - beg: &RXingResultPoint, - end: &RXingResultPoint, - ) -> Result { + pub fn modules(&mut self, beg: &RXingResultPoint, end: &RXingResultPoint) -> Result { if self.points.len() <= 3 { return Err(Exceptions::IllegalStateException(None)); } diff --git a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs index d547e93..1093881 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/edge_tracer.rs @@ -1,6 +1,10 @@ use std::{cell::RefCell, rc::Rc}; -use crate::{common::BitMatrix, qrcode::encoder::ByteMatrix, Exceptions, RXingResultPoint}; +use crate::{ + common::{BitMatrix, Result}, + qrcode::encoder::ByteMatrix, + Exceptions, RXingResultPoint, +}; use super::{BitMatrixCursor, Direction, RegressionLine, StepResult, Value}; @@ -170,7 +174,7 @@ impl<'a> EdgeTracer<'_> { dEdge: &RXingResultPoint, maxStepSize: i32, goodDirection: bool, - ) -> Result { + ) -> Result { let dEdge = RXingResultPoint::mainDirection(*dEdge); for breadth in 1..=(if maxStepSize == 1 { 2 @@ -262,7 +266,7 @@ impl<'a> EdgeTracer<'_> { &mut self, dEdge: &RXingResultPoint, line: &mut T, - ) -> Result { + ) -> Result { line.setDirectionInward(dEdge); loop { // log(self.p); @@ -295,7 +299,7 @@ impl<'a> EdgeTracer<'_> { line: &mut T, maxStepSize: i32, finishLine: &mut T, - ) -> Result { + ) -> Result { let mut maxStepSize = maxStepSize; line.setDirectionInward(dEdge); let mut gaps = 0; @@ -437,7 +441,7 @@ impl<'a> EdgeTracer<'_> { &mut self, dir: &mut RXingResultPoint, corner: &mut RXingResultPoint, - ) -> Result { + ) -> Result { self.step(None); // log(p); *corner = self.p; diff --git a/src/datamatrix/detector/zxing_cpp_detector/regression_line.rs b/src/datamatrix/detector/zxing_cpp_detector/regression_line.rs index aa73470..f0f5ab5 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/regression_line.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/regression_line.rs @@ -1,4 +1,5 @@ -use crate::{Exceptions, RXingResultPoint}; +use crate::common::Result; +use crate::RXingResultPoint; pub trait RegressionLine { // points: Vec, @@ -76,12 +77,12 @@ pub trait RegressionLine { // a = b = c = NAN; // } - fn add(&mut self, p: &RXingResultPoint) -> Result<(), Exceptions>; //{ - // assert(_directionInward != PointF()); - // _points.push_back(p); - // if (_points.size() == 1) - // c = dot(normal(), p); - // } + fn add(&mut self, p: &RXingResultPoint) -> Result<()>; //{ + // assert(_directionInward != PointF()); + // _points.push_back(p); + // if (_points.size() == 1) + // c = dot(normal(), p); + // } fn pop_back(&mut self); // { _points.pop_back(); } diff --git a/src/datamatrix/detector/zxing_cpp_detector/util.rs b/src/datamatrix/detector/zxing_cpp_detector/util.rs index 00e3c01..0df0f36 100644 --- a/src/datamatrix/detector/zxing_cpp_detector/util.rs +++ b/src/datamatrix/detector/zxing_cpp_detector/util.rs @@ -1,3 +1,4 @@ +use crate::common::Result; use crate::{Exceptions, RXingResultPoint}; use super::{DMRegressionLine, Direction, RegressionLine}; @@ -21,10 +22,7 @@ pub fn float_max(a: T, b: T) -> T { } #[inline(always)] -pub fn intersect( - l1: &DMRegressionLine, - l2: &DMRegressionLine, -) -> Result { +pub fn intersect(l1: &DMRegressionLine, l2: &DMRegressionLine) -> Result { if !(l1.isValid() && l2.isValid()) { return Err(Exceptions::IllegalStateException(None)); } diff --git a/src/datamatrix/encoder/ascii_encoder.rs b/src/datamatrix/encoder/ascii_encoder.rs index a235321..b6a0def 100644 --- a/src/datamatrix/encoder/ascii_encoder.rs +++ b/src/datamatrix/encoder/ascii_encoder.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::{high_level_encoder, Encoder}; @@ -21,7 +22,7 @@ use super::{high_level_encoder, Encoder}; pub struct ASCIIEncoder; impl Encoder for ASCIIEncoder { - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { //step B let n = high_level_encoder::determineConsecutiveDigitCount(context.getMessage(), context.pos); @@ -99,7 +100,7 @@ impl ASCIIEncoder { pub fn new() -> Self { Self } - fn encodeASCIIDigits(digit1: char, digit2: char) -> Result { + fn encodeASCIIDigits(digit1: char, digit2: char) -> Result { if high_level_encoder::isDigit(digit1) && high_level_encoder::isDigit(digit2) { let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); Ok((num + 130) as char) diff --git a/src/datamatrix/encoder/base256_encoder.rs b/src/datamatrix/encoder/base256_encoder.rs index f62d9ed..0d7ada3 100644 --- a/src/datamatrix/encoder/base256_encoder.rs +++ b/src/datamatrix/encoder/base256_encoder.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::{ @@ -27,7 +28,7 @@ impl Encoder for Base256Encoder { BASE256_ENCODATION } - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), crate::Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { let mut buffer = String::new(); buffer.push('\0'); //Initialize length field while context.hasMoreCharacters() { diff --git a/src/datamatrix/encoder/c40_encoder.rs b/src/datamatrix/encoder/c40_encoder.rs index b6c3d3a..fa8bbce 100644 --- a/src/datamatrix/encoder/c40_encoder.rs +++ b/src/datamatrix/encoder/c40_encoder.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::high_level_encoder::{ @@ -25,7 +26,7 @@ use super::{Encoder, EncoderContext}; pub struct C40Encoder; impl Encoder for C40Encoder { - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { self.encode_with_encode_char_fn( context, &Self::encodeChar_c40, @@ -48,9 +49,9 @@ impl C40Encoder { &self, context: &mut super::EncoderContext, encodeChar: &dyn Fn(char, &mut String) -> u32, - handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<(), Exceptions>, + handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<()>, getEncodingMode: &dyn Fn() -> usize, - ) -> Result<(), Exceptions> { + ) -> Result<()> { //step C let mut buffer = String::new(); while context.hasMoreCharacters() { @@ -110,7 +111,7 @@ impl C40Encoder { handleEOD(context, &mut buffer) } - pub fn encodeMaximalC40(&self, context: &mut EncoderContext) -> Result<(), Exceptions> { + pub fn encodeMaximalC40(&self, context: &mut EncoderContext) -> Result<()> { self.encodeMaximal(context, &Self::encodeChar_c40, &Self::handleEOD_c40) } @@ -118,8 +119,8 @@ impl C40Encoder { &self, context: &mut EncoderContext, encodeChar: &dyn Fn(char, &mut String) -> u32, - handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<(), Exceptions>, - ) -> Result<(), Exceptions> { + handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<()>, + ) -> Result<()> { let mut buffer = String::new(); let mut lastCharSize = 0; let mut backtrackStartPosition = context.pos; @@ -181,7 +182,7 @@ impl C40Encoder { pub(super) fn writeNextTriplet( context: &mut EncoderContext, buffer: &mut String, - ) -> Result<(), Exceptions> { + ) -> Result<()> { context.writeCodewords( &Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?, ); @@ -196,10 +197,7 @@ impl C40Encoder { * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ - pub fn handleEOD_c40( - context: &mut EncoderContext, - buffer: &mut String, - ) -> Result<(), Exceptions> { + pub fn handleEOD_c40(context: &mut EncoderContext, buffer: &mut String) -> Result<()> { let unwritten = (buffer.chars().count() / 3) * 2; let rest = buffer.chars().count() % 3; diff --git a/src/datamatrix/encoder/datamatrix_encoder.rs b/src/datamatrix/encoder/datamatrix_encoder.rs index 907f38a..91c54bb 100644 --- a/src/datamatrix/encoder/datamatrix_encoder.rs +++ b/src/datamatrix/encoder/datamatrix_encoder.rs @@ -14,12 +14,12 @@ * limitations under the License. */ -use crate::Exceptions; +use crate::common::Result; use super::EncoderContext; pub trait Encoder { fn getEncodingMode(&self) -> usize; - fn encode(&self, context: &mut EncoderContext) -> Result<(), Exceptions>; + fn encode(&self, context: &mut EncoderContext) -> Result<()>; } diff --git a/src/datamatrix/encoder/default_placement.rs b/src/datamatrix/encoder/default_placement.rs index a4091a3..46137b5 100644 --- a/src/datamatrix/encoder/default_placement.rs +++ b/src/datamatrix/encoder/default_placement.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; const EMPTY_BIT_VAL: u8 = 13; @@ -73,7 +74,7 @@ impl DefaultPlacement { self.bits[row * self.numcols + col] == EMPTY_BIT_VAL } - pub fn place(&mut self) -> Result<(), Exceptions> { + pub fn place(&mut self) -> Result<()> { let mut pos = 0; let mut row = 4_isize; let mut col = 0_isize; @@ -147,7 +148,7 @@ impl DefaultPlacement { Ok(()) } - fn module(&mut self, row: isize, col: isize, pos: usize, bit: u32) -> Result<(), Exceptions> { + fn module(&mut self, row: isize, col: isize, pos: usize, bit: u32) -> Result<()> { let mut row = row; let mut col = col; @@ -178,7 +179,7 @@ impl DefaultPlacement { * @param col the column * @param pos character position */ - fn utah(&mut self, row: isize, col: isize, pos: usize) -> Result<(), Exceptions> { + fn utah(&mut self, row: isize, col: isize, pos: usize) -> Result<()> { self.module(row - 2, col - 2, pos, 1)?; self.module(row - 2, col - 1, pos, 2)?; self.module(row - 1, col - 2, pos, 3)?; @@ -190,7 +191,7 @@ impl DefaultPlacement { Ok(()) } - fn corner1(&mut self, pos: usize) -> Result<(), Exceptions> { + fn corner1(&mut self, pos: usize) -> Result<()> { self.module(self.numrows as isize - 1, 0, pos, 1)?; self.module(self.numrows as isize - 1, 1, pos, 2)?; self.module(self.numrows as isize - 1, 2, pos, 3)?; @@ -202,7 +203,7 @@ impl DefaultPlacement { Ok(()) } - fn corner2(&mut self, pos: usize) -> Result<(), Exceptions> { + fn corner2(&mut self, pos: usize) -> Result<()> { self.module(self.numrows as isize - 3, 0, pos, 1)?; self.module(self.numrows as isize - 2, 0, pos, 2)?; self.module(self.numrows as isize - 1, 0, pos, 3)?; @@ -214,7 +215,7 @@ impl DefaultPlacement { Ok(()) } - fn corner3(&mut self, pos: usize) -> Result<(), Exceptions> { + fn corner3(&mut self, pos: usize) -> Result<()> { self.module(self.numrows as isize - 3, 0, pos, 1)?; self.module(self.numrows as isize - 2, 0, pos, 2)?; self.module(self.numrows as isize - 1, 0, pos, 3)?; @@ -226,7 +227,7 @@ impl DefaultPlacement { Ok(()) } - fn corner4(&mut self, pos: usize) -> Result<(), Exceptions> { + fn corner4(&mut self, pos: usize) -> Result<()> { self.module(self.numrows as isize - 1, 0, pos, 1)?; self.module(self.numrows as isize - 1, self.numcols as isize - 1, pos, 2)?; self.module(0, self.numcols as isize - 3, pos, 3)?; diff --git a/src/datamatrix/encoder/edifact_encoder.rs b/src/datamatrix/encoder/edifact_encoder.rs index cf1cab0..88d3c1c 100644 --- a/src/datamatrix/encoder/edifact_encoder.rs +++ b/src/datamatrix/encoder/edifact_encoder.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::{high_level_encoder, Encoder, EncoderContext}; @@ -24,7 +25,7 @@ impl Encoder for EdifactEncoder { high_level_encoder::EDIFACT_ENCODATION } - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), crate::Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { //step F let mut buffer = String::new(); while context.hasMoreCharacters() { @@ -65,8 +66,8 @@ impl EdifactEncoder { * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ - fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { - let mut runner = || -> Result<(), Exceptions> { + fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<()> { + let mut runner = || -> Result<()> { let count = buffer.chars().count(); if count == 0 { return Ok(()); //Already finished @@ -135,7 +136,7 @@ impl EdifactEncoder { res } - fn encodeChar(c: char, sb: &mut String) -> Result<(), Exceptions> { + fn encodeChar(c: char, sb: &mut String) -> Result<()> { if (' '..='?').contains(&c) { sb.push(c); } else if ('@'..='^').contains(&c) { @@ -146,7 +147,7 @@ impl EdifactEncoder { Ok(()) } - fn encodeToCodewords(sb: &str) -> Result { + fn encodeToCodewords(sb: &str) -> Result { let len = sb.chars().count(); if len == 0 { return Err(Exceptions::IllegalStateException(Some( diff --git a/src/datamatrix/encoder/encoder_context.rs b/src/datamatrix/encoder/encoder_context.rs index c2a9c7f..0c1c5f0 100644 --- a/src/datamatrix/encoder/encoder_context.rs +++ b/src/datamatrix/encoder/encoder_context.rs @@ -16,6 +16,7 @@ use std::rc::Rc; +use crate::common::Result; use crate::{Dimension, Exceptions}; use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint}; @@ -40,13 +41,13 @@ impl<'a> EncoderContext<'_> { pub fn with_symbol_info_lookup( msg: &str, symbol_lookup: Rc>, - ) -> Result, Exceptions> { + ) -> Result> { let mut new_self = EncoderContext::new(msg)?; new_self.symbol_lookup = symbol_lookup.clone(); Ok(new_self) } - pub fn new(msg: &str) -> Result { + pub fn new(msg: &str) -> Result { //From this point on Strings are not Unicode anymore! // let msgBinary = ISO_8859_1_ENCODER.encode(msg, encoding::EncoderTrap::Strict).expect("encode to bytes");//msg.getBytes(StandardCharsets.ISO_8859_1); // let sb = String::with_capacity(msgBinary.len()); diff --git a/src/datamatrix/encoder/error_correction.rs b/src/datamatrix/encoder/error_correction.rs index 4c07b9b..3a623e6 100644 --- a/src/datamatrix/encoder/error_correction.rs +++ b/src/datamatrix/encoder/error_correction.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::SymbolInfo; @@ -152,7 +153,7 @@ const ALOG: [u32; 255] = { * @param symbolInfo information about the symbol to be encoded * @return the codewords with interleaved error correction. */ -pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { +pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { return Err(Exceptions::IllegalArgumentException(Some( "The number of codewords does not match the selected symbol".to_owned(), @@ -217,7 +218,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result Result { +fn createECCBlock(codewords: &str, numECWords: usize) -> Result { let mut table = -1_isize; for (i, set) in FACTOR_SETS.iter().enumerate() { // for i in 0..FACTOR_SETS.len() { diff --git a/src/datamatrix/encoder/high_level_encoder.rs b/src/datamatrix/encoder/high_level_encoder.rs index b08d9cc..5baa97b 100644 --- a/src/datamatrix/encoder/high_level_encoder.rs +++ b/src/datamatrix/encoder/high_level_encoder.rs @@ -18,6 +18,7 @@ use std::rc::Rc; use encoding::{self, EncodingRef}; +use crate::common::Result; use crate::{Dimension, Exceptions}; use super::{ @@ -134,7 +135,7 @@ fn randomize253State(codewordPosition: u32) -> String { * @param msg the message * @return the encoded message (the char values range from 0 to 255) */ -pub fn encodeHighLevel(msg: &str) -> Result { +pub fn encodeHighLevel(msg: &str) -> Result { encodeHighLevelWithDimensionForceC40(msg, SymbolShapeHint::FORCE_NONE, None, None, false) } @@ -148,7 +149,7 @@ pub fn encodeHighLevel(msg: &str) -> Result { pub fn encodeHighLevelSIL( msg: &str, symbol_lookup: Option>, -) -> Result { +) -> Result { encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( msg, SymbolShapeHint::FORCE_NONE, @@ -175,7 +176,7 @@ pub fn encodeHighLevelWithDimension( shape: SymbolShapeHint, minSize: Option, maxSize: Option, -) -> Result { +) -> Result { encodeHighLevelWithDimensionForceC40(msg, shape, minSize, maxSize, false) } @@ -186,7 +187,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( maxSize: Option, forceC40: bool, symbol_lookup: Option>, -) -> Result { +) -> Result { //the codewords 0..255 are encoded as Unicode characters let c40Encoder = Rc::new(C40Encoder::new()); let encoders: [Rc; 6] = [ @@ -284,7 +285,7 @@ pub fn encodeHighLevelWithDimensionForceC40( minSize: Option, maxSize: Option, forceC40: bool, -) -> Result { +) -> Result { encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( msg, shape, minSize, maxSize, forceC40, None, ) @@ -608,7 +609,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 { idx - startpos } -pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { +pub fn illegalCharacter(c: char) -> Result<()> { // let hex = Integer.toHexString(c); // hex = "0000".substring(0, 4 - hex.length()) + hex; Err(Exceptions::IllegalArgumentException(Some(format!( diff --git a/src/datamatrix/encoder/minimal_encoder.rs b/src/datamatrix/encoder/minimal_encoder.rs index 67ee60b..bd7f84f 100755 --- a/src/datamatrix/encoder/minimal_encoder.rs +++ b/src/datamatrix/encoder/minimal_encoder.rs @@ -19,7 +19,7 @@ use std::{fmt, rc::Rc}; use encoding::{self, EncodingRef}; use crate::{ - common::{ECIInput, MinimalECIInput}, + common::{ECIInput, MinimalECIInput, Result}, Exceptions, }; @@ -134,7 +134,7 @@ fn isInTextShift2Set(ch: char, fnc1: Option) -> bool { * @param msg the message * @return the encoded message (the char values range from 0 to 255) */ -pub fn encodeHighLevel(msg: &str) -> Result { +pub fn encodeHighLevel(msg: &str) -> Result { encodeHighLevelWithDetails(msg, None, None, SymbolShapeHint::FORCE_NONE) } @@ -156,7 +156,7 @@ pub fn encodeHighLevelWithDetails( priorityCharset: Option, fnc1: Option, shape: SymbolShapeHint, -) -> Result { +) -> Result { let mut msg = msg; let mut macroId = 0; if msg.starts_with(high_level_encoder::MACRO_05_HEADER) @@ -201,7 +201,7 @@ fn encode( fnc1: Option, shape: SymbolShapeHint, macroId: i32, -) -> Result, Exceptions> { +) -> Result> { Ok(encodeMinimally(Rc::new(Input::new( input, priorityCharset, @@ -213,7 +213,7 @@ fn encode( .to_vec()) } -fn addEdge(edges: &mut [Vec>>], edge: Rc) -> Result<(), Exceptions> { +fn addEdge(edges: &mut [Vec>>], edge: Rc) -> Result<()> { let vertexIndex = (edge.fromPosition + edge.characterLength) as usize; if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() || edges[vertexIndex][edge.getEndMode()?.ordinal()] @@ -239,7 +239,7 @@ fn getNumberOfC40Words( from: u32, c40: bool, characterLength: &mut [u32], -) -> Result { +) -> Result { let mut thirdsCount = 0; for i in (from as usize)..input.length() { // for (int i = from; i < input.length(); i++) { @@ -282,7 +282,7 @@ fn addEdges( edges: &mut [Vec>>], from: u32, previous: Option>, -) -> Result<(), Exceptions> { +) -> Result<()> { if input.isECI(from)? { addEdge( edges, @@ -409,7 +409,7 @@ fn addEdges( Ok(()) } -fn encodeMinimally(input: Rc) -> Result { +fn encodeMinimally(input: Rc) -> Result { // @SuppressWarnings("checkstyle:lineLength") /* The minimal encoding is computed by Dijkstra. The acyclic graph is modeled as follows: * A vertex represents a combination of a position in the input and an encoding mode where position 0 @@ -667,7 +667,7 @@ impl Edge { fromPosition: u32, characterLength: u32, previous: Option>, - ) -> Result { + ) -> Result { if fromPosition + characterLength > input.length() as u32 { return Err(Exceptions::FormatException(None)); } @@ -804,7 +804,7 @@ impl Edge { // if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode} } - pub fn getPreviousMode(previous: Option>) -> Result { + pub fn getPreviousMode(previous: Option>) -> Result { if let Some(prev) = previous { prev.getEndMode() } else { @@ -819,7 +819,7 @@ impl Edge { * - Mode is C40, TEXT or X12 and the remaining characters can be encoded in at most 1 ASCII byte. * Returns mode in all other cases. * */ - pub fn getEndMode(&self) -> Result { + pub fn getEndMode(&self) -> Result { let mode = self.mode; if mode == Mode::Edf { if self.characterLength < 4 { @@ -856,7 +856,7 @@ impl Edge { * two consecutive digits and a non extended character or of 4 digits. * Returns 0 in any other case **/ - pub fn getLastASCII(&self) -> Result { + pub fn getLastASCII(&self) -> Result { let length = self.input.length() as u32; let from = self.fromPosition + self.characterLength; if length - from > 4 || from >= length { @@ -1000,7 +1000,7 @@ impl Edge { } } - pub fn getX12Words(&self) -> Result, Exceptions> { + pub fn getX12Words(&self) -> Result> { assert!(self.characterLength % 3 == 0); let mut result = vec![0u8; self.characterLength as usize / 3 * 2]; let mut i = 0; @@ -1096,7 +1096,7 @@ impl Edge { } } - pub fn getC40Words(&self, c40: bool, fnc1: Option) -> Result, Exceptions> { + pub fn getC40Words(&self, c40: bool, fnc1: Option) -> Result> { let mut c40Values: Vec = Vec::new(); let fromPosition = self.fromPosition as usize; for i in 0..self.characterLength as usize { @@ -1156,7 +1156,7 @@ impl Edge { Ok(result) } - pub fn getEDFBytes(&self) -> Result, Exceptions> { + pub fn getEDFBytes(&self) -> Result> { let numberOfThirds = (self.characterLength as f32 / 4.0).ceil() as usize; let mut result = vec![0u8; numberOfThirds * 3]; let mut pos = self.fromPosition as usize; @@ -1190,7 +1190,7 @@ impl Edge { Ok(result) } - pub fn getLatchBytes(&self) -> Result, Exceptions> { + pub fn getLatchBytes(&self) -> Result> { match Self::getPreviousMode(self.previous.clone())? { Mode::Ascii | Mode::B256 => //after B256 ends (via length) we are back to ASCII @@ -1224,7 +1224,7 @@ impl Edge { } // Important: The function does not return the length bytes (one or two) in case of B256 encoding - pub fn getDataBytes(&self) -> Result, Exceptions> { + pub fn getDataBytes(&self) -> Result> { match self.mode { Mode::Ascii => { if self.input.isECI(self.fromPosition)? { @@ -1272,7 +1272,7 @@ struct RXingResult { bytes: Vec, } impl RXingResult { - pub fn new(solution: Option>) -> Result { + pub fn new(solution: Option>) -> Result { let solution = if let Some(edge) = solution { edge } else { @@ -1427,10 +1427,10 @@ impl Input { pub fn length(&self) -> usize { self.internal.length() } - pub fn isECI(&self, index: u32) -> Result { + pub fn isECI(&self, index: u32) -> Result { self.internal.isECI(index) } - pub fn charAt(&self, index: usize) -> Result { + pub fn charAt(&self, index: usize) -> Result { self.internal.charAt(index) } pub fn getFNC1Character(&self) -> Option { @@ -1440,13 +1440,13 @@ impl Input { Some(self.internal.getFNC1Character() as u8 as char) } } - fn haveNCharacters(&self, index: usize, n: usize) -> Result { + fn haveNCharacters(&self, index: usize, n: usize) -> Result { self.internal.haveNCharacters(index, n) } - fn isFNC1(&self, index: usize) -> Result { + fn isFNC1(&self, index: usize) -> Result { self.internal.isFNC1(index) } - fn getECIValue(&self, index: usize) -> Result { + fn getECIValue(&self, index: usize) -> Result { self.internal.getECIValue(index) } } diff --git a/src/datamatrix/encoder/symbol_info.rs b/src/datamatrix/encoder/symbol_info.rs index 1ff6b9e..d3c4d6e 100644 --- a/src/datamatrix/encoder/symbol_info.rs +++ b/src/datamatrix/encoder/symbol_info.rs @@ -16,6 +16,7 @@ use std::fmt; +use crate::common::Result; use crate::{Dimension, Exceptions}; use super::SymbolShapeHint; @@ -122,7 +123,7 @@ impl SymbolInfo { new_symbol } - fn getHorizontalDataRegions(&self) -> Result { + fn getHorizontalDataRegions(&self) -> Result { match self.dataRegions { 1 => Ok(1), 2 | 4 => Ok(2), @@ -134,7 +135,7 @@ impl SymbolInfo { } } - fn getVerticalDataRegions(&self) -> Result { + fn getVerticalDataRegions(&self) -> Result { match self.dataRegions { 1 | 2 => Ok(1), 4 => Ok(2), @@ -146,19 +147,19 @@ impl SymbolInfo { } } - pub fn getSymbolDataWidth(&self) -> Result { + pub fn getSymbolDataWidth(&self) -> Result { Ok(self.getHorizontalDataRegions()? * self.matrixWidth) } - pub fn getSymbolDataHeight(&self) -> Result { + pub fn getSymbolDataHeight(&self) -> Result { Ok(self.getVerticalDataRegions()? * self.matrixHeight) } - pub fn getSymbolWidth(&self) -> Result { + pub fn getSymbolWidth(&self) -> Result { Ok(self.getSymbolDataWidth()? + (self.getHorizontalDataRegions()? * 2)) } - pub fn getSymbolHeight(&self) -> Result { + pub fn getSymbolHeight(&self) -> Result { Ok(self.getSymbolDataHeight()? + (self.getVerticalDataRegions()? * 2)) } @@ -236,7 +237,7 @@ impl<'a> SymbolInfoLookup<'a> { self.0 = Some(override_symbols); } - pub fn lookup(&self, dataCodewords: u32) -> Result, Exceptions> { + pub fn lookup(&self, dataCodewords: u32) -> Result> { self.lookup_with_codewords_shape_fail(dataCodewords, SymbolShapeHint::FORCE_NONE, true) } @@ -244,7 +245,7 @@ impl<'a> SymbolInfoLookup<'a> { &self, dataCodewords: u32, shape: SymbolShapeHint, - ) -> Result, Exceptions> { + ) -> Result> { self.lookup_with_codewords_shape_fail(dataCodewords, shape, true) } @@ -253,7 +254,7 @@ impl<'a> SymbolInfoLookup<'a> { dataCodewords: u32, allowRectangular: bool, fail: bool, - ) -> Result, Exceptions> { + ) -> Result> { let shape = if allowRectangular { SymbolShapeHint::FORCE_NONE } else { @@ -267,7 +268,7 @@ impl<'a> SymbolInfoLookup<'a> { dataCodewords: u32, shape: SymbolShapeHint, fail: bool, - ) -> Result, Exceptions> { + ) -> Result> { self.lookup_with_codewords_shape_size_fail(dataCodewords, shape, &None, &None, fail) } @@ -279,7 +280,7 @@ impl<'a> SymbolInfoLookup<'a> { maxSize: &Option, fail: bool, // alternate_symbols_chart: Option<&'a Vec>, - ) -> Result, Exceptions> { + ) -> Result> { let symbol_search_chart: &Vec = if self.0.is_none() { &PROD_SYMBOLS } else { diff --git a/src/datamatrix/encoder/text_encoder.rs b/src/datamatrix/encoder/text_encoder.rs index a375560..217233e 100644 --- a/src/datamatrix/encoder/text_encoder.rs +++ b/src/datamatrix/encoder/text_encoder.rs @@ -15,6 +15,7 @@ */ use super::{high_level_encoder, C40Encoder, Encoder}; +use crate::common::Result; pub struct TextEncoder(C40Encoder); impl Encoder for TextEncoder { @@ -22,7 +23,7 @@ impl Encoder for TextEncoder { high_level_encoder::TEXT_ENCODATION } - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), crate::Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { self.0.encode_with_encode_char_fn( context, &Self::encodeChar, diff --git a/src/datamatrix/encoder/x12_encoder.rs b/src/datamatrix/encoder/x12_encoder.rs index c479f24..fd55031 100644 --- a/src/datamatrix/encoder/x12_encoder.rs +++ b/src/datamatrix/encoder/x12_encoder.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::{high_level_encoder, C40Encoder, Encoder, EncoderContext}; @@ -24,7 +25,7 @@ impl Encoder for X12Encoder { high_level_encoder::X12_ENCODATION } - fn encode(&self, context: &mut super::EncoderContext) -> Result<(), crate::Exceptions> { + fn encode(&self, context: &mut super::EncoderContext) -> Result<()> { //step C let mut buffer = String::new(); while context.hasMoreCharacters() { @@ -58,7 +59,7 @@ impl X12Encoder { Self(C40Encoder::new()) } - fn encodeChar(c: char, sb: &mut String) -> Result { + fn encodeChar(c: char, sb: &mut String) -> Result { match c { '\r' => sb.push('\0'), '*' => sb.push('\u{1}'), @@ -77,7 +78,7 @@ impl X12Encoder { Ok(1) } - fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { + fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<()> { context.updateSymbolInfo(); let available = context .getSymbolInfo() diff --git a/src/helpers.rs b/src/helpers.rs index 68e853b..02e694b 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -6,7 +6,7 @@ use std::{ }; use crate::{ - common::{BitMatrix, HybridBinarizer}, + common::{BitMatrix, HybridBinarizer, Result}, multi::{GenericMultipleBarcodeReader, MultipleBarcodeReader}, BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, Luma8LuminanceSource, MultiFormatReader, RXingResult, Reader, @@ -16,10 +16,7 @@ use crate::{ use crate::BufferedImageLuminanceSource; #[cfg(feature = "svg_read")] -pub fn detect_in_svg( - file_name: &str, - barcode_type: Option, -) -> Result { +pub fn detect_in_svg(file_name: &str, barcode_type: Option) -> Result { detect_in_svg_with_hints(file_name, barcode_type, &mut HashMap::new()) } @@ -28,7 +25,7 @@ pub fn detect_in_svg_with_hints( file_name: &str, barcode_type: Option, hints: &mut DecodingHintDictionary, -) -> Result { +) -> Result { use std::{fs::File, io::Read}; use crate::SVGLuminanceSource; @@ -73,7 +70,7 @@ pub fn detect_in_svg_with_hints( } #[cfg(feature = "svg_read")] -pub fn detect_multiple_in_svg(file_name: &str) -> Result, Exceptions> { +pub fn detect_multiple_in_svg(file_name: &str) -> Result> { detect_multiple_in_svg_with_hints(file_name, &mut HashMap::new()) } @@ -81,7 +78,7 @@ pub fn detect_multiple_in_svg(file_name: &str) -> Result, Excep pub fn detect_multiple_in_svg_with_hints( file_name: &str, hints: &mut DecodingHintDictionary, -) -> Result, Exceptions> { +) -> Result> { use std::{fs::File, io::Read}; use crate::SVGLuminanceSource; @@ -120,10 +117,7 @@ pub fn detect_multiple_in_svg_with_hints( } #[cfg(feature = "image")] -pub fn detect_in_file( - file_name: &str, - barcode_type: Option, -) -> Result { +pub fn detect_in_file(file_name: &str, barcode_type: Option) -> Result { detect_in_file_with_hints(file_name, barcode_type, &mut HashMap::new()) } @@ -132,7 +126,7 @@ pub fn detect_in_file_with_hints( file_name: &str, barcode_type: Option, hints: &mut DecodingHintDictionary, -) -> Result { +) -> Result { let Ok(img) = image::open(file_name) else { return Err(Exceptions::IllegalArgumentException(Some(format!("file '{file_name}' not found or cannot be opened")))); }; @@ -158,7 +152,7 @@ pub fn detect_in_file_with_hints( } #[cfg(feature = "image")] -pub fn detect_multiple_in_file(file_name: &str) -> Result, Exceptions> { +pub fn detect_multiple_in_file(file_name: &str) -> Result> { detect_multiple_in_file_with_hints(file_name, &mut HashMap::new()) } @@ -166,7 +160,7 @@ pub fn detect_multiple_in_file(file_name: &str) -> Result, Exce pub fn detect_multiple_in_file_with_hints( file_name: &str, hints: &mut DecodingHintDictionary, -) -> Result, Exceptions> { +) -> Result> { let img = image::open(file_name).map_err(|e| { Exceptions::RuntimeException(Some(format!("couldn't read {file_name}: {e}"))) })?; @@ -190,7 +184,7 @@ pub fn detect_in_luma( width: u32, height: u32, barcode_type: Option, -) -> Result { +) -> Result { detect_in_luma_with_hints(luma, height, width, barcode_type, &mut HashMap::new()) } @@ -200,7 +194,7 @@ pub fn detect_in_luma_with_hints( height: u32, barcode_type: Option, hints: &mut DecodingHintDictionary, -) -> Result { +) -> Result { let mut multi_format_reader = MultiFormatReader::default(); if let Some(bc_type) = barcode_type { @@ -222,11 +216,7 @@ pub fn detect_in_luma_with_hints( ) } -pub fn detect_multiple_in_luma( - luma: Vec, - width: u32, - height: u32, -) -> Result, Exceptions> { +pub fn detect_multiple_in_luma(luma: Vec, width: u32, height: u32) -> Result> { detect_multiple_in_luma_with_hints(luma, width, height, &mut HashMap::new()) } @@ -235,7 +225,7 @@ pub fn detect_multiple_in_luma_with_hints( width: u32, height: u32, hints: &mut DecodingHintDictionary, -) -> Result, Exceptions> { +) -> Result> { let multi_format_reader = MultiFormatReader::default(); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); @@ -252,7 +242,7 @@ pub fn detect_multiple_in_luma_with_hints( } #[cfg(feature = "image")] -pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptions> { +pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { let image: image::DynamicImage = bit_matrix.into(); match image.save(file_name) { Ok(_) => Ok(()), @@ -263,7 +253,7 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Excepti } #[cfg(feature = "svg_write")] -pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptions> { +pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { let svg: svg::Document = bit_matrix.into(); match svg::save(file_name, &svg) { @@ -275,7 +265,7 @@ pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exception } } -pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptions> { +pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<()> { let path = PathBuf::from(file_name); #[allow(unused_variables)] diff --git a/src/luma_luma_source.rs b/src/luma_luma_source.rs index 37631fa..d326734 100644 --- a/src/luma_luma_source.rs +++ b/src/luma_luma_source.rs @@ -1,3 +1,4 @@ +use crate::common::Result; use crate::LuminanceSource; /// A simple luma8 source for bytes, supports cropping but not rotation @@ -67,7 +68,7 @@ impl LuminanceSource for Luma8LuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, crate::Exceptions> { + ) -> Result> { Ok(Box::new(Self { dimensions: (width as u32, height as u32), origin: (left as u32, top as u32), @@ -81,7 +82,7 @@ impl LuminanceSource for Luma8LuminanceSource { true } - fn rotateCounterClockwise(&self) -> Result, crate::Exceptions> { + fn rotateCounterClockwise(&self) -> Result> { let mut new_matrix = Self { dimensions: self.dimensions, origin: self.origin, @@ -94,7 +95,7 @@ impl LuminanceSource for Luma8LuminanceSource { Ok(Box::new(new_matrix)) } - fn rotateCounterClockwise45(&self) -> Result, crate::Exceptions> { + fn rotateCounterClockwise45(&self) -> Result> { Err(crate::Exceptions::UnsupportedOperationException(Some( "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..581c86a 100644 --- a/src/luminance_source.rs +++ b/src/luminance_source.rs @@ -16,6 +16,7 @@ //package com.google.zxing; +use crate::common::Result; use crate::Exceptions; /** @@ -90,7 +91,7 @@ pub trait LuminanceSource { _top: usize, _width: usize, _height: usize, - ) -> Result, Exceptions> { + ) -> Result> { Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support cropping.".to_owned(), ))) @@ -117,7 +118,7 @@ pub trait LuminanceSource { * * @return A rotated version of this object. */ - fn rotateCounterClockwise(&self) -> Result, Exceptions> { + fn rotateCounterClockwise(&self) -> Result> { Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support rotation by 90 degrees.".to_owned(), ))) @@ -129,7 +130,7 @@ pub trait LuminanceSource { * * @return A rotated version of this object. */ - fn rotateCounterClockwise45(&self) -> Result, Exceptions> { + fn rotateCounterClockwise45(&self) -> Result> { Err(Exceptions::UnsupportedOperationException(Some( "This luminance source does not support rotation by 45 degrees.".to_owned(), ))) diff --git a/src/maxicode/decoder/decoded_bit_stream_parser.rs b/src/maxicode/decoder/decoded_bit_stream_parser.rs index 33f2578..7120ecb 100644 --- a/src/maxicode/decoder/decoded_bit_stream_parser.rs +++ b/src/maxicode/decoder/decoded_bit_stream_parser.rs @@ -16,7 +16,10 @@ use unicode_segmentation::UnicodeSegmentation; -use crate::{common::DecoderRXingResult, Exceptions}; +use crate::{ + common::{DecoderRXingResult, Result}, + Exceptions, +}; use once_cell::sync::Lazy; /** @@ -78,7 +81,7 @@ static SETS: Lazy<[String; 5]> = Lazy::new(|| { ] }); -pub fn decode(bytes: &[u8], mode: u8) -> Result { +pub fn decode(bytes: &[u8], mode: u8) -> Result { let mut result = String::with_capacity(144); match mode { 2 | 3 => { diff --git a/src/maxicode/decoder/maxicode_decoder.rs b/src/maxicode/decoder/maxicode_decoder.rs index d142f85..d77c05d 100644 --- a/src/maxicode/decoder/maxicode_decoder.rs +++ b/src/maxicode/decoder/maxicode_decoder.rs @@ -21,7 +21,7 @@ use once_cell::sync::Lazy; use crate::{ common::{ reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder}, - BitMatrix, DecoderRXingResult, + BitMatrix, DecoderRXingResult, Result, }, DecodingHintDictionary, Exceptions, }; @@ -45,14 +45,14 @@ static RS_DECODER: Lazy = Lazy::new(|| { )) }); -pub fn decode(bits: &BitMatrix) -> Result { +pub fn decode(bits: &BitMatrix) -> Result { decode_with_hints(bits, &HashMap::new()) } pub fn decode_with_hints( bits: &BitMatrix, _hints: &DecodingHintDictionary, -) -> Result { +) -> Result { let parser = BitMatrixParser::new(bits); let mut codewords = parser.readCodewords(); @@ -88,7 +88,7 @@ fn correctErrors( dataCodewords: u32, ecCodewords: u32, mode: u32, -) -> Result<(), Exceptions> { +) -> Result<()> { let codewords = dataCodewords + ecCodewords; // in EVEN or ODD mode only half the codewords diff --git a/src/maxicode/detector.rs b/src/maxicode/detector.rs index dc67188..37391a4 100644 --- a/src/maxicode/detector.rs +++ b/src/maxicode/detector.rs @@ -4,6 +4,7 @@ use num::integer::Roots; use crate::{ common::{ detector::MathUtils, BitMatrix, DefaultGridSampler, DetectorRXingResult, GridSampler, + Result, }, Exceptions, RXingResultPoint, }; @@ -315,7 +316,7 @@ impl Circle<'_> { } } -pub fn detect(image: &BitMatrix, try_harder: bool) -> Result { +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)); @@ -711,10 +712,7 @@ const LEFT_SHIFT_PERCENT_ADJUST: f32 = 0.03; const RIGHT_SHIFT_PERCENT_ADJUST: f32 = 0.03; const ACCEPTED_SCALES: [f64; 5] = [0.065, 0.069, 0.07, 0.075, 0.08]; -fn box_symbol( - image: &BitMatrix, - circle: &mut Circle, -) -> Result<([(f32, f32); 4], f32), Exceptions> { +fn box_symbol(image: &BitMatrix, circle: &mut Circle) -> Result<([(f32, f32); 4], f32)> { let (left_boundary, right_boundary, top_boundary, bottom_boundary) = calculate_simple_boundary(circle, Some(image), None, false); @@ -1051,7 +1049,7 @@ fn compare_circle(a: &Circle, b: &Circle) -> std::cmp::Ordering { } /// Read appropriate bits from a bitmatrix for the maxicode decoder -pub fn read_bits(image: &BitMatrix) -> Result { +pub fn read_bits(image: &BitMatrix) -> Result { let enclosingRectangle = image .getEnclosingRectangle() .ok_or(Exceptions::NotFoundException(None))?; diff --git a/src/maxicode/maxi_code_reader.rs b/src/maxicode/maxi_code_reader.rs index a7f422c..1f5ab77 100644 --- a/src/maxicode/maxi_code_reader.rs +++ b/src/maxicode/maxi_code_reader.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use crate::{ - common::{BitMatrix, DetectorRXingResult}, + common::{BitMatrix, DetectorRXingResult, Result}, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, RXingResultMetadataType, Reader, }; @@ -41,10 +41,7 @@ impl Reader for MaxiCodeReader { * @throws FormatException if a MaxiCode cannot be decoded * @throws ChecksumException if error correction fails */ - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -60,7 +57,7 @@ impl Reader for MaxiCodeReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { // Note that MaxiCode reader effectively always assumes PURE_BARCODE mode // and can't detect it in an image let try_harder = matches!( @@ -123,7 +120,7 @@ impl MaxiCodeReader { * around it. This is a specialized method that works exceptionally fast in this special * case. */ - fn extractPureBits(image: &BitMatrix) -> Result { + fn extractPureBits(image: &BitMatrix) -> Result { let enclosingRectangleOption = image.getEnclosingRectangle(); if enclosingRectangleOption.is_none() { return Err(Exceptions::NotFoundException(None)); diff --git a/src/multi/by_quadrant_reader.rs b/src/multi/by_quadrant_reader.rs index 7374291..571a79a 100644 --- a/src/multi/by_quadrant_reader.rs +++ b/src/multi/by_quadrant_reader.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; +use crate::common::Result; use crate::{Exceptions, RXingResult, RXingResultPoint, Reader, ResultPoint}; /** @@ -29,10 +30,7 @@ use crate::{Exceptions, RXingResult, RXingResultPoint, Reader, ResultPoint}; */ pub struct ByQuadrantReader(T); impl Reader for ByQuadrantReader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -40,7 +38,7 @@ impl Reader for ByQuadrantReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let width = image.getWidth(); let height = image.getHeight(); let halfWidth = width / 2; diff --git a/src/multi/generic_multiple_barcode_reader.rs b/src/multi/generic_multiple_barcode_reader.rs index 301889d..2574dd7 100644 --- a/src/multi/generic_multiple_barcode_reader.rs +++ b/src/multi/generic_multiple_barcode_reader.rs @@ -17,8 +17,8 @@ use std::collections::HashMap; use crate::{ - BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult, RXingResultPoint, Reader, - ResultPoint, + common::Result, BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult, + RXingResultPoint, Reader, ResultPoint, }; use super::MultipleBarcodeReader; @@ -44,7 +44,7 @@ impl MultipleBarcodeReader for GenericMultipleBarcodeReader { fn decode_multiple( &mut self, image: &mut crate::BinaryBitmap, - ) -> Result, crate::Exceptions> { + ) -> Result> { self.decode_multiple_with_hints(image, &HashMap::new()) } @@ -52,7 +52,7 @@ impl MultipleBarcodeReader for GenericMultipleBarcodeReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result, crate::Exceptions> { + ) -> Result> { let mut results = Vec::new(); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); if results.is_empty() { diff --git a/src/multi/multiple_barcode_reader.rs b/src/multi/multiple_barcode_reader.rs index 12fecfc..191d23b 100644 --- a/src/multi/multiple_barcode_reader.rs +++ b/src/multi/multiple_barcode_reader.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult}; +use crate::{common::Result, BinaryBitmap, DecodingHintDictionary, RXingResult}; /** * Implementation of this interface attempt to read several barcodes from one image. @@ -23,12 +23,11 @@ use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult}; * @author Sean Owen */ pub trait MultipleBarcodeReader { - fn decode_multiple(&mut self, image: &mut BinaryBitmap) - -> Result, Exceptions>; + fn decode_multiple(&mut self, image: &mut BinaryBitmap) -> Result>; fn decode_multiple_with_hints( &mut self, image: &mut BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result, Exceptions>; + ) -> Result>; } diff --git a/src/multi/qrcode/detector/multi_detector.rs b/src/multi/qrcode/detector/multi_detector.rs index bd4d934..aabae83 100644 --- a/src/multi/qrcode/detector/multi_detector.rs +++ b/src/multi/qrcode/detector/multi_detector.rs @@ -15,7 +15,7 @@ */ use crate::{ - common::BitMatrix, + common::{BitMatrix, Result}, qrcode::detector::{Detector, QRCodeDetectorResult}, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, }; @@ -37,10 +37,7 @@ impl<'a> MultiDetector<'_> { // private static final DetectorRXingResult[] EMPTY_DETECTOR_RESULTS = new DetectorRXingResult[0]; - pub fn detectMulti( - &self, - hints: &DecodingHintDictionary, - ) -> Result, Exceptions> { + pub fn detectMulti(&self, hints: &DecodingHintDictionary) -> Result> { let image = self.0.getImage(); let resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) = hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK) diff --git a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs index 7e68975..d313714 100644 --- a/src/multi/qrcode/detector/multi_finder_pattern_finder.rs +++ b/src/multi/qrcode/detector/multi_finder_pattern_finder.rs @@ -17,7 +17,7 @@ use std::cmp::Ordering; use crate::{ - common::BitMatrix, + common::{BitMatrix, Result}, qrcode::detector::{FinderPattern, FinderPatternFinder, FinderPatternInfo}, result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions, RXingResultPointCallback, @@ -82,7 +82,7 @@ impl<'a> MultiFinderPatternFinder<'_> { * size differs from the average among those patterns the least * @throws NotFoundException if 3 such finder patterns do not exist */ - fn selectMultipleBestPatterns(&self) -> Result, Exceptions> { + fn selectMultipleBestPatterns(&self) -> Result> { let mut possibleCenters = Vec::new(); for fp in self.0.getPossibleCenters() { if fp.getCount() >= 2 { @@ -216,10 +216,7 @@ impl<'a> MultiFinderPatternFinder<'_> { } } - pub fn findMulti( - &mut self, - hints: &DecodingHintDictionary, - ) -> Result, Exceptions> { + pub fn findMulti(&mut self, hints: &DecodingHintDictionary) -> Result> { let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER); let image = self.0.getImage().clone(); let maxI = image.getHeight(); diff --git a/src/multi/qrcode/qr_code_multi_reader.rs b/src/multi/qrcode/qr_code_multi_reader.rs index ce0190f..67eed66 100644 --- a/src/multi/qrcode/qr_code_multi_reader.rs +++ b/src/multi/qrcode/qr_code_multi_reader.rs @@ -17,7 +17,7 @@ use std::{cmp::Ordering, collections::HashMap}; use crate::{ - common::DetectorRXingResult, + common::{DetectorRXingResult, Result}, multi::MultipleBarcodeReader, qrcode::{ decoder::{self, QRCodeDecoderMetaData}, @@ -40,7 +40,7 @@ impl MultipleBarcodeReader for QRCodeMultiReader { fn decode_multiple( &mut self, image: &mut crate::BinaryBitmap, - ) -> Result, crate::Exceptions> { + ) -> Result> { self.decode_multiple_with_hints(image, &HashMap::new()) } @@ -48,11 +48,11 @@ impl MultipleBarcodeReader for QRCodeMultiReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result, crate::Exceptions> { + ) -> Result> { let mut results = Vec::new(); let detectorRXingResults = MultiDetector::new(image.getBlackMatrix()).detectMulti(hints)?; for detectorRXingResult in detectorRXingResults { - let mut proc = || -> Result<(), Exceptions> { + let mut proc = || -> Result<()> { let decoderRXingResult = decoder::qrcode_decoder::decode_bitmatrix_with_hints( detectorRXingResult.getBits(), hints, @@ -126,7 +126,7 @@ impl QRCodeMultiReader { Self(QRCodeReader::new()) } - fn processStructuredAppend(results: Vec) -> Result, Exceptions> { + fn processStructuredAppend(results: Vec) -> Result> { let mut newRXingResults = Vec::new(); let mut saRXingResults = Vec::new(); for result in &results { diff --git a/src/multi_format_reader.rs b/src/multi_format_reader.rs index dd797c9..e74df4e 100644 --- a/src/multi_format_reader.rs +++ b/src/multi_format_reader.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; +use crate::common::Result; use crate::{ aztec::AztecReader, datamatrix::DataMatrixReader, maxicode::MaxiCodeReader, oned::MultiFormatOneDReader, pdf417::PDF417Reader, qrcode::QRCodeReader, BarcodeFormat, @@ -47,10 +48,7 @@ impl Reader for MultiFormatReader { * @return The contents of the image * @throws NotFoundException Any errors which occurred */ - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.set_ints(&HashMap::new()); self.decode_internal(image) } @@ -67,7 +65,7 @@ impl Reader for MultiFormatReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { self.set_ints(hints); self.decode_internal(image) } @@ -88,10 +86,7 @@ impl MultiFormatReader { * @return The contents of the image * @throws NotFoundException Any errors which occurred */ - pub fn decode_with_state( - &mut self, - image: &mut BinaryBitmap, - ) -> Result { + pub fn decode_with_state(&mut self, image: &mut BinaryBitmap) -> Result { // Make sure to set up the default state so we don't crash if self.readers.is_empty() { self.set_ints(&HashMap::new()); @@ -170,7 +165,7 @@ impl MultiFormatReader { self.readers = readers; } - pub fn decode_internal(&mut self, image: &mut BinaryBitmap) -> Result { + pub fn decode_internal(&mut self, image: &mut BinaryBitmap) -> Result { if !self.readers.is_empty() { for reader in self.readers.iter_mut() { let res = reader.decode_with_hints(image, &self.hints); diff --git a/src/multi_format_writer.rs b/src/multi_format_writer.rs index 8371cd7..a6e3d61 100644 --- a/src/multi_format_writer.rs +++ b/src/multi_format_writer.rs @@ -18,6 +18,7 @@ use std::collections::HashMap; use crate::{ aztec::AztecWriter, + common::Result, datamatrix::DataMatrixWriter, oned::{ CodaBarWriter, Code128Writer, Code39Writer, Code93Writer, EAN13Writer, EAN8Writer, @@ -44,7 +45,7 @@ impl Writer for MultiFormatWriter { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -55,7 +56,7 @@ impl Writer for MultiFormatWriter { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { let writer: Box = match format { BarcodeFormat::EAN_8 => Box::::default(), BarcodeFormat::UPC_E => Box::::default(), diff --git a/src/oned/coda_bar_reader.rs b/src/oned/coda_bar_reader.rs index fe3dcc8..c154e52 100644 --- a/src/oned/coda_bar_reader.rs +++ b/src/oned/coda_bar_reader.rs @@ -16,7 +16,7 @@ use rxing_one_d_proc_derive::OneDReader; -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use crate::BarcodeFormat; use crate::DecodeHintValue; use crate::Exceptions; @@ -54,7 +54,7 @@ impl OneDReader for CodaBarReader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { self.counters.fill(0); // Arrays.fill(counters, 0); self.setCounters(row)?; @@ -228,7 +228,7 @@ impl CodaBarReader { } } - fn validatePattern(&self, start: usize) -> Result<(), Exceptions> { + fn validatePattern(&self, start: usize) -> Result<()> { // First, sum up the total size of our four categories of stripe sizes; let mut sizes = [0, 0, 0, 0]; let mut counts = [0, 0, 0, 0]; @@ -305,7 +305,7 @@ impl CodaBarReader { * uses our builtin "counters" member for storage. * @param row row to count from */ - fn setCounters(&mut self, row: &BitArray) -> Result<(), Exceptions> { + fn setCounters(&mut self, row: &BitArray) -> Result<()> { self.counterLength = 0; // Start from the first white bit. let mut i = row.getNextUnset(0); @@ -339,7 +339,7 @@ impl CodaBarReader { } } - fn findStartPattern(&mut self) -> Result { + fn findStartPattern(&mut self) -> Result { let mut i = 1; while i < self.counterLength { // for (int i = 1; i < counterLength; i += 2) { diff --git a/src/oned/coda_bar_writer.rs b/src/oned/coda_bar_writer.rs index 553f51b..be15305 100644 --- a/src/oned/coda_bar_writer.rs +++ b/src/oned/coda_bar_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::{CodaBarReader, OneDimensionalCodeWriter}; @@ -34,7 +35,7 @@ const DEFAULT_GUARD: char = START_END_CHARS[0]; pub struct CodaBarWriter; impl OneDimensionalCodeWriter for CodaBarWriter { - fn encode_oned(&self, contents: &str) -> Result, crate::Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let contents = if contents.chars().count() < 2 { // Can't have a start/end guard, so tentatively add default guards format!("{DEFAULT_GUARD}{contents}{DEFAULT_GUARD}") diff --git a/src/oned/code_128_reader.rs b/src/oned/code_128_reader.rs index f9b8ca9..9898a56 100644 --- a/src/oned/code_128_reader.rs +++ b/src/oned/code_128_reader.rs @@ -16,7 +16,10 @@ use rxing_one_d_proc_derive::OneDReader; -use crate::{common::BitArray, BarcodeFormat, Exceptions, RXingResult}; +use crate::{ + common::{BitArray, Result}, + BarcodeFormat, Exceptions, RXingResult, +}; use super::{one_d_reader, OneDReader}; @@ -34,7 +37,7 @@ impl OneDReader for Code128Reader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let convertFNC1 = hints.contains_key(&DecodeHintType::ASSUME_GS1); let mut symbologyModifier = 0; @@ -354,7 +357,7 @@ impl OneDReader for Code128Reader { } } impl Code128Reader { - fn findStartPattern(&self, row: &BitArray) -> Result<[usize; 3], Exceptions> { + fn findStartPattern(&self, row: &BitArray) -> Result<[usize; 3]> { let width = row.getSize(); let rowOffset = row.getNextSet(0); @@ -410,12 +413,7 @@ impl Code128Reader { Err(Exceptions::NotFoundException(None)) } - fn decodeCode( - &self, - row: &BitArray, - counters: &mut [u32; 6], - rowOffset: usize, - ) -> Result { + fn decodeCode(&self, row: &BitArray, counters: &mut [u32; 6], rowOffset: usize) -> Result { one_d_reader::recordPattern(row, rowOffset, counters)?; let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestMatch = -1_isize; diff --git a/src/oned/code_128_writer.rs b/src/oned/code_128_writer.rs index 04a6d77..3515045 100644 --- a/src/oned/code_128_writer.rs +++ b/src/oned/code_128_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::{code_128_reader, OneDimensionalCodeWriter}; @@ -58,7 +59,7 @@ enum CType { pub struct Code128Writer; impl OneDimensionalCodeWriter for Code128Writer { - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { self.encode_oned_with_hints(contents, &HashMap::new()) } @@ -70,7 +71,7 @@ impl OneDimensionalCodeWriter for Code128Writer { &self, contents: &str, hints: &crate::EncodingHintDictionary, - ) -> Result, Exceptions> { + ) -> Result> { let forcedCodeSet = check(contents, hints)?; let hasCompactionHint = matches!( @@ -95,7 +96,7 @@ impl OneDimensionalCodeWriter for Code128Writer { } } -fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { +fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result { let length = contents.chars().count(); // Check length if !(1..=80).contains(&length) { @@ -183,7 +184,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result Result, Exceptions> { +fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result> { let length = contents.chars().count(); let mut patterns: Vec> = Vec::new(); //new ArrayList<>(); // temporary storage for patterns @@ -442,7 +443,7 @@ fn chooseCode(value: &str, start: usize, oldCode: usize) -> Option { // minPath:Vec>, // } mod MinimalEncoder { - use crate::{oned::code_128_reader, Exceptions}; + use crate::{common::Result, oned::code_128_reader, Exceptions}; use super::{ produceRXingResult, CODE_CODE_A, CODE_CODE_B, CODE_CODE_C, CODE_FNC_1, CODE_FNC_2, @@ -476,7 +477,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; const CODE_SHIFT: usize = 98; - pub fn encode(contents: &str) -> Result, Exceptions> { + pub fn encode(contents: &str) -> Result> { let length = contents.chars().count(); let mut memoizedCost = vec![vec![0_u32; length]; 4]; //new int[4][contents.length()]; let mut minPath = vec![vec![Latch::None; length]; 4]; //new Latch[4][contents.length()]; @@ -680,7 +681,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}"; position: usize, memoizedCost: &mut Vec>, minPath: &mut Vec>, - ) -> Result { + ) -> Result { if position >= contents.chars().count() { return Err(Exceptions::IllegalStateException(None)); } diff --git a/src/oned/code_128_writer_test_tase.rs b/src/oned/code_128_writer_test_tase.rs index 5ff3f7b..e82a838 100644 --- a/src/oned/code_128_writer_test_tase.rs +++ b/src/oned/code_128_writer_test_tase.rs @@ -37,9 +37,9 @@ use std::collections::HashMap; use once_cell::sync::Lazy; use crate::{ - common::{bit_matrix_test_case, BitMatrix}, + common::{bit_matrix_test_case, BitMatrix, Result}, oned::{Code128Reader, OneDReader}, - BarcodeFormat, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Exceptions, Writer, + BarcodeFormat, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Writer, }; use super::Code128Writer; @@ -469,7 +469,7 @@ fn testEncodeWithForcedCodeSetFailureCodeSetB() { assert_eq!(expected, actual); } -fn encode(toEncode: &str, compact: bool, expectedLoopback: &str) -> Result { +fn encode(toEncode: &str, compact: bool, expectedLoopback: &str) -> Result { let mut reader = Code128Reader::default(); let mut hints: EncodingHintDictionary = HashMap::new(); diff --git a/src/oned/code_39_reader.rs b/src/oned/code_39_reader.rs index 6a80c1a..56060bd 100644 --- a/src/oned/code_39_reader.rs +++ b/src/oned/code_39_reader.rs @@ -16,7 +16,7 @@ use rxing_one_d_proc_derive::OneDReader; -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use crate::{BarcodeFormat, Exceptions, RXingResult}; use super::{one_d_reader, OneDReader}; @@ -45,7 +45,7 @@ impl OneDReader for Code39Reader { rowNumber: u32, row: &crate::common::BitArray, _hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { let mut counters = [0_u32; 9]; self.decodeRowRXingResult.clear(); @@ -204,7 +204,7 @@ impl Code39Reader { } } - fn findAsteriskPattern(row: &BitArray, counters: &mut [u32]) -> Result, Exceptions> { + fn findAsteriskPattern(row: &BitArray, counters: &mut [u32]) -> Result> { let width = row.getSize(); let rowOffset = row.getNextSet(0); @@ -300,7 +300,7 @@ impl Code39Reader { -1 } - fn patternToChar(pattern: u32) -> Result { + fn patternToChar(pattern: u32) -> Result { for i in 0..Self::CHARACTER_ENCODINGS.len() { if Self::CHARACTER_ENCODINGS[i] == pattern { return Self::ALPHABET_STRING @@ -315,7 +315,7 @@ impl Code39Reader { Err(Exceptions::NotFoundException(None)) } - fn decodeExtended(encoded: &str) -> Result { + fn decodeExtended(encoded: &str) -> Result { let length = encoded.chars().count(); let mut decoded = String::with_capacity(length); //new StringBuilder(length); let mut i = 0; diff --git a/src/oned/code_39_writer.rs b/src/oned/code_39_writer.rs index c7bc102..f88a05a 100644 --- a/src/oned/code_39_writer.rs +++ b/src/oned/code_39_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::{Code39Reader, OneDimensionalCodeWriter}; @@ -29,7 +30,7 @@ use super::{Code39Reader, OneDimensionalCodeWriter}; pub struct Code39Writer; impl OneDimensionalCodeWriter for Code39Writer { - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let mut contents = contents.to_owned(); let mut length = contents.chars().count(); if length > 80 { @@ -99,7 +100,7 @@ impl Code39Writer { } } - fn tryToConvertToExtendedMode(contents: &str) -> Result { + fn tryToConvertToExtendedMode(contents: &str) -> Result { // let length = contents.chars().count(); let mut extendedContent = String::new(); //new StringBuilder(); for character in contents.chars() { diff --git a/src/oned/code_93_reader.rs b/src/oned/code_93_reader.rs index 5f73fcb..415cb80 100644 --- a/src/oned/code_93_reader.rs +++ b/src/oned/code_93_reader.rs @@ -16,7 +16,10 @@ use rxing_one_d_proc_derive::OneDReader; -use crate::{common::BitArray, BarcodeFormat, Exceptions, RXingResult}; +use crate::{ + common::{BitArray, Result}, + BarcodeFormat, Exceptions, RXingResult, +}; use super::{one_d_reader, OneDReader}; @@ -47,7 +50,7 @@ impl OneDReader for Code93Reader { rowNumber: u32, row: &crate::common::BitArray, _hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let start = self.findAsteriskPattern(row)?; // Read off white space let mut nextStart = row.getNextSet(start[1]); @@ -159,7 +162,7 @@ impl Code93Reader { } } - fn findAsteriskPattern(&mut self, row: &BitArray) -> Result<[usize; 2], Exceptions> { + fn findAsteriskPattern(&mut self, row: &BitArray) -> Result<[usize; 2]> { let width = row.getSize(); let rowOffset = row.getNextSet(0); @@ -215,7 +218,7 @@ impl Code93Reader { pattern } - fn patternToChar(pattern: u32) -> Result { + fn patternToChar(pattern: u32) -> Result { for i in 0..Self::CHARACTER_ENCODINGS.len() { if Self::CHARACTER_ENCODINGS[i] == pattern { return Ok(Self::ALPHABET[i]); @@ -224,7 +227,7 @@ impl Code93Reader { Err(Exceptions::NotFoundException(None)) } - fn decodeExtended(encoded: &str) -> Result { + fn decodeExtended(encoded: &str) -> Result { let length = encoded.chars().count(); let mut decoded = String::with_capacity(length); let mut i = 0; @@ -321,18 +324,14 @@ impl Code93Reader { Ok(decoded) } - fn checkChecksums(result: &str) -> Result<(), Exceptions> { + fn checkChecksums(result: &str) -> Result<()> { let length = result.chars().count(); Self::checkOneChecksum(result, length - 2, 20)?; Self::checkOneChecksum(result, length - 1, 15)?; Ok(()) } - fn checkOneChecksum( - result: &str, - checkPosition: usize, - weightMax: u32, - ) -> Result<(), Exceptions> { + fn checkOneChecksum(result: &str, checkPosition: usize, weightMax: u32) -> Result<()> { let mut weight = 1; let mut total = 0; for i in (0..checkPosition).rev() { diff --git a/src/oned/code_93_writer.rs b/src/oned/code_93_writer.rs index be3b7ae..232f12a 100644 --- a/src/oned/code_93_writer.rs +++ b/src/oned/code_93_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::{Code93Reader, OneDimensionalCodeWriter}; @@ -31,7 +32,7 @@ impl OneDimensionalCodeWriter for Code93Writer { * @param contents barcode contents to encode. It should not be encoded for extended characters. * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let mut contents = Self::convertToExtended(contents)?; let length = contents.chars().count(); if length > 80 { @@ -142,7 +143,7 @@ impl Code93Writer { total as usize % 47 } - fn convertToExtended(contents: &str) -> Result { + fn convertToExtended(contents: &str) -> Result { let length = contents.chars().count(); let mut extendedContent = String::with_capacity(length * 2); for character in contents.chars() { diff --git a/src/oned/ean_13_reader.rs b/src/oned/ean_13_reader.rs index 809cb54..551339f 100644 --- a/src/oned/ean_13_reader.rs +++ b/src/oned/ean_13_reader.rs @@ -21,6 +21,7 @@ use super::UPCEANReader; use super::upc_ean_reader; use super::OneDReader; +use crate::common::Result; use crate::BarcodeFormat; use crate::Exceptions; @@ -43,7 +44,7 @@ impl UPCEANReader for EAN13Reader { row: &crate::common::BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result { + ) -> Result { let mut counters = [0_u32; 4]; //decodeMiddleCounters; // counters[0] = 0; // counters[1] = 0; @@ -145,10 +146,7 @@ impl EAN13Reader { * encode digits * @throws NotFoundException if first digit cannot be determined */ - fn determineFirstDigit( - resultString: &mut String, - lgPatternFound: usize, - ) -> Result<(), Exceptions> { + fn determineFirstDigit(resultString: &mut String, lgPatternFound: usize) -> Result<()> { for d in 0..10 { // for (int d = 0; d < 10; d++) { if lgPatternFound == Self::FIRST_DIGIT_ENCODINGS[d] { diff --git a/src/oned/ean_13_writer.rs b/src/oned/ean_13_writer.rs index 26a0942..b180c40 100644 --- a/src/oned/ean_13_writer.rs +++ b/src/oned/ean_13_writer.rs @@ -17,6 +17,7 @@ use rxing_one_d_proc_derive::OneDWriter; use crate::{ + common::Result, oned::{upc_ean_reader, EAN13Reader}, BarcodeFormat, }; @@ -33,7 +34,7 @@ pub struct EAN13Writer; impl UPCEANWriter for EAN13Writer {} impl OneDimensionalCodeWriter for EAN13Writer { - fn encode_oned(&self, contents: &str) -> Result, crate::Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let reader: EAN13Reader = EAN13Reader::default(); let mut contents = contents.to_owned(); let length = contents.chars().count(); diff --git a/src/oned/ean_8_reader.rs b/src/oned/ean_8_reader.rs index 5e20ab3..c32528d 100644 --- a/src/oned/ean_8_reader.rs +++ b/src/oned/ean_8_reader.rs @@ -15,6 +15,7 @@ */ use super::OneDReader; +use crate::common::Result; use crate::{BarcodeFormat, Exceptions}; use rxing_one_d_proc_derive::{EANReader, OneDReader}; @@ -39,7 +40,7 @@ impl UPCEANReader for EAN8Reader { row: &crate::common::BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result { + ) -> Result { let mut counters = [0_u32; 4]; //decodeMiddleCounters; // counters[0] = 0; // counters[1] = 0; diff --git a/src/oned/ean_8_writer.rs b/src/oned/ean_8_writer.rs index e329d46..6871a1f 100644 --- a/src/oned/ean_8_writer.rs +++ b/src/oned/ean_8_writer.rs @@ -17,6 +17,7 @@ use rxing_one_d_proc_derive::OneDWriter; use crate::{ + common::Result, oned::{EAN8Reader, UPCEANReader}, BarcodeFormat, }; @@ -42,7 +43,7 @@ impl OneDimensionalCodeWriter for EAN8Writer { /** * @return a byte array of horizontal pixels (false = white, true = black) */ - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let length = contents.chars().count(); let reader = EAN8Reader::default(); let mut contents = contents.to_owned(); diff --git a/src/oned/itf_reader.rs b/src/oned/itf_reader.rs index 0f13089..41de313 100644 --- a/src/oned/itf_reader.rs +++ b/src/oned/itf_reader.rs @@ -16,7 +16,10 @@ use rxing_one_d_proc_derive::OneDReader; -use crate::{common::BitArray, BarcodeFormat, DecodeHintValue, Exceptions, RXingResult}; +use crate::{ + common::{BitArray, Result}, + BarcodeFormat, DecodeHintValue, Exceptions, RXingResult, +}; use super::{one_d_reader, OneDReader}; @@ -106,7 +109,7 @@ impl OneDReader for ITFReader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { // Find out where the Middle section (payload) starts & ends let mut row = row.clone(); let startRange = self.decodeStart(&row)?; @@ -174,7 +177,7 @@ impl ITFReader { payloadStart: usize, payloadEnd: usize, resultString: &mut String, - ) -> Result<(), Exceptions> { + ) -> Result<()> { let mut payloadStart = payloadStart; // Digits are interleaved in pairs - 5 black lines for one digit, and the // 5 interleaved white lines for the second digit. @@ -216,7 +219,7 @@ impl ITFReader { * @return Array, containing index of start of 'start block' and end of * 'start block' */ - fn decodeStart(&mut self, row: &BitArray) -> Result<[usize; 2], Exceptions> { + fn decodeStart(&mut self, row: &BitArray) -> Result<[usize; 2]> { let endStart = Self::skipWhiteSpace(row)?; let startPattern = self.findGuardPattern(row, endStart, &START_PATTERN)?; @@ -245,7 +248,7 @@ impl ITFReader { * @param startPattern index into row of the start or end pattern. * @throws NotFoundException if the quiet zone cannot be found */ - fn validateQuietZone(&self, row: &BitArray, startPattern: usize) -> Result<(), Exceptions> { + fn validateQuietZone(&self, row: &BitArray, startPattern: usize) -> Result<()> { let mut quietCount = self.narrowLineWidth * 10; // expect to find this many pixels of quiet zone // if there are not so many pixel at all let's try as many as possible @@ -275,7 +278,7 @@ impl ITFReader { * @return index of the first black line. * @throws NotFoundException Throws exception if no black lines are found in the row */ - fn skipWhiteSpace(row: &BitArray) -> Result { + fn skipWhiteSpace(row: &BitArray) -> Result { let width = row.getSize(); let endStart = row.getNextSet(0); if endStart == width { @@ -292,11 +295,11 @@ impl ITFReader { * @return Array, containing index of start of 'end block' and end of 'end * block' */ - fn decodeEnd(&self, row: &mut BitArray) -> Result<[usize; 2], Exceptions> { + fn decodeEnd(&self, row: &mut BitArray) -> Result<[usize; 2]> { // For convenience, reverse the row and then // search from 'the start' for the end block row.reverse(); - let interim_function = || -> Result<[usize; 2], Exceptions> { + let interim_function = || -> Result<[usize; 2]> { let endStart = Self::skipWhiteSpace(row)?; let mut endPattern = if let Ok(ptrn) = self.findGuardPattern(row, endStart, &END_PATTERN_REVERSED[0]) { @@ -339,7 +342,7 @@ impl ITFReader { row: &BitArray, rowOffset: usize, pattern: &[u32], - ) -> Result<[usize; 2], Exceptions> { + ) -> Result<[usize; 2]> { let patternLength = pattern.len(); let mut counters = vec![0u32; patternLength]; //new int[patternLength]; let width = row.getSize(); @@ -385,7 +388,7 @@ impl ITFReader { * @return The decoded digit * @throws NotFoundException if digit cannot be decoded */ - fn decodeDigit(&self, counters: &[u32]) -> Result { + fn decodeDigit(&self, counters: &[u32]) -> Result { let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestMatch = -1_isize; let max = PATTERNS.len(); diff --git a/src/oned/itf_writer.rs b/src/oned/itf_writer.rs index 2363d25..9104aff 100644 --- a/src/oned/itf_writer.rs +++ b/src/oned/itf_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::OneDimensionalCodeWriter; @@ -29,7 +30,7 @@ use super::OneDimensionalCodeWriter; pub struct ITFWriter; impl OneDimensionalCodeWriter for ITFWriter { - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let length = contents.chars().count(); if length % 2 != 0 { return Err(Exceptions::IllegalArgumentException(Some( diff --git a/src/oned/multi_format_one_d_reader.rs b/src/oned/multi_format_one_d_reader.rs index 8248e44..b0c7eb4 100644 --- a/src/oned/multi_format_one_d_reader.rs +++ b/src/oned/multi_format_one_d_reader.rs @@ -23,6 +23,7 @@ use super::Code93Reader; use super::ITFReader; use super::MultiFormatUPCEANReader; use super::OneDReader; +use crate::common::Result; use crate::BarcodeFormat; use crate::DecodeHintValue; use crate::Exceptions; @@ -39,7 +40,7 @@ impl OneDReader for MultiFormatOneDReader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { for reader in self.0.iter_mut() { if let Ok(res) = reader.decodeRow(rowNumber, row, hints) { return Ok(res); @@ -113,10 +114,7 @@ use crate::Reader; use std::collections::HashMap; impl Reader for MultiFormatOneDReader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -125,7 +123,7 @@ impl Reader for MultiFormatOneDReader { &mut self, image: &mut crate::BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { let first_try = self.doDecode(image, hints); if first_try.is_ok() { return first_try; diff --git a/src/oned/multi_format_upc_ean_reader.rs b/src/oned/multi_format_upc_ean_reader.rs index 25d5a3a..fb8b817 100644 --- a/src/oned/multi_format_upc_ean_reader.rs +++ b/src/oned/multi_format_upc_ean_reader.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::BarcodeFormat; use crate::DecodeHintValue; use crate::Exceptions; @@ -74,7 +75,7 @@ impl MultiFormatUPCEANReader { row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, startGuardPattern: &[usize; 2], - ) -> Result { + ) -> Result { let result = reader.decodeRowWithGuardRange(rowNumber, row, startGuardPattern, hints)?; // Special case: a 12-digit code encoded in UPC-A is identical to a "0" // followed by those 12 digits encoded as EAN-13. Each will recognize such a code, @@ -122,7 +123,7 @@ impl OneDReader for MultiFormatUPCEANReader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { // Compute this location once and reuse it on multiple implementations let startGuardPattern = STAND_IN.findStartGuardPattern(row)?; for reader in &self.0 { @@ -145,10 +146,7 @@ use crate::RXingResultMetadataValue; use std::collections::HashMap; impl Reader for MultiFormatUPCEANReader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -157,7 +155,7 @@ impl Reader for MultiFormatUPCEANReader { &mut self, image: &mut crate::BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { let first_try = self.doDecode(image, hints); if first_try.is_ok() { return first_try; diff --git a/src/oned/one_d_code_writer.rs b/src/oned/one_d_code_writer.rs index 50d7e40..5fb9655 100644 --- a/src/oned/one_d_code_writer.rs +++ b/src/oned/one_d_code_writer.rs @@ -17,7 +17,8 @@ use std::collections::HashMap; use crate::{ - common::BitMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, + common::{BitMatrix, Result}, + BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, }; use once_cell::sync::Lazy; @@ -40,7 +41,7 @@ pub trait OneDimensionalCodeWriter: Writer { * @param contents barcode contents to encode * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ - fn encode_oned(&self, contents: &str) -> Result, Exceptions>; + fn encode_oned(&self, contents: &str) -> Result>; /** * Can be overwritten if the encode requires to read the hints map. Otherwise it defaults to {@code encode}. @@ -52,7 +53,7 @@ pub trait OneDimensionalCodeWriter: Writer { &self, contents: &str, _hints: &crate::EncodingHintDictionary, - ) -> Result, Exceptions> { + ) -> Result> { self.encode_oned(contents) } @@ -68,7 +69,7 @@ pub trait OneDimensionalCodeWriter: Writer { width: i32, height: i32, sidesMargin: u32, - ) -> Result { + ) -> Result { let inputWidth = code.len(); // Add quiet zone on both sides. let fullWidth = inputWidth + sidesMargin as usize; @@ -98,7 +99,7 @@ pub trait OneDimensionalCodeWriter: Writer { * @param contents string to check for numeric characters * @throws IllegalArgumentException if input contains characters other than digits 0-9. */ - fn checkNumeric(contents: &str) -> Result<(), Exceptions> { + fn checkNumeric(contents: &str) -> Result<()> { if !NUMERIC.is_match(contents) { Err(Exceptions::IllegalArgumentException(Some( "Input should only contain digits 0-9".to_owned(), @@ -150,7 +151,7 @@ impl Writer for L { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -161,7 +162,7 @@ impl Writer for L { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { if contents.is_empty() { return Err(Exceptions::IllegalArgumentException(Some( "Found empty contents".to_owned(), @@ -195,7 +196,7 @@ impl Writer for L { } impl OneDimensionalCodeWriter for L { - fn encode_oned(&self, _contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, _contents: &str) -> Result> { todo!() } } diff --git a/src/oned/one_d_reader.rs b/src/oned/one_d_reader.rs index fd0adcc..091ed1a 100644 --- a/src/oned/one_d_reader.rs +++ b/src/oned/one_d_reader.rs @@ -15,9 +15,9 @@ */ use crate::{ - common::BitArray, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, - Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, - Reader, ResultPoint, + common::{BitArray, Result}, + BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, RXingResult, + RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, ResultPoint, }; /** @@ -46,7 +46,7 @@ pub trait OneDReader: Reader { &mut self, image: &mut BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { let mut hints = hints.clone(); let width = image.getWidth(); let height = image.getHeight(); @@ -151,7 +151,7 @@ pub trait OneDReader: Reader { rowNumber: u32, row: &BitArray, hints: &DecodingHintDictionary, - ) -> Result; + ) -> Result; } /** @@ -212,7 +212,7 @@ pub fn patternMatchVariance(counters: &[u32], pattern: &[u32], maxIndividualVari * @throws NotFoundException if counters cannot be filled entirely from row before running out * of pixels */ -pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Result<(), Exceptions> { +pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Result<()> { let numCounters = counters.len(); counters.fill(0); @@ -246,11 +246,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu Ok(()) } -pub fn recordPatternInReverse( - row: &BitArray, - start: usize, - counters: &mut [u32], -) -> Result<(), Exceptions> { +pub fn recordPatternInReverse(row: &BitArray, start: usize, counters: &mut [u32]) -> Result<()> { let mut start = start; // This could be more efficient I guess let mut numTransitionsLeft = counters.len() as isize; diff --git a/src/oned/rss/abstract_rss_reader.rs b/src/oned/rss/abstract_rss_reader.rs index 5e2ee2d..20b8a25 100644 --- a/src/oned/rss/abstract_rss_reader.rs +++ b/src/oned/rss/abstract_rss_reader.rs @@ -15,6 +15,7 @@ */ use crate::{ + common::Result, oned::{one_d_reader, OneDReader}, Exceptions, }; @@ -30,7 +31,7 @@ pub trait AbstractRSSReaderTrait: OneDReader { const MIN_FINDER_PATTERN_RATIO: f32 = 9.5 / 12.0; const MAX_FINDER_PATTERN_RATIO: f32 = 12.5 / 14.0; - fn parseFinderValue(counters: &[u32], finderPatterns: &[[u32; 4]]) -> Result { + fn parseFinderValue(counters: &[u32], finderPatterns: &[[u32; 4]]) -> Result { for (value, pattern) in finderPatterns.iter().enumerate() { if one_d_reader::patternMatchVariance(counters, pattern, Self::MAX_INDIVIDUAL_VARIANCE) < Self::MAX_AVG_VARIANCE diff --git a/src/oned/rss/expanded/binary_util.rs b/src/oned/rss/expanded/binary_util.rs index b183bd9..799fec2 100644 --- a/src/oned/rss/expanded/binary_util.rs +++ b/src/oned/rss/expanded/binary_util.rs @@ -30,7 +30,10 @@ use once_cell::sync::Lazy; use regex::Regex; -use crate::{common::BitArray, Exceptions}; +use crate::{ + common::{BitArray, Result}, + Exceptions, +}; static ONE: Lazy = Lazy::new(|| Regex::new("1").unwrap()); static ZERO: Lazy = Lazy::new(|| Regex::new("0").unwrap()); @@ -39,7 +42,7 @@ static SPACE: Lazy = Lazy::new(|| Regex::new(" ").unwrap()); /* * Constructs a BitArray from a String like the one returned from BitArray.toString() */ -pub fn buildBitArrayFromString(data: &str) -> Result { +pub fn buildBitArrayFromString(data: &str) -> Result { let dotsAndXs = ZERO .replace_all(&ONE.replace_all(data, "X"), ".") .to_string(); @@ -75,7 +78,7 @@ pub fn buildBitArrayFromString(data: &str) -> Result { Ok(binary) } -pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result { +pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result { let mut sb = String::new(); // let dotsAndXs = ZERO.matcher(ONE.matcher(data).replaceAll("X")).replaceAll("."); diff --git a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs index 62d15d3..3633463 100644 --- a/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs +++ b/src/oned/rss/expanded/decoders/abstract_expanded_decoder.rs @@ -24,7 +24,10 @@ * http://www.piramidepse.com/ */ -use crate::{common::BitArray, Exceptions}; +use crate::{ + common::{BitArray, Result}, + Exceptions, +}; use super::{ AI013103decoder, AI01320xDecoder, AI01392xDecoder, AI01393xDecoder, AI013x0x1xDecoder, @@ -53,14 +56,14 @@ pub trait AbstractExpandedDecoder { // return generalDecoder; // } - fn parseInformation(&mut self) -> Result; + fn parseInformation(&mut self) -> Result; fn getGeneralDecoder(&self) -> &GeneralAppIdDecoder; // fn new(information:&BitArray) -> Self where Self:Sized; } pub fn createDecoder<'a>( information: &'a BitArray, -) -> Result, Exceptions> { +) -> Result> { if information.get(1) { return Ok(Box::new(AI01AndOtherAIs::new(information))); } diff --git a/src/oned/rss/expanded/decoders/ai_013103_decoder.rs b/src/oned/rss/expanded/decoders/ai_013103_decoder.rs index 1b63c39..feea75a 100644 --- a/src/oned/rss/expanded/decoders/ai_013103_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013103_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI013x0xDecoder, AI01decoder, AI01weightDecoder, AbstractExpandedDecoder}; @@ -43,7 +43,7 @@ impl AI01weightDecoder for AI013103decoder<'_> { } } impl AbstractExpandedDecoder for AI013103decoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { self.0.parseInformation() } diff --git a/src/oned/rss/expanded/decoders/ai_01320x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01320x_decoder.rs index ad990af..c44940b 100644 --- a/src/oned/rss/expanded/decoders/ai_01320x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01320x_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI013x0xDecoder, AI01decoder, AI01weightDecoder, AbstractExpandedDecoder}; @@ -43,7 +43,7 @@ impl AI01weightDecoder for AI01320xDecoder<'_> { } } impl AbstractExpandedDecoder for AI01320xDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { self.0.parseInformation() } diff --git a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs index 4e487d4..f202c02 100644 --- a/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01392x_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI01decoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -37,7 +37,7 @@ pub struct AI01392xDecoder<'a> { } impl AI01decoder for AI01392xDecoder<'_> {} impl AbstractExpandedDecoder for AI01392xDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { return Err(crate::Exceptions::NotFoundException(None)); } diff --git a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs index d6dbd9b..898005b 100644 --- a/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_01393x_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI01decoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -37,7 +37,7 @@ pub struct AI01393xDecoder<'a> { } impl AI01decoder for AI01393xDecoder<'_> {} impl AbstractExpandedDecoder for AI01393xDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize { return Err(crate::Exceptions::NotFoundException(None)); } diff --git a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs index ab25f1f..35a3e61 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x1x_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI01decoder, AI01weightDecoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -53,7 +53,7 @@ impl AI01weightDecoder for AI013x0x1xDecoder<'_> { } impl AI01decoder for AI013x0x1xDecoder<'_> {} impl AbstractExpandedDecoder for AI013x0x1xDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE + Self::DATE_SIZE { diff --git a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs index 0c70233..33476d1 100644 --- a/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs +++ b/src/oned/rss/expanded/decoders/ai_013x0x_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI01decoder, AI01weightDecoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -49,7 +49,7 @@ impl AI01weightDecoder for AI013x0xDecoder<'_> { } } impl AbstractExpandedDecoder for AI013x0xDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { if self.information.getSize() != Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE { diff --git a/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs b/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs index 74e93fa..5ceffb5 100644 --- a/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs +++ b/src/oned/rss/expanded/decoders/ai_01_and_other_ais.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AI01decoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -35,7 +35,7 @@ use super::{AI01decoder, AbstractExpandedDecoder, GeneralAppIdDecoder}; pub struct AI01AndOtherAIs<'a>(&'a BitArray, GeneralAppIdDecoder<'a>); impl AI01decoder for AI01AndOtherAIs<'_> {} impl AbstractExpandedDecoder for AI01AndOtherAIs<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { let mut buff = String::new(); buff.push_str("(01)"); diff --git a/src/oned/rss/expanded/decoders/any_ai_decoder.rs b/src/oned/rss/expanded/decoders/any_ai_decoder.rs index f3c20ad..4ef4307 100644 --- a/src/oned/rss/expanded/decoders/any_ai_decoder.rs +++ b/src/oned/rss/expanded/decoders/any_ai_decoder.rs @@ -24,7 +24,7 @@ * http://www.piramidepse.com/ */ -use crate::common::BitArray; +use crate::common::{BitArray, Result}; use super::{AbstractExpandedDecoder, GeneralAppIdDecoder}; @@ -37,7 +37,7 @@ pub struct AnyAIDecoder<'a> { general_decoder: GeneralAppIdDecoder<'a>, } impl AbstractExpandedDecoder for AnyAIDecoder<'_> { - fn parseInformation(&mut self) -> Result { + fn parseInformation(&mut self) -> Result { let buf = String::new(); self.general_decoder.decodeAllCodes(buf, Self::HEADER_SIZE) } diff --git a/src/oned/rss/expanded/decoders/decoded_numeric.rs b/src/oned/rss/expanded/decoders/decoded_numeric.rs index ed32120..5201af8 100644 --- a/src/oned/rss/expanded/decoders/decoded_numeric.rs +++ b/src/oned/rss/expanded/decoders/decoded_numeric.rs @@ -24,6 +24,7 @@ * http://www.piramidepse.com/ */ +use crate::common::Result; use crate::Exceptions; use super::DecodedObject; @@ -45,7 +46,7 @@ impl DecodedObject for DecodedNumeric { impl DecodedNumeric { pub const FNC1: u32 = 10; - pub fn new(newPosition: usize, firstDigit: u32, secondDigit: u32) -> Result { + pub fn new(newPosition: usize, firstDigit: u32, secondDigit: u32) -> Result { // super(newPosition); if diff --git a/src/oned/rss/expanded/decoders/field_parser.rs b/src/oned/rss/expanded/decoders/field_parser.rs index e38a856..8e2f42a 100644 --- a/src/oned/rss/expanded/decoders/field_parser.rs +++ b/src/oned/rss/expanded/decoders/field_parser.rs @@ -29,6 +29,7 @@ */ use std::collections::HashMap; +use crate::common::Result; use crate::Exceptions; use once_cell::sync::Lazy; @@ -137,7 +138,7 @@ static FOUR_DIGIT_DATA_LENGTH: Lazy> = Lazy::new(|| hm }); -pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { +pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result { if rawInformation.is_empty() { return Ok(String::default()); } @@ -194,11 +195,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result Result { +fn processFixedAI(aiSize: usize, fieldSize: usize, rawInformation: &str) -> Result { if rawInformation.chars().count() < aiSize { return Err(Exceptions::NotFoundException(None)); } @@ -229,7 +226,7 @@ fn processVariableAI( aiSize: usize, variableFieldSize: usize, rawInformation: &str, -) -> Result { +) -> Result { let ai: String = rawInformation.chars().take(aiSize).collect(); let maxSize = rawInformation .chars() 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..257d8e2 100644 --- a/src/oned/rss/expanded/decoders/general_app_id_decoder.rs +++ b/src/oned/rss/expanded/decoders/general_app_id_decoder.rs @@ -24,7 +24,10 @@ * http://www.piramidepse.com/ */ -use crate::{common::BitArray, Exceptions}; +use crate::{ + common::{BitArray, Result}, + Exceptions, +}; use super::{ field_parser, BlockParsedRXingResult, CurrentParsingState, DecodedChar, DecodedInformation, @@ -50,11 +53,7 @@ impl<'a> GeneralAppIdDecoder<'_> { } } - pub fn decodeAllCodes( - &mut self, - buff: String, - initialPosition: usize, - ) -> Result { + pub fn decodeAllCodes(&mut self, buff: String, initialPosition: usize) -> Result { let mut buff = buff; let mut currentPosition = initialPosition; let mut remaining = String::default(); @@ -97,7 +96,7 @@ impl<'a> GeneralAppIdDecoder<'_> { self.information.get(pos + 3) } - fn decodeNumeric(&self, pos: usize) -> Result { + fn decodeNumeric(&self, pos: usize) -> Result { if pos + 7 > self.information.getSize() { let numeric = self.extractNumericValueFromBitArray(pos, 4); if numeric == 0 { @@ -144,7 +143,7 @@ impl<'a> GeneralAppIdDecoder<'_> { &mut self, pos: usize, remaining: &str, - ) -> Result { + ) -> Result { self.buffer.clear(); if !remaining.is_empty() { @@ -168,7 +167,7 @@ impl<'a> GeneralAppIdDecoder<'_> { )) } - fn parseBlocks(&mut self) -> Result { + fn parseBlocks(&mut self) -> Result { let mut isFinished; let mut result: BlockParsedRXingResult; loop { @@ -203,7 +202,7 @@ impl<'a> GeneralAppIdDecoder<'_> { } } - fn parseNumericBlock(&mut self) -> Result { + fn parseNumericBlock(&mut self) -> Result { while self.isStillNumeric(self.current.getPosition()) { let numeric = self.decodeNumeric(self.current.getPosition())?; self.current.setPosition(numeric.getNewPosition()); @@ -244,7 +243,7 @@ impl<'a> GeneralAppIdDecoder<'_> { Ok(BlockParsedRXingResult::new()) } - fn parseIsoIec646Block(&mut self) -> Result { + fn parseIsoIec646Block(&mut self) -> Result { while self.isStillIsoIec646(self.current.getPosition()) { let iso = self.decodeIsoIec646(self.current.getPosition())?; self.current.setPosition(iso.getNewPosition()); @@ -275,7 +274,7 @@ impl<'a> GeneralAppIdDecoder<'_> { Ok(BlockParsedRXingResult::new()) } - fn parseAlphaBlock(&mut self) -> Result { + fn parseAlphaBlock(&mut self) -> Result { while self.isStillAlpha(self.current.getPosition()) { let alpha = self.decodeAlphanumeric(self.current.getPosition())?; self.current.setPosition(alpha.getNewPosition()); @@ -336,7 +335,7 @@ impl<'a> GeneralAppIdDecoder<'_> { (232..253).contains(&eightBitValue) } - fn decodeIsoIec646(&self, pos: usize) -> Result { + fn decodeIsoIec646(&self, pos: usize) -> Result { let fiveBitValue = self.extractNumericValueFromBitArray(pos, 5); if fiveBitValue == 15 { return Ok(DecodedChar::new(pos + 5, DecodedChar::FNC1)); @@ -415,7 +414,7 @@ impl<'a> GeneralAppIdDecoder<'_> { (16..63).contains(&sixBitValue) // 63 not included } - fn decodeAlphanumeric(&self, pos: usize) -> Result { + fn decodeAlphanumeric(&self, pos: usize) -> Result { let fiveBitValue = self.extractNumericValueFromBitArray(pos, 5); if fiveBitValue == 15 { return Ok(DecodedChar::new(pos + 5, DecodedChar::FNC1)); diff --git a/src/oned/rss/expanded/rss_expanded_reader.rs b/src/oned/rss/expanded/rss_expanded_reader.rs index c6381cd..62a94a3 100644 --- a/src/oned/rss/expanded/rss_expanded_reader.rs +++ b/src/oned/rss/expanded/rss_expanded_reader.rs @@ -27,7 +27,7 @@ use std::collections::HashMap; use crate::{ - common::BitArray, + common::{BitArray, Result}, oned::{ recordPattern, recordPatternInReverse, rss::{ @@ -156,7 +156,7 @@ impl OneDReader for RSSExpandedReader { rowNumber: u32, row: &crate::common::BitArray, _hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { // Rows can start with even pattern in case in prev rows there where odd number of patters. // So lets try twice self.pairs.clear(); @@ -173,10 +173,7 @@ impl OneDReader for RSSExpandedReader { } } impl Reader for RSSExpandedReader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -185,7 +182,7 @@ impl Reader for RSSExpandedReader { &mut self, image: &mut crate::BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { if let Ok(res) = self.doDecode(image, hints) { Ok(res) } else { @@ -289,7 +286,7 @@ impl RSSExpandedReader { &mut self, rowNumber: u32, row: &BitArray, - ) -> Result, Exceptions> { + ) -> Result> { let mut done = false; while !done { let previousPairs = self.pairs.clone(); @@ -372,7 +369,7 @@ impl RSSExpandedReader { &mut self, collectedRows: &mut Vec, currentRow: usize, - ) -> Result, Exceptions> { + ) -> Result> { for i in currentRow..self.rows.len() { // for (int i = currentRow; i < rows.size(); i++) { let row = self @@ -535,7 +532,7 @@ impl RSSExpandedReader { } // Not private for unit testing - pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result { + pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result { let binary = bit_array_builder::buildBitArray(&pairs.to_vec()) .ok_or(Exceptions::IllegalStateException(None))?; @@ -625,7 +622,7 @@ impl RSSExpandedReader { row: &BitArray, previousPairs: &[ExpandedPair], rowNumber: u32, - ) -> Result { + ) -> Result { let mut isOddPattern = previousPairs.len() % 2 == 0; if self.startFromEven { isOddPattern = !isOddPattern; @@ -688,7 +685,7 @@ impl RSSExpandedReader { row: &BitArray, previousPairs: &[ExpandedPair], forcedOffset: i32, - ) -> Result<(), Exceptions> { + ) -> Result<()> { let counters = &mut self.decodeFinderCounters; counters.fill(0); // counters[0] = 0; @@ -830,7 +827,7 @@ impl RSSExpandedReader { pattern: &FinderPattern, isOddPattern: bool, leftChar: bool, - ) -> Result { + ) -> Result { let counters = &mut self.dataCharacterCounters; counters.fill(0); @@ -934,7 +931,7 @@ impl RSSExpandedReader { !(pattern.getValue() == 0 && isOddPattern && leftChar) } - fn adjustOddEvenCounts(&mut self, numModules: u32) -> Result<(), Exceptions> { + fn adjustOddEvenCounts(&mut self, numModules: u32) -> Result<()> { let oddSum = self.oddCounts.iter().sum::(); let evenSum = self.evenCounts.iter().sum::(); diff --git a/src/oned/rss/expanded/rss_expanded_stacked_internal_test_case.rs b/src/oned/rss/expanded/rss_expanded_stacked_internal_test_case.rs index 2b32ac2..3affb4f 100644 --- a/src/oned/rss/expanded/rss_expanded_stacked_internal_test_case.rs +++ b/src/oned/rss/expanded/rss_expanded_stacked_internal_test_case.rs @@ -24,7 +24,8 @@ * http://www.piramidepse.com/ */ -use crate::{oned::rss::expanded::ExpandedPair, Exceptions, Reader}; +use crate::common::Result; +use crate::{oned::rss::expanded::ExpandedPair, Reader}; use super::{test_case_util, RSSExpandedReader}; @@ -43,7 +44,7 @@ fn testDecodingRowByRow() { // let tester = ; - assert!(|| -> Result, Exceptions> { + assert!(|| -> Result> { rssExpandedReader.decodeRow2pairs(firstRowNumber as u32, &firstRow) // fail(NotFoundException.class.getName() + " expected"); }() diff --git a/src/oned/rss/rss_14_reader.rs b/src/oned/rss/rss_14_reader.rs index 1bf5ff8..520a32c 100644 --- a/src/oned/rss/rss_14_reader.rs +++ b/src/oned/rss/rss_14_reader.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use crate::{ - common::BitArray, + common::{BitArray, Result}, oned::{one_d_reader, OneDReader}, BarcodeFormat, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, @@ -50,7 +50,7 @@ impl OneDReader for RSS14Reader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let mut row = row.clone(); let leftPair = self.decodePair(&row, false, rowNumber, hints); Self::addOrTally(&mut self.possibleLeftPairs, leftPair); @@ -73,10 +73,7 @@ impl OneDReader for RSS14Reader { } } impl Reader for RSS14Reader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -85,7 +82,7 @@ impl Reader for RSS14Reader { &mut self, image: &mut crate::BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { if let Ok(res) = self.doDecode(image, hints) { Ok(res) } else { @@ -249,7 +246,7 @@ impl RSS14Reader { rowNumber: u32, hints: &DecodingHintDictionary, ) -> Option { - let pos_pair = || -> Result { + let pos_pair = || -> Result { let startEnd = self.findFinderPattern(row, right)?; let pattern = self.parseFoundFinderPattern(row, rowNumber, right, &startEnd)?; @@ -285,7 +282,7 @@ impl RSS14Reader { row: &BitArray, pattern: &FinderPattern, outsideChar: bool, - ) -> Result { + ) -> Result { let counters = &mut self.dataCharacterCounters; counters.fill(0); @@ -378,7 +375,7 @@ impl RSS14Reader { &mut self, row: &BitArray, rightFinderPattern: bool, - ) -> Result<[usize; 2], Exceptions> { + ) -> Result<[usize; 2]> { let counters = &mut self.decodeFinderCounters; counters.fill(0); @@ -426,7 +423,7 @@ impl RSS14Reader { rowNumber: u32, right: bool, startEnd: &[usize], - ) -> Result { + ) -> Result { // Actually we found elements 2-5 let firstIsBlack = row.get(startEnd[0]); let mut firstElementStart = startEnd[0] as isize - 1; @@ -461,11 +458,7 @@ impl RSS14Reader { )) } - fn adjustOddEvenCounts( - &mut self, - outsideChar: bool, - numModules: u32, - ) -> Result<(), Exceptions> { + fn adjustOddEvenCounts(&mut self, outsideChar: bool, numModules: u32) -> Result<()> { let oddSum = self.oddCounts.iter().sum::(); let evenSum = self.evenCounts.iter().sum::(); diff --git a/src/oned/upc_a_reader.rs b/src/oned/upc_a_reader.rs index a4904da..58d0eb1 100644 --- a/src/oned/upc_a_reader.rs +++ b/src/oned/upc_a_reader.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use crate::{BarcodeFormat, Exceptions, RXingResult, Reader}; +use crate::{common::Result, BarcodeFormat, Exceptions, RXingResult, Reader}; use super::{EAN13Reader, OneDReader, UPCEANReader}; @@ -28,10 +28,7 @@ use super::{EAN13Reader, OneDReader, UPCEANReader}; pub struct UPCAReader(EAN13Reader); impl Reader for UPCAReader { - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { Self::maybeReturnRXingResult(self.0.decode(image)?) } @@ -39,7 +36,7 @@ impl Reader for UPCAReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { Self::maybeReturnRXingResult(self.0.decode_with_hints(image, hints)?) } } @@ -50,7 +47,7 @@ impl OneDReader for UPCAReader { rowNumber: u32, row: &crate::common::BitArray, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { Self::maybeReturnRXingResult(self.0.decodeRow(rowNumber, row, hints)?) } } @@ -65,7 +62,7 @@ impl UPCEANReader for UPCAReader { row: &crate::common::BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result { + ) -> Result { self.0.decodeMiddle(row, startRange, resultString) } @@ -75,7 +72,7 @@ impl UPCEANReader for UPCAReader { row: &crate::common::BitArray, startGuardRange: &[usize; 2], hints: &crate::DecodingHintDictionary, - ) -> Result + ) -> Result where Self: Sized, { @@ -91,7 +88,7 @@ impl UPCEANReader for UPCAReader { impl UPCAReader { // private final UPCEANReader ean13Reader = new EAN13Reader(); - fn maybeReturnRXingResult(result: RXingResult) -> Result { + fn maybeReturnRXingResult(result: RXingResult) -> Result { let text = result.getText(); if let Some(stripped_text) = text.strip_prefix('0') { let mut upcaRXingResult = RXingResult::new( diff --git a/src/oned/upc_a_writer.rs b/src/oned/upc_a_writer.rs index 339dd35..19d5954 100644 --- a/src/oned/upc_a_writer.rs +++ b/src/oned/upc_a_writer.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; -use crate::{BarcodeFormat, Exceptions, Writer}; +use crate::{common::Result, BarcodeFormat, Exceptions, Writer}; use super::EAN13Writer; @@ -35,7 +35,7 @@ impl Writer for UPCAWriter { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -46,7 +46,7 @@ impl Writer for UPCAWriter { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { if format != &BarcodeFormat::UPC_A { return Err(Exceptions::IllegalArgumentException(Some(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 248b85f..f74f410 100644 --- a/src/oned/upc_e_reader.rs +++ b/src/oned/upc_e_reader.rs @@ -15,7 +15,7 @@ */ use super::{OneDReader, UPCEANReader, L_AND_G_PATTERNS}; -use crate::{BarcodeFormat, Exceptions}; +use crate::{common::Result, BarcodeFormat, Exceptions}; use rxing_one_d_proc_derive::{EANReader, OneDReader}; /** @@ -38,7 +38,7 @@ impl UPCEANReader for UPCEReader { row: &crate::common::BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result { + ) -> Result { let mut counters = [0_u32; 4]; let end = row.getSize(); @@ -67,17 +67,13 @@ impl UPCEANReader for UPCEReader { Ok(rowOffset) } - fn checkChecksum(&self, s: &str) -> Result { + fn checkChecksum(&self, s: &str) -> Result { self.checkStandardUPCEANChecksum( &convertUPCEtoUPCA(s).ok_or(Exceptions::IllegalArgumentException(None))?, ) } - fn decodeEnd( - &self, - row: &crate::common::BitArray, - endStart: usize, - ) -> Result<[usize; 2], Exceptions> { + fn decodeEnd(&self, row: &crate::common::BitArray, endStart: usize) -> Result<[usize; 2]> { self.findGuardPattern(row, endStart, true, &Self::MIDDLE_END_PATTERN) } } @@ -126,7 +122,7 @@ impl UPCEReader { fn determineNumSysAndCheckDigit( resultString: &mut String, lgPatternFound: usize, - ) -> Result<(), Exceptions> { + ) -> Result<()> { for numSys in 0..=1 { for d in 0..10 { if lgPatternFound == Self::NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d] { diff --git a/src/oned/upc_e_writer.rs b/src/oned/upc_e_writer.rs index f88568a..1b21de2 100644 --- a/src/oned/upc_e_writer.rs +++ b/src/oned/upc_e_writer.rs @@ -16,6 +16,7 @@ use rxing_one_d_proc_derive::OneDWriter; +use crate::common::Result; use crate::BarcodeFormat; use super::{ @@ -37,7 +38,7 @@ pub struct UPCEWriter; impl UPCEANWriter for UPCEWriter {} impl OneDimensionalCodeWriter for UPCEWriter { - fn encode_oned(&self, contents: &str) -> Result, Exceptions> { + fn encode_oned(&self, contents: &str) -> Result> { let length = contents.chars().count(); let mut contents = contents.to_owned(); let reader = UPCEReader::default(); diff --git a/src/oned/upc_ean_extension_2_support.rs b/src/oned/upc_ean_extension_2_support.rs index 0ab38ab..6dd85d0 100644 --- a/src/oned/upc_ean_extension_2_support.rs +++ b/src/oned/upc_ean_extension_2_support.rs @@ -17,8 +17,9 @@ use std::collections::HashMap; use crate::{ - common::BitArray, BarcodeFormat, Exceptions, RXingResult, RXingResultMetadataType, - RXingResultMetadataValue, RXingResultPoint, + common::{BitArray, Result}, + BarcodeFormat, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, + RXingResultPoint, }; use super::{upc_ean_reader, UPCEANReader, STAND_IN}; @@ -37,7 +38,7 @@ impl UPCEANExtension2Support { rowNumber: u32, row: &BitArray, extensionStartRange: &[u32; 3], - ) -> Result { + ) -> Result { let mut result = String::new(); let end = self.decodeMiddle(row, extensionStartRange, &mut result)?; @@ -68,7 +69,7 @@ impl UPCEANExtension2Support { row: &BitArray, startRange: &[u32; 3], resultString: &mut String, - ) -> Result { + ) -> Result { let mut counters = self.decodeMiddleCounters; counters.fill(0); diff --git a/src/oned/upc_ean_extension_5_support.rs b/src/oned/upc_ean_extension_5_support.rs index 8bbbaf8..db147fb 100644 --- a/src/oned/upc_ean_extension_5_support.rs +++ b/src/oned/upc_ean_extension_5_support.rs @@ -17,8 +17,9 @@ use std::collections::HashMap; use crate::{ - common::BitArray, BarcodeFormat, Exceptions, RXingResult, RXingResultMetadataType, - RXingResultMetadataValue, RXingResultPoint, + common::{BitArray, Result}, + BarcodeFormat, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, + RXingResultPoint, }; use super::{upc_ean_reader, UPCEANReader, STAND_IN}; @@ -38,7 +39,7 @@ impl UPCEANExtension5Support { rowNumber: u32, row: &BitArray, extensionStartRange: &[usize; 2], - ) -> Result { + ) -> Result { let mut result = String::new(); let end = Self::decodeMiddle(row, extensionStartRange, &mut result)?; @@ -70,7 +71,7 @@ impl UPCEANExtension5Support { row: &BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result { + ) -> Result { let mut counters = [0_u32; 4]; let end = row.getSize(); let mut rowOffset = startRange[1]; @@ -142,7 +143,7 @@ impl UPCEANExtension5Support { Some(sum % 10) } - fn determineCheckDigit(lgPatternFound: usize) -> Result { + fn determineCheckDigit(lgPatternFound: usize) -> Result { for d in 0..10 { if lgPatternFound == Self::CHECK_DIGIT_ENCODINGS[d] { return Ok(d); diff --git a/src/oned/upc_ean_extension_support.rs b/src/oned/upc_ean_extension_support.rs index 831af00..8115b47 100644 --- a/src/oned/upc_ean_extension_support.rs +++ b/src/oned/upc_ean_extension_support.rs @@ -14,7 +14,10 @@ * limitations under the License. */ -use crate::{common::BitArray, Exceptions, RXingResult}; +use crate::{ + common::{BitArray, Result}, + RXingResult, +}; use super::{UPCEANExtension2Support, UPCEANExtension5Support, UPCEANReader, STAND_IN}; @@ -32,7 +35,7 @@ impl UPCEANExtensionSupport { rowNumber: u32, row: &BitArray, rowOffset: usize, - ) -> Result { + ) -> Result { let extensionStartRange = STAND_IN.findGuardPattern(row, rowOffset, false, &Self::EXTENSION_START_PATTERN)?; if let Ok(res_1) = self diff --git a/src/oned/upc_ean_reader.rs b/src/oned/upc_ean_reader.rs index 60d9a72..2fca4bc 100644 --- a/src/oned/upc_ean_reader.rs +++ b/src/oned/upc_ean_reader.rs @@ -15,7 +15,8 @@ */ use crate::{ - common::BitArray, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, + common::{BitArray, Result}, + BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, }; @@ -100,7 +101,7 @@ pub const L_AND_G_PATTERNS: [[u32; 4]; 20] = { * @author alasdair@google.com (Alasdair Mackintosh) */ pub trait UPCEANReader: OneDReader { - fn findStartGuardPattern(&self, row: &BitArray) -> Result<[usize; 2], Exceptions> { + fn findStartGuardPattern(&self, row: &BitArray) -> Result<[usize; 2]> { let mut foundStart = false; let mut startRange = [0; 2]; let mut nextStart = 0; @@ -150,7 +151,7 @@ pub trait UPCEANReader: OneDReader { row: &BitArray, startGuardRange: &[usize; 2], hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let resultPointCallback = hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK); let mut symbologyIdentifier = 0; @@ -211,7 +212,7 @@ pub trait UPCEANReader: OneDReader { let mut extensionLength = 0; - let mut attempt = || -> Result<(), Exceptions> { + let mut attempt = || -> Result<()> { let extensionRXingResult = UPC_EAN_EXTENSION_SUPPORT.decodeRow(rowNumber, row, endRange[1])?; @@ -272,7 +273,7 @@ pub trait UPCEANReader: OneDReader { * @return {@link #checkStandardUPCEANChecksum(CharSequence)} * @throws FormatException if the string does not contain only digits */ - fn checkChecksum(&self, s: &str) -> Result { + fn checkChecksum(&self, s: &str) -> Result { self.checkStandardUPCEANChecksum(s) } @@ -284,7 +285,7 @@ pub trait UPCEANReader: OneDReader { * @return true iff string of digits passes the UPC/EAN checksum algorithm * @throws FormatException if the string does not contain only digits */ - fn checkStandardUPCEANChecksum(&self, s: &str) -> Result { + fn checkStandardUPCEANChecksum(&self, s: &str) -> Result { let length = s.len(); if length == 0 { return Ok(false); @@ -308,7 +309,7 @@ pub trait UPCEANReader: OneDReader { }) } - fn getStandardUPCEANChecksum(&self, s: &str) -> Result { + fn getStandardUPCEANChecksum(&self, s: &str) -> Result { let length = s.chars().count(); let mut sum = 0; let mut i = length as isize - 1; @@ -345,7 +346,7 @@ pub trait UPCEANReader: OneDReader { Ok(((1000 - sum) % 10) as u32) } - fn decodeEnd(&self, row: &BitArray, endStart: usize) -> Result<[usize; 2], Exceptions> { + fn decodeEnd(&self, row: &BitArray, endStart: usize) -> Result<[usize; 2]> { self.findGuardPattern(row, endStart, false, &START_END_PATTERN) } @@ -355,7 +356,7 @@ pub trait UPCEANReader: OneDReader { rowOffset: usize, whiteFirst: bool, pattern: &[u32], - ) -> Result<[usize; 2], Exceptions> { + ) -> Result<[usize; 2]> { self.findGuardPatternWithCounters( row, rowOffset, @@ -383,7 +384,7 @@ pub trait UPCEANReader: OneDReader { whiteFirst: bool, pattern: &[u32], counters: &mut [u32], - ) -> Result<[usize; 2], Exceptions> { + ) -> Result<[usize; 2]> { let width = row.getSize(); let rowOffset = if whiteFirst { row.getNextUnset(rowOffset) @@ -444,7 +445,7 @@ pub trait UPCEANReader: OneDReader { counters: &mut [u32; 4], rowOffset: usize, patterns: &[[u32; 4]], - ) -> Result { + ) -> Result { one_d_reader::recordPattern(row, rowOffset, counters)?; let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestMatch = -1_isize; @@ -486,7 +487,7 @@ pub trait UPCEANReader: OneDReader { row: &BitArray, startRange: &[usize; 2], resultString: &mut String, - ) -> Result; + ) -> Result; } pub(crate) struct StandInStruct; @@ -500,7 +501,7 @@ impl UPCEANReader for StandInStruct { _row: &BitArray, _startRange: &[usize; 2], _resultString: &mut String, - ) -> Result { + ) -> Result { todo!() } } @@ -510,13 +511,13 @@ impl OneDReader for StandInStruct { _rowNumber: u32, _row: &BitArray, _hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { todo!() } } impl Reader for StandInStruct { - fn decode(&mut self, _image: &mut crate::BinaryBitmap) -> Result { + fn decode(&mut self, _image: &mut crate::BinaryBitmap) -> Result { todo!() } @@ -524,7 +525,7 @@ impl Reader for StandInStruct { &mut self, _image: &mut crate::BinaryBitmap, _hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { todo!() } } diff --git a/src/pdf417/decoder/bounding_box.rs b/src/pdf417/decoder/bounding_box.rs index 4cf5aca..19bc668 100644 --- a/src/pdf417/decoder/bounding_box.rs +++ b/src/pdf417/decoder/bounding_box.rs @@ -16,7 +16,10 @@ use std::rc::Rc; -use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, RXingResultPoint, ResultPoint, +}; /** * @author Guenther Grau @@ -40,7 +43,7 @@ impl BoundingBox { bottomLeft: Option, topRight: Option, bottomRight: Option, - ) -> Result { + ) -> Result { let leftUnspecified = topLeft.is_none() || bottomLeft.is_none(); let rightUnspecified = topRight.is_none() || bottomRight.is_none(); if leftUnspecified && rightUnspecified { @@ -100,7 +103,7 @@ impl BoundingBox { pub fn merge( leftBox: Option, rightBox: Option, - ) -> Result { + ) -> Result { if leftBox.is_none() { return Ok(rightBox .as_ref() @@ -130,7 +133,7 @@ impl BoundingBox { missingStartRows: u32, missingEndRows: u32, isLeft: bool, - ) -> Result { + ) -> Result { let mut newTopLeft = self.topLeft; let mut newBottomLeft = self.bottomLeft; let mut newTopRight = self.topRight; diff --git a/src/pdf417/decoder/decoded_bit_stream_parser.rs b/src/pdf417/decoder/decoded_bit_stream_parser.rs index a3c2cc3..9d2651e 100644 --- a/src/pdf417/decoder/decoded_bit_stream_parser.rs +++ b/src/pdf417/decoder/decoded_bit_stream_parser.rs @@ -19,7 +19,7 @@ use num::{self, bigint::ToBigUint, BigUint}; use std::rc::Rc; use crate::{ - common::{DecoderRXingResult, ECIStringBuilder}, + common::{DecoderRXingResult, ECIStringBuilder, Result}, pdf417::PDF417RXingResultMetadata, Exceptions, }; @@ -106,7 +106,7 @@ static EXP900: Lazy> = Lazy::new(|| { const NUMBER_OF_SEQUENCE_CODEWORDS: usize = 2; -pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { +pub fn decode(codewords: &[u32], ecLevel: &str) -> Result { let mut result = ECIStringBuilder::with_capacity(codewords.len() * 2); let mut codeIndex = textCompaction(codewords, 1, &mut result)?; let mut resultMetadata = PDF417RXingResultMetadata::default(); @@ -182,7 +182,7 @@ pub fn decodeMacroBlock( codewords: &[u32], codeIndex: usize, resultMetadata: &mut PDF417RXingResultMetadata, -) -> Result { +) -> Result { let mut codeIndex = codeIndex; if codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0] as usize { // we must have at least two bytes left for the segment index @@ -332,7 +332,7 @@ fn textCompaction( codewords: &[u32], codeIndex: usize, result: &mut ECIStringBuilder, -) -> Result { +) -> Result { let mut codeIndex = codeIndex; // 2 character per codeword let mut textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2]; @@ -610,7 +610,7 @@ fn byteCompaction( codewords: &[u32], codeIndex: usize, result: &mut ECIStringBuilder, -) -> Result { +) -> Result { let mut end = false; let mut codeIndex = codeIndex; @@ -681,7 +681,7 @@ fn numericCompaction( codewords: &[u32], codeIndex: usize, result: &mut ECIStringBuilder, -) -> Result { +) -> Result { let mut count = 0; let mut end = false; let mut codeIndex = codeIndex; @@ -769,7 +769,7 @@ fn numericCompaction( Remove leading 1 => RXingResult is 000213298174000 */ -fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result { +fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result { let mut result = 0 .to_biguint() .ok_or(Exceptions::ArithmeticException(None))?; diff --git a/src/pdf417/decoder/ec/error_correction.rs b/src/pdf417/decoder/ec/error_correction.rs index 791fe22..65a9f6d 100644 --- a/src/pdf417/decoder/ec/error_correction.rs +++ b/src/pdf417/decoder/ec/error_correction.rs @@ -17,6 +17,7 @@ use std::rc::Rc; use crate::{ + common::Result, pdf417::{decoder::ec::ModulusGF, pdf_417_common::NUMBER_OF_CODEWORDS}, Exceptions, }; @@ -45,11 +46,7 @@ static FLD_INTERIOR: Lazy = Lazy::new(|| ModulusGF::new(NUMBER_OF_COD * @return number of errors * @throws ChecksumException if errors cannot be corrected, maybe because of too many errors */ -pub fn decode( - received: &mut [u32], - numECCodewords: u32, - erasures: &mut [u32], -) -> Result { +pub fn decode(received: &mut [u32], numECCodewords: u32, erasures: &mut [u32]) -> Result { let field: &'static ModulusGF = &FLD_INTERIOR; let poly = ModulusPoly::new(field, received.to_vec())?; let mut S = vec![0u32; numECCodewords as usize]; @@ -117,7 +114,7 @@ fn runEuclideanAlgorithm( b: Rc, R: u32, field: &'static ModulusGF, -) -> Result<[Rc; 2], Exceptions> { +) -> Result<[Rc; 2]> { // Assume a's degree is >= b's let mut a = a; let mut b = b; @@ -172,10 +169,7 @@ fn runEuclideanAlgorithm( Ok([sigma, omega]) } -fn findErrorLocations( - errorLocator: Rc, - field: &ModulusGF, -) -> Result, Exceptions> { +fn findErrorLocations(errorLocator: Rc, field: &ModulusGF) -> Result> { // This is a direct application of Chien's search let numErrors = errorLocator.getDegree(); let mut result = vec![0u32; numErrors as usize]; diff --git a/src/pdf417/decoder/ec/error_correction_test_case.rs b/src/pdf417/decoder/ec/error_correction_test_case.rs index 5267a65..9e5ccc8 100644 --- a/src/pdf417/decoder/ec/error_correction_test_case.rs +++ b/src/pdf417/decoder/ec/error_correction_test_case.rs @@ -16,7 +16,7 @@ use rand::Rng; -use crate::Exceptions; +use crate::common::Result; use super::{ abstract_error_correction_test_case::{corrupt, getRandom}, @@ -99,11 +99,11 @@ fn testTooManyErrors() { // } } -fn checkDecode(received: &mut [u32]) -> Result<(), Exceptions> { +fn checkDecode(received: &mut [u32]) -> Result<()> { checkDecodeErasures(received, &mut [0_u32; 0]) } -fn checkDecodeErasures(received: &mut [u32], erasures: &mut [u32]) -> Result<(), Exceptions> { +fn checkDecodeErasures(received: &mut [u32], erasures: &mut [u32]) -> Result<()> { decode(received, ECC_BYTES as u32, erasures)?; // ec.decode(received, ECC_BYTES, erasures); for i in 0..PDF417_TEST.len() { diff --git a/src/pdf417/decoder/ec/modulus_gf.rs b/src/pdf417/decoder/ec/modulus_gf.rs index 539342b..d67d375 100644 --- a/src/pdf417/decoder/ec/modulus_gf.rs +++ b/src/pdf417/decoder/ec/modulus_gf.rs @@ -16,6 +16,7 @@ //public static final ModulusGF PDF417_GF = new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS, 3); +use crate::common::Result; use crate::Exceptions; /** @@ -75,7 +76,7 @@ impl ModulusGF { self.expTable[a as usize] } - pub fn log(&self, a: u32) -> Result { + pub fn log(&self, a: u32) -> Result { if a == 0 { Err(Exceptions::ArithmeticException(None)) } else { @@ -83,7 +84,7 @@ impl ModulusGF { } } - pub fn inverse(&self, a: u32) -> Result { + pub fn inverse(&self, a: u32) -> Result { if a == 0 { Err(Exceptions::ArithmeticException(None)) } else { diff --git a/src/pdf417/decoder/ec/modulus_poly.rs b/src/pdf417/decoder/ec/modulus_poly.rs index 7ac93bc..35c40a9 100644 --- a/src/pdf417/decoder/ec/modulus_poly.rs +++ b/src/pdf417/decoder/ec/modulus_poly.rs @@ -16,6 +16,7 @@ use std::rc::Rc; +use crate::common::Result; use crate::Exceptions; use super::ModulusGF; @@ -31,10 +32,7 @@ pub struct ModulusPoly { // one: Option>, } impl ModulusPoly { - pub fn new( - field: &'static ModulusGF, - coefficients: Vec, - ) -> Result { + pub fn new(field: &'static ModulusGF, coefficients: Vec) -> Result { if coefficients.is_empty() { return Err(Exceptions::IllegalArgumentException(None)); } @@ -124,7 +122,7 @@ impl ModulusPoly { result } - pub fn add(&self, other: Rc) -> Result, Exceptions> { + pub fn add(&self, other: Rc) -> Result> { if self.field != other.field { return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), @@ -158,7 +156,7 @@ impl ModulusPoly { Ok(Rc::new(ModulusPoly::new(self.field, sumDiff)?)) } - pub fn subtract(&self, other: Rc) -> Result, Exceptions> { + pub fn subtract(&self, other: Rc) -> Result> { if self.field != other.field { return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), @@ -170,7 +168,7 @@ impl ModulusPoly { self.add(other.negative()) } - pub fn multiply(&self, other: Rc) -> Result, Exceptions> { + pub fn multiply(&self, other: Rc) -> Result> { if !(self.field == other.field) { return Err(Exceptions::IllegalArgumentException(Some( "ModulusPolys do not have same ModulusGF field".to_owned(), diff --git a/src/pdf417/decoder/pdf_417_scanning_decoder.rs b/src/pdf417/decoder/pdf_417_scanning_decoder.rs index a5c49fd..19cf9a0 100644 --- a/src/pdf417/decoder/pdf_417_scanning_decoder.rs +++ b/src/pdf417/decoder/pdf_417_scanning_decoder.rs @@ -17,7 +17,7 @@ use std::rc::Rc; use crate::{ - common::{BitMatrix, DecoderRXingResult}, + common::{BitMatrix, DecoderRXingResult, Result}, pdf417::pdf_417_common, Exceptions, RXingResultPoint, ResultPoint, }; @@ -50,7 +50,7 @@ pub fn decode( imageBottomRight: Option, minCodewordWidth: u32, maxCodewordWidth: u32, -) -> Result { +) -> Result { let mut minCodewordWidth = minCodewordWidth; let mut maxCodewordWidth = maxCodewordWidth; let mut boundingBox = Rc::new(BoundingBox::new( @@ -180,7 +180,7 @@ pub fn decode( fn merge<'a, T: DetectionRXingResultRowIndicatorColumn>( leftRowIndicatorColumn: &'a mut Option, rightRowIndicatorColumn: &'a mut Option, -) -> Result, Exceptions> { +) -> Result> { if leftRowIndicatorColumn.is_none() && rightRowIndicatorColumn.is_none() { return Ok(None); } @@ -201,7 +201,7 @@ fn merge<'a, T: DetectionRXingResultRowIndicatorColumn>( fn adjustBoundingBox( rowIndicatorColumn: &mut Option, -) -> Result, Exceptions> { +) -> Result> { if rowIndicatorColumn.is_none() { return Ok(None); } @@ -403,7 +403,7 @@ fn getRowIndicatorColumn<'a>( fn adjustCodewordCount( detectionRXingResult: &DetectionRXingResult, barcodeMatrix: &mut [Vec], -) -> Result<(), Exceptions> { +) -> Result<()> { let barcodeMatrix01 = &mut barcodeMatrix[0][1]; let numberOfCodewords = barcodeMatrix01.getValue(); let calculatedNumberOfCodewords = (detectionRXingResult.getBarcodeColumnCount() as isize @@ -426,7 +426,7 @@ fn adjustCodewordCount( fn createDecoderRXingResult( detectionRXingResult: &mut DetectionRXingResult, -) -> Result { +) -> Result { let mut barcodeMatrix = createBarcodeMatrix(detectionRXingResult); adjustCodewordCount(detectionRXingResult, &mut barcodeMatrix)?; let mut erasures = Vec::new(); @@ -488,7 +488,7 @@ fn createDecoderRXingResultFromAmbiguousValues( erasureArray: &mut [u32], ambiguousIndexes: &mut [u32], ambiguousIndexValues: &[Vec], -) -> Result { +) -> Result { let mut ambiguousIndexCount = vec![0; ambiguousIndexes.len()]; let mut tries = 100; @@ -843,7 +843,7 @@ fn decodeCodewords( codewords: &mut [u32], ecLevel: u32, erasures: &mut [u32], -) -> Result { +) -> Result { if codewords.is_empty() { return Err(Exceptions::FormatException(None)); } @@ -874,7 +874,7 @@ fn correctErrors( codewords: &mut [u32], erasures: &mut [u32], numECCodewords: u32, -) -> Result { +) -> Result { if !erasures.is_empty() && erasures.len() as u32 > numECCodewords / 2 + MAX_ERRORS /*|| numECCodewords < 0*/ || numECCodewords > MAX_EC_CODEWORDS @@ -888,7 +888,7 @@ fn correctErrors( /** * Verify that all is OK with the codeword array. */ -fn verifyCodewordCount(codewords: &mut [u32], numECCodewords: u32) -> Result<(), Exceptions> { +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 diff --git a/src/pdf417/detector/pdf_417_detector.rs b/src/pdf417/detector/pdf_417_detector.rs index b747c32..0e007c0 100644 --- a/src/pdf417/detector/pdf_417_detector.rs +++ b/src/pdf417/detector/pdf_417_detector.rs @@ -15,8 +15,8 @@ */ use crate::{ - common::BitMatrix, BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResultPoint, - ResultPoint, + common::{BitMatrix, Result}, + BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResultPoint, ResultPoint, }; use std::borrow::Cow; @@ -68,7 +68,7 @@ pub fn detect_with_hints( image: &mut BinaryBitmap, _hints: &DecodingHintDictionary, multiple: bool, -) -> Result { +) -> Result { // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even // different binarizers //boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); @@ -101,7 +101,7 @@ pub fn detect_with_hints( * @param rotation the degrees of rotation to apply * @return BitMatrix with applied rotation */ -fn applyRotation(matrix: &BitMatrix, rotation: u32) -> Result, Exceptions> { +fn applyRotation(matrix: &BitMatrix, rotation: u32) -> Result> { if rotation % 360 == 0 { Ok(Cow::Borrowed(matrix)) } else { diff --git a/src/pdf417/encoder/pdf_417.rs b/src/pdf417/encoder/pdf_417.rs index 6f99a8c..62114f6 100644 --- a/src/pdf417/encoder/pdf_417.rs +++ b/src/pdf417/encoder/pdf_417.rs @@ -20,6 +20,7 @@ use encoding::EncodingRef; +use crate::common::Result; use crate::Exceptions; use super::{ @@ -133,7 +134,7 @@ impl PDF417 { r: u32, errorCorrectionLevel: u32, logic: &mut BarcodeMatrix, - ) -> Result<(), Exceptions> { + ) -> Result<()> { let mut idx = 0; for y in 0..r { let cluster = y as usize % 3; @@ -184,11 +185,7 @@ impl PDF417 { * @param errorCorrectionLevel PDF417 error correction level to use * @throws WriterException if the contents cannot be encoded in this format */ - pub fn generateBarcodeLogic( - &mut self, - msg: &str, - errorCorrectionLevel: u32, - ) -> Result<(), Exceptions> { + pub fn generateBarcodeLogic(&mut self, msg: &str, errorCorrectionLevel: u32) -> Result<()> { self.generateBarcodeLogicWithAutoECI(msg, errorCorrectionLevel, false) } @@ -203,7 +200,7 @@ impl PDF417 { msg: &str, errorCorrectionLevel: u32, autoECI: bool, - ) -> Result<(), Exceptions> { + ) -> Result<()> { //1. step: High-level encoding let errorCorrectionCodeWords = pdf_417_error_correction::getErrorCorrectionCodewordCount(errorCorrectionLevel)?; @@ -272,7 +269,7 @@ impl PDF417 { &self, sourceCodeWords: u32, errorCorrectionCodeWords: u32, - ) -> Result<[u32; 2], Exceptions> { + ) -> Result<[u32; 2]> { let mut ratio = 0.0; let mut dimension = None; diff --git a/src/pdf417/encoder/pdf_417_error_correction.rs b/src/pdf417/encoder/pdf_417_error_correction.rs index bf7522c..ed56ca6 100644 --- a/src/pdf417/encoder/pdf_417_error_correction.rs +++ b/src/pdf417/encoder/pdf_417_error_correction.rs @@ -24,6 +24,7 @@ */ use once_cell::sync::Lazy; +use crate::common::Result; use crate::Exceptions; /** @@ -117,7 +118,7 @@ static EC_COEFFICIENTS: Lazy<[Vec; 9]> = Lazy::new(|| { * @param errorCorrectionLevel the error correction level (0-8) * @return the number of codewords generated for error correction */ -pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { +pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result { if errorCorrectionLevel > 8 { return Err(Exceptions::IllegalArgumentException(Some( "Error correction level must be between 0 and 8!".to_owned(), @@ -133,7 +134,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result Result { +pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result { if n == 0 { Err(Exceptions::IllegalArgumentException(Some( "n must be > 0".to_owned(), @@ -160,10 +161,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result Result { +pub fn generateErrorCorrection(dataCodewords: &str, errorCorrectionLevel: u32) -> Result { let k = getErrorCorrectionCodewordCount(errorCorrectionLevel)?; let mut e = vec![0 as char; k as usize]; //new char[k]; let sld = dataCodewords.chars().count(); diff --git a/src/pdf417/encoder/pdf_417_high_level_encoder.rs b/src/pdf417/encoder/pdf_417_high_level_encoder.rs index 4da0f17..e0031af 100644 --- a/src/pdf417/encoder/pdf_417_high_level_encoder.rs +++ b/src/pdf417/encoder/pdf_417_high_level_encoder.rs @@ -23,7 +23,7 @@ use std::{any::TypeId, fmt::Display, str::FromStr}; use encoding::EncodingRef; use crate::{ - common::{CharacterSetECI, ECIInput, MinimalECIInput}, + common::{CharacterSetECI, ECIInput, MinimalECIInput, Result}, Exceptions, }; @@ -176,7 +176,7 @@ pub fn encodeHighLevel( compaction: Compaction, encoding: Option, autoECI: bool, -) -> Result { +) -> Result { let mut encoding = encoding; if msg.is_empty() { return Err(Exceptions::WriterException(Some( @@ -368,7 +368,7 @@ fn encodeText( count: u32, sb: &mut String, initialSubmode: u32, -) -> Result { +) -> Result { let mut tmp = String::with_capacity(count as usize); let mut submode = initialSubmode; let mut idx = 0; @@ -531,7 +531,7 @@ fn encodeMultiECIBinary( count: u32, startmode: u32, sb: &mut String, -) -> Result<(), Exceptions> { +) -> Result<()> { let end = (startpos + count).min(input.length() as u32); let mut localStart = startpos; loop { @@ -570,11 +570,7 @@ fn encodeMultiECIBinary( Ok(()) } -pub fn subBytes( - input: &Box, - start: u32, - end: u32, -) -> Result, Exceptions> { +pub fn subBytes(input: &Box, start: u32, end: u32) -> Result> { let count = (end - start) as usize; let mut result = vec![0_u8; count]; for i in start as usize..end as usize { @@ -600,7 +596,7 @@ fn encodeBinary( count: u32, startmode: u32, sb: &mut String, -) -> Result<(), Exceptions> { +) -> Result<()> { if count == 1 && startmode == TEXT_COMPACTION { sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::ParseException(None))?); } else if (count % 6) == 0 { @@ -641,7 +637,7 @@ fn encodeNumeric( startpos: u32, count: u32, sb: &mut String, -) -> Result<(), Exceptions> { +) -> Result<()> { 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))?; @@ -723,7 +719,7 @@ fn isText(ch: char) -> bool { fn determineConsecutiveDigitCount( input: &Box, startpos: u32, -) -> Result { +) -> Result { let mut count = 0; let len = input.length(); let mut idx = startpos as usize; @@ -747,7 +743,7 @@ fn determineConsecutiveDigitCount( fn determineConsecutiveTextCount( input: &Box, startpos: u32, -) -> Result { +) -> Result { let len = input.length(); let mut idx = startpos as usize; while idx < len { @@ -789,7 +785,7 @@ fn determineConsecutiveBinaryCount( input: &Box, startpos: u32, encoding: Option, -) -> Result { +) -> Result { let len = input.length(); let mut idx = startpos as usize; while idx < len { @@ -834,7 +830,7 @@ fn determineConsecutiveBinaryCount( Ok(idx as u32 - startpos) } -fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> { +fn encodingECI(eci: i32, sb: &mut String) -> Result<()> { 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))?); @@ -859,27 +855,27 @@ impl ECIInput for NoECIInput { self.0.chars().count() } - fn charAt(&self, index: usize) -> Result { + fn charAt(&self, index: usize) -> Result { self.0 .chars() .nth(index) .ok_or(Exceptions::IndexOutOfBoundsException(None)) } - fn subSequence(&self, start: usize, end: usize) -> Result, Exceptions> { + fn subSequence(&self, start: usize, end: usize) -> Result> { let res: Vec = self.0.chars().skip(start).take(end - start).collect(); Ok(res) } - fn isECI(&self, _index: u32) -> Result { + fn isECI(&self, _index: u32) -> Result { Ok(false) } - fn getECIValue(&self, _index: usize) -> Result { + fn getECIValue(&self, _index: usize) -> Result { Ok(-1) } - fn haveNCharacters(&self, index: usize, n: usize) -> Result { + fn haveNCharacters(&self, index: usize, n: usize) -> Result { Ok(index + n <= self.0.len()) } } diff --git a/src/pdf417/encoder/pdf_417_high_level_encoder_test_adapter.rs b/src/pdf417/encoder/pdf_417_high_level_encoder_test_adapter.rs index 7490ddc..3382821 100644 --- a/src/pdf417/encoder/pdf_417_high_level_encoder_test_adapter.rs +++ b/src/pdf417/encoder/pdf_417_high_level_encoder_test_adapter.rs @@ -16,7 +16,7 @@ use encoding::EncodingRef; -use crate::Exceptions; +use crate::common::Result; use super::{pdf_417_high_level_encoder, Compaction}; @@ -29,6 +29,6 @@ pub fn encodeHighLevel( compaction: Compaction, encoding: Option, autoECI: bool, -) -> Result { +) -> Result { pdf_417_high_level_encoder::encodeHighLevel(msg, compaction, encoding, autoECI) } diff --git a/src/pdf417/pdf_417_reader.rs b/src/pdf417/pdf_417_reader.rs index 25d0d4c..b99280d 100644 --- a/src/pdf417/pdf_417_reader.rs +++ b/src/pdf417/pdf_417_reader.rs @@ -17,9 +17,9 @@ use std::collections::HashMap; use crate::{ - multi::MultipleBarcodeReader, BarcodeFormat, BinaryBitmap, DecodingHintDictionary, Exceptions, - RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, - ResultPoint, + common::Result, multi::MultipleBarcodeReader, BarcodeFormat, BinaryBitmap, + DecodingHintDictionary, Exceptions, RXingResult, RXingResultMetadataType, + RXingResultMetadataValue, RXingResultPoint, Reader, ResultPoint, }; use super::{ @@ -43,10 +43,7 @@ impl Reader for PDF417Reader { * @throws NotFoundException if a PDF417 code cannot be found, * @throws FormatException if a PDF417 cannot be decoded */ - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -54,7 +51,7 @@ impl Reader for PDF417Reader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let result = Self::decode(image, hints, false)?; if result.is_empty() { return Err(Exceptions::NotFoundException(None)); @@ -67,7 +64,7 @@ impl MultipleBarcodeReader for PDF417Reader { fn decode_multiple( &mut self, image: &mut crate::BinaryBitmap, - ) -> Result, crate::Exceptions> { + ) -> Result> { self.decode_multiple_with_hints(image, &HashMap::new()) } @@ -75,7 +72,7 @@ impl MultipleBarcodeReader for PDF417Reader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result, crate::Exceptions> { + ) -> Result> { Self::decode(image, hints, true) } } @@ -89,7 +86,7 @@ impl PDF417Reader { image: &mut BinaryBitmap, hints: &DecodingHintDictionary, multiple: bool, - ) -> Result, Exceptions> { + ) -> Result> { let mut results = Vec::new(); let detectorRXingResult = pdf_417_detector::detect_with_hints(image, hints, multiple)?; diff --git a/src/pdf417/pdf_417_writer.rs b/src/pdf417/pdf_417_writer.rs index 5c03e69..41941f4 100644 --- a/src/pdf417/pdf_417_writer.rs +++ b/src/pdf417/pdf_417_writer.rs @@ -17,7 +17,8 @@ use std::collections::HashMap; use crate::{ - common::BitMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, + common::{BitMatrix, Result}, + BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, }; use super::encoder::PDF417; @@ -46,7 +47,7 @@ impl Writer for PDF417Writer { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -57,7 +58,7 @@ impl Writer for PDF417Writer { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { if format != &BarcodeFormat::PDF_417 { return Err(Exceptions::IllegalArgumentException(Some(format!( "Can only encode PDF_417, but got {format}" @@ -142,7 +143,7 @@ impl PDF417Writer { height: u32, margin: u32, autoECI: bool, - ) -> Result { + ) -> Result { encoder.generateBarcodeLogicWithAutoECI(contents, errorCorrectionLevel, autoECI)?; let aspectRatio = 4; diff --git a/src/planar_yuv_luminance_source.rs b/src/planar_yuv_luminance_source.rs index dd3a363..e628d1d 100644 --- a/src/planar_yuv_luminance_source.rs +++ b/src/planar_yuv_luminance_source.rs @@ -126,6 +126,7 @@ //package com.google.zxing; +use crate::common::Result; use crate::{Exceptions, LuminanceSource}; const THUMBNAIL_SCALE_FACTOR: usize = 2; @@ -164,7 +165,7 @@ impl PlanarYUVLuminanceSource { height: usize, reverse_horizontal: bool, inverted: bool, - ) -> Result { + ) -> Result { if left + width > data_width || top + height > data_height { return Err(Exceptions::IllegalArgumentException(Some( "Crop rectangle does not fit within image data.".to_owned(), @@ -315,7 +316,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, Exceptions> { + ) -> Result> { match PlanarYUVLuminanceSource::new_with_all( self.yuv_data.clone(), self.data_width, diff --git a/src/qrcode/decoder/VersionTestCase.rs b/src/qrcode/decoder/VersionTestCase.rs index ba32789..56a34b8 100644 --- a/src/qrcode/decoder/VersionTestCase.rs +++ b/src/qrcode/decoder/VersionTestCase.rs @@ -15,8 +15,8 @@ */ use crate::{ + common::Result, qrcode::decoder::{ErrorCorrectionLevel, Version}, - Exceptions, }; /** @@ -37,7 +37,7 @@ fn testVersionForNumber() { } } -fn checkVersion(version: Result<&Version, Exceptions>, number: u32, dimension: u32) { +fn checkVersion(version: Result<&Version>, number: u32, dimension: u32) { assert!(version.is_ok()); let version = version.unwrap(); assert_eq!(number, version.getVersionNumber()); diff --git a/src/qrcode/decoder/bit_matrix_parser.rs b/src/qrcode/decoder/bit_matrix_parser.rs index ae8eb1c..51b8c71 100644 --- a/src/qrcode/decoder/bit_matrix_parser.rs +++ b/src/qrcode/decoder/bit_matrix_parser.rs @@ -14,7 +14,10 @@ * limitations under the License. */ -use crate::{common::BitMatrix, Exceptions}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, +}; use super::{DataMask, FormatInformation, Version, VersionRef}; @@ -33,7 +36,7 @@ impl BitMatrixParser { * @param bitMatrix {@link BitMatrix} to parse * @throws FormatException if dimension is not >= 21 and 1 mod 4 */ - pub fn new(bit_matrix: BitMatrix) -> Result { + pub fn new(bit_matrix: BitMatrix) -> Result { let dimension = bit_matrix.getHeight(); if dimension < 21 || (dimension & 0x03) != 1 { Err(Exceptions::FormatException(Some(format!( @@ -56,7 +59,7 @@ impl BitMatrixParser { * @throws FormatException if both format information locations cannot be parsed as * the valid encoding of format information */ - pub fn readFormatInformation(&mut self) -> Result<&FormatInformation, Exceptions> { + pub fn readFormatInformation(&mut self) -> Result<&FormatInformation> { if self.parsedFormatInfo.is_some() { return self .parsedFormatInfo @@ -104,7 +107,7 @@ impl BitMatrixParser { * @throws FormatException if both version information locations cannot be parsed as * the valid encoding of version information */ - pub fn readVersion(&mut self) -> Result { + pub fn readVersion(&mut self) -> Result { if let Some(pv) = self.parsedVersion { return Ok(pv); } @@ -171,7 +174,7 @@ impl BitMatrixParser { * @return bytes encoded within the QR Code * @throws FormatException if the exact number of bytes expected is not read */ - pub fn readCodewords(&mut self) -> Result, Exceptions> { + pub fn readCodewords(&mut self) -> Result> { let version = self.readVersion()?; // Get the data mask for the format used in this QR Code. This will exclude @@ -235,7 +238,7 @@ impl BitMatrixParser { /** * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state. */ - pub fn remask(&mut self) -> Result<(), Exceptions> { + pub fn remask(&mut self) -> Result<()> { if let Some(pfi) = &self.parsedFormatInfo { let dataMask: DataMask = pfi.getDataMask().try_into()?; let dimension = self.bitMatrix.getHeight(); diff --git a/src/qrcode/decoder/data_block.rs b/src/qrcode/decoder/data_block.rs index 8c364dd..1d23900 100755 --- a/src/qrcode/decoder/data_block.rs +++ b/src/qrcode/decoder/data_block.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::{ErrorCorrectionLevel, VersionRef}; @@ -53,7 +54,7 @@ impl DataBlock { rawCodewords: &[u8], version: VersionRef, ecLevel: ErrorCorrectionLevel, - ) -> Result, Exceptions> { + ) -> Result> { if rawCodewords.len() as u32 != version.getTotalCodewords() { return Err(Exceptions::IllegalArgumentException(None)); } diff --git a/src/qrcode/decoder/decoded_bit_stream_parser.rs b/src/qrcode/decoder/decoded_bit_stream_parser.rs index f791e4f..6c2ce50 100644 --- a/src/qrcode/decoder/decoded_bit_stream_parser.rs +++ b/src/qrcode/decoder/decoded_bit_stream_parser.rs @@ -15,7 +15,7 @@ */ use crate::{ - common::{BitSource, CharacterSetECI, DecoderRXingResult, StringUtils}, + common::{BitSource, CharacterSetECI, DecoderRXingResult, Result, StringUtils}, DecodingHintDictionary, Exceptions, }; @@ -44,7 +44,7 @@ pub fn decode( version: VersionRef, ecLevel: ErrorCorrectionLevel, hints: &DecodingHintDictionary, -) -> Result { +) -> Result { let mut bits = BitSource::new(bytes.to_owned()); let mut result = String::with_capacity(50); let mut byteSegments = vec![vec![0u8; 0]; 0]; @@ -174,11 +174,7 @@ pub fn decode( /** * See specification GBT 18284-2000 */ -fn decodeHanziSegment( - bits: &mut BitSource, - result: &mut String, - count: usize, -) -> Result<(), Exceptions> { +fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -> Result<()> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { return Err(Exceptions::FormatException(None)); @@ -224,7 +220,7 @@ fn decodeKanjiSegment( count: usize, currentCharacterSetECI: Option, hints: &DecodingHintDictionary, -) -> Result<(), Exceptions> { +) -> Result<()> { // Don't crash trying to read more bits than we have available. if count * 13 > bits.available() { return Err(Exceptions::FormatException(None)); @@ -292,7 +288,7 @@ fn decodeByteSegment( currentCharacterSetECI: Option, byteSegments: &mut Vec>, hints: &DecodingHintDictionary, -) -> Result<(), Exceptions> { +) -> Result<()> { // Don't crash trying to read more bits than we have available. if 8 * count > bits.available() { return Err(Exceptions::FormatException(None)); @@ -359,7 +355,7 @@ fn decodeByteSegment( Ok(()) } -fn toAlphaNumericChar(value: u32) -> Result { +fn toAlphaNumericChar(value: u32) -> Result { if value as usize >= ALPHANUMERIC_CHARS.len() { return Err(Exceptions::FormatException(None)); } @@ -375,7 +371,7 @@ fn decodeAlphanumericSegment( result: &mut String, count: usize, fc1InEffect: bool, -) -> Result<(), Exceptions> { +) -> Result<()> { // Read two characters at a time let start = result.len(); let mut count = count; @@ -425,11 +421,7 @@ fn decodeAlphanumericSegment( Ok(()) } -fn decodeNumericSegment( - bits: &mut BitSource, - result: &mut String, - count: usize, -) -> Result<(), Exceptions> { +fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize) -> Result<()> { let mut count = count; // Read three digits at a time while count >= 3 { @@ -472,7 +464,7 @@ fn decodeNumericSegment( Ok(()) } -fn parseECIValue(bits: &mut BitSource) -> Result { +fn parseECIValue(bits: &mut BitSource) -> Result { let firstByte = bits.readBits(8)?; if (firstByte & 0x80) == 0 { // just one byte diff --git a/src/qrcode/decoder/error_correction_level.rs b/src/qrcode/decoder/error_correction_level.rs index a43e8fd..1b6d54d 100644 --- a/src/qrcode/decoder/error_correction_level.rs +++ b/src/qrcode/decoder/error_correction_level.rs @@ -16,6 +16,7 @@ use std::str::FromStr; +use crate::common::Result; use crate::Exceptions; /** @@ -41,7 +42,7 @@ impl ErrorCorrectionLevel { * @param bits int containing the two bits encoding a QR Code's error correction level * @return ErrorCorrectionLevel representing the encoded error correction level */ - pub fn forBits(bits: u8) -> Result { + pub fn forBits(bits: u8) -> Result { match bits { 0 => Ok(Self::M), 1 => Ok(Self::L), diff --git a/src/qrcode/decoder/format_information.rs b/src/qrcode/decoder/format_information.rs index 202e4d9..b6564f4 100644 --- a/src/qrcode/decoder/format_information.rs +++ b/src/qrcode/decoder/format_information.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use crate::Exceptions; +use crate::common::Result; use super::ErrorCorrectionLevel; @@ -73,7 +73,7 @@ pub struct FormatInformation { } impl FormatInformation { - fn new(format_info: u8) -> Result { + fn new(format_info: u8) -> Result { // Bits 3,4 let errorCorrectionLevel = ErrorCorrectionLevel::forBits((format_info >> 3) & 0x03)?; // Bottom 3 bits diff --git a/src/qrcode/decoder/mode.rs b/src/qrcode/decoder/mode.rs index 1d927ae..1dd1ef1 100644 --- a/src/qrcode/decoder/mode.rs +++ b/src/qrcode/decoder/mode.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::Version; @@ -52,7 +53,7 @@ impl Mode { * @return Mode encoded by these bits * @throws IllegalArgumentException if bits do not correspond to a known mode */ - pub fn forBits(bits: u8) -> Result { + pub fn forBits(bits: u8) -> Result { match bits { 0x0 => Ok(Self::TERMINATOR), 0x1 => Ok(Self::NUMERIC), diff --git a/src/qrcode/decoder/qrcode_decoder.rs b/src/qrcode/decoder/qrcode_decoder.rs index 6076ae3..688caa9 100644 --- a/src/qrcode/decoder/qrcode_decoder.rs +++ b/src/qrcode/decoder/qrcode_decoder.rs @@ -27,7 +27,7 @@ use once_cell::sync::Lazy; use crate::{ common::{ reedsolomon::get_predefined_genericgf, reedsolomon::PredefinedGenericGF, - reedsolomon::ReedSolomonDecoder, BitMatrix, DecoderRXingResult, + reedsolomon::ReedSolomonDecoder, BitMatrix, DecoderRXingResult, Result, }, DecodingHintDictionary, Exceptions, }; @@ -41,7 +41,7 @@ static RS_DECODER: Lazy = Lazy::new(|| { )) }); -pub fn decode_bool_array(image: &Vec>) -> Result { +pub fn decode_bool_array(image: &Vec>) -> Result { decode_bool_array_with_hints(image, &HashMap::new()) } @@ -58,11 +58,11 @@ pub fn decode_bool_array(image: &Vec>) -> Result>, hints: &DecodingHintDictionary, -) -> Result { +) -> Result { decode_bitmatrix_with_hints(&BitMatrix::parse_bools(image), hints) } -pub fn decode_bitmatrix(bits: &BitMatrix) -> Result { +pub fn decode_bitmatrix(bits: &BitMatrix) -> Result { decode_bitmatrix_with_hints(bits, &HashMap::new()) } @@ -78,7 +78,7 @@ pub fn decode_bitmatrix(bits: &BitMatrix) -> Result Result { +) -> Result { // Construct a parser and read version, error-correction level let mut parser = BitMatrixParser::new(bits.clone())?; let mut fe = None; @@ -92,7 +92,7 @@ pub fn decode_bitmatrix_with_hints( }, } - let mut trying = || -> Result { + let mut trying = || -> Result { // Revert the bit matrix parser.remask()?; @@ -140,7 +140,7 @@ pub fn decode_bitmatrix_with_hints( fn decode_bitmatrix_parser_with_hints( parser: &mut BitMatrixParser, hints: &DecodingHintDictionary, -) -> Result { +) -> Result { let version = parser.readVersion()?; let ecLevel = parser.readFormatInformation()?.getErrorCorrectionLevel(); @@ -180,7 +180,7 @@ fn decode_bitmatrix_parser_with_hints( * @param numDataCodewords number of codewords that are data bytes * @throws ChecksumException if error correction fails */ -fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<(), Exceptions> { +fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<()> { let numCodewords = codewordBytes.len(); // First read into an array of ints let mut codewordsInts = vec![0u8; numCodewords]; diff --git a/src/qrcode/decoder/version.rs b/src/qrcode/decoder/version.rs index 2528583..7f7f68e 100755 --- a/src/qrcode/decoder/version.rs +++ b/src/qrcode/decoder/version.rs @@ -16,7 +16,10 @@ use std::fmt; -use crate::{common::BitMatrix, Exceptions}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, +}; use super::{ErrorCorrectionLevel, FormatInformation}; @@ -97,9 +100,7 @@ impl Version { * @return Version for a QR Code of that dimension * @throws FormatException if dimension is not 1 mod 4 */ - pub fn getProvisionalVersionForDimension( - dimension: u32, - ) -> Result<&'static Version, Exceptions> { + pub fn getProvisionalVersionForDimension(dimension: u32) -> Result<&'static Version> { if dimension % 4 != 1 { return Err(Exceptions::FormatException(Some( "dimension incorrect".to_owned(), @@ -108,7 +109,7 @@ impl Version { Self::getVersionForNumber((dimension - 17) / 4) } - pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> { + pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version> { if !(1..=40).contains(&versionNumber) { return Err(Exceptions::IllegalArgumentException(Some( "version out of spec".to_owned(), @@ -117,7 +118,7 @@ impl Version { Ok(&VERSIONS[versionNumber as usize - 1]) } - pub fn decodeVersionInformation(versionBits: u32) -> Result<&'static Version, Exceptions> { + pub fn decodeVersionInformation(versionBits: u32) -> Result<&'static Version> { let mut bestDifference = u32::MAX; let mut bestVersion = 0; for i in 0..VERSION_DECODE_INFO.len() as u32 { @@ -146,7 +147,7 @@ impl Version { /** * See ISO 18004:2006 Annex E */ - pub fn buildFunctionPattern(&self) -> Result { + pub fn buildFunctionPattern(&self) -> Result { let dimension = self.getDimensionForVersion(); let mut bitMatrix = BitMatrix::with_single_dimension(dimension)?; diff --git a/src/qrcode/detector/alignment_pattern_finder.rs b/src/qrcode/detector/alignment_pattern_finder.rs index df3d59a..c10700e 100644 --- a/src/qrcode/detector/alignment_pattern_finder.rs +++ b/src/qrcode/detector/alignment_pattern_finder.rs @@ -14,7 +14,10 @@ * limitations under the License. */ -use crate::{common::BitMatrix, Exceptions, RXingResultPointCallback}; +use crate::{ + common::{BitMatrix, Result}, + Exceptions, RXingResultPointCallback, +}; use super::AlignmentPattern; @@ -84,7 +87,7 @@ impl AlignmentPatternFinder { * @return {@link AlignmentPattern} if found * @throws NotFoundException if not found */ - pub fn find(&mut self) -> Result { + pub fn find(&mut self) -> Result { let startX = self.startX; let height = self.height; let maxJ = startX + self.width; diff --git a/src/qrcode/detector/finder_pattern_finder.rs b/src/qrcode/detector/finder_pattern_finder.rs index 0b93a8e..c8ba971 100755 --- a/src/qrcode/detector/finder_pattern_finder.rs +++ b/src/qrcode/detector/finder_pattern_finder.rs @@ -15,8 +15,9 @@ */ use crate::{ - common::BitMatrix, result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, - Exceptions, RXingResultPointCallback, ResultPoint, + common::{BitMatrix, Result}, + result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, + RXingResultPointCallback, ResultPoint, }; use super::{FinderPattern, FinderPatternInfo}; @@ -71,10 +72,7 @@ impl<'a> FinderPatternFinder<'_> { &self.possibleCenters } - pub fn find( - &mut self, - hints: &DecodingHintDictionary, - ) -> Result { + pub fn find(&mut self, hints: &DecodingHintDictionary) -> Result { let tryHarder = matches!( hints.get(&DecodeHintType::TRY_HARDER), Some(DecodeHintValue::TryHarder(true)) @@ -692,7 +690,7 @@ impl<'a> FinderPatternFinder<'_> { * those have similar module size and form a shape closer to a isosceles right triangle. * @throws NotFoundException if 3 such finder patterns do not exist */ - fn selectBestPatterns(&mut self) -> Result<[FinderPattern; 3], Exceptions> { + fn selectBestPatterns(&mut self) -> Result<[FinderPattern; 3]> { let startSize = self.possibleCenters.len(); if startSize < 3 { // Couldn't find enough finder patterns diff --git a/src/qrcode/detector/qrcode_detector.rs b/src/qrcode/detector/qrcode_detector.rs index 6110b92..3985426 100644 --- a/src/qrcode/detector/qrcode_detector.rs +++ b/src/qrcode/detector/qrcode_detector.rs @@ -19,6 +19,7 @@ use std::collections::HashMap; use crate::{ common::{ detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler, PerspectiveTransform, + Result, }, qrcode::decoder::Version, result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, @@ -64,7 +65,7 @@ impl<'a> Detector<'_> { * @throws NotFoundException if QR Code cannot be found * @throws FormatException if a QR Code cannot be decoded */ - pub fn detect(&mut self) -> Result { + pub fn detect(&mut self) -> Result { self.detect_with_hints(&HashMap::new()) } @@ -79,7 +80,7 @@ impl<'a> Detector<'_> { pub fn detect_with_hints( &mut self, hints: &DecodingHintDictionary, - ) -> Result { + ) -> Result { self.resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) = hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK) { @@ -98,7 +99,7 @@ impl<'a> Detector<'_> { pub fn processFinderPatternInfo( &self, info: FinderPatternInfo, - ) -> Result { + ) -> Result { let topLeft = info.getTopLeft(); let topRight = info.getTopRight(); let bottomLeft = info.getBottomLeft(); @@ -218,7 +219,7 @@ impl<'a> Detector<'_> { image: &BitMatrix, transform: &PerspectiveTransform, dimension: u32, - ) -> Result { + ) -> Result { let sampler = DefaultGridSampler::default(); sampler.sample_grid(image, dimension, dimension, transform) } @@ -232,7 +233,7 @@ impl<'a> Detector<'_> { topRight: &T, bottomLeft: &T, moduleSize: f32, - ) -> Result { + ) -> Result { let tltrCentersDimension = MathUtils::round(result_point_utils::distance(topLeft, topRight) / moduleSize); let tlblCentersDimension = @@ -421,7 +422,7 @@ impl<'a> Detector<'_> { estAlignmentX: u32, estAlignmentY: u32, allowanceFactor: f32, - ) -> Result { + ) -> Result { // Look for an alignment pattern (3 modules in size) around where it // should be let allowance = (allowanceFactor * overallEstModuleSize) as u32; diff --git a/src/qrcode/encoder/mask_util.rs b/src/qrcode/encoder/mask_util.rs index 80b660c..e6d25fd 100644 --- a/src/qrcode/encoder/mask_util.rs +++ b/src/qrcode/encoder/mask_util.rs @@ -14,6 +14,7 @@ * limitations under the License. */ +use crate::common::Result; use crate::Exceptions; use super::ByteMatrix; @@ -154,7 +155,7 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 { * Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask * pattern conditions. */ -pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result { +pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result { let intermediate = match maskPattern { 0 => (y + x) & 0x1, 1 => y & 0x1, diff --git a/src/qrcode/encoder/matrix_util.rs b/src/qrcode/encoder/matrix_util.rs index f8de1a7..e476ad4 100644 --- a/src/qrcode/encoder/matrix_util.rs +++ b/src/qrcode/encoder/matrix_util.rs @@ -15,7 +15,7 @@ */ use crate::{ - common::BitArray, + common::{BitArray, Result}, qrcode::decoder::{ErrorCorrectionLevel, Version}, Exceptions, }; @@ -131,7 +131,7 @@ pub fn buildMatrix( version: &Version, maskPattern: i32, matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +) -> Result<()> { clearMatrix(matrix); embedBasicPatterns(version, matrix)?; // Type information appear with any version. @@ -149,7 +149,7 @@ pub fn buildMatrix( // - Timing patterns // - Dark dot at the left bottom corner // - Position adjustment patterns, if need be -pub fn embedBasicPatterns(version: &Version, matrix: &mut ByteMatrix) -> Result<(), Exceptions> { +pub fn embedBasicPatterns(version: &Version, matrix: &mut ByteMatrix) -> Result<()> { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix)?; // Then, embed the dark dot at the left bottom corner. @@ -167,7 +167,7 @@ pub fn embedTypeInfo( ecLevel: &ErrorCorrectionLevel, maskPattern: i32, matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +) -> Result<()> { let mut typeInfoBits = BitArray::new(); makeTypeInfoBits(ecLevel, maskPattern as u32, &mut typeInfoBits)?; @@ -204,7 +204,7 @@ pub fn embedTypeInfo( // Embed version information if need be. On success, modify the matrix and return true. // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. -pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Result<(), Exceptions> { +pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Result<()> { if version.getVersionNumber() < 7 { // Version info is necessary if version >= 7. return Ok(()); // Don't need version info. @@ -230,11 +230,7 @@ pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Resu // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. // For debugging purposes, it skips masking process if "getMaskPattern" is -1. // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. -pub fn embedDataBits( - dataBits: &BitArray, - maskPattern: i32, - matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMatrix) -> Result<()> { let mut bitIndex = 0; let mut direction: i32 = -1; // Start from the right bottom cell. @@ -321,7 +317,7 @@ pub fn findMSBSet(value: u32) -> u32 { // // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit // operations. We don't care if coefficients are positive or negative. -pub fn calculateBCHCode(value: u32, poly: u32) -> Result { +pub fn calculateBCHCode(value: u32, poly: u32) -> Result { if poly == 0 { return Err(Exceptions::IllegalArgumentException(Some( "0 polynomial".to_owned(), @@ -347,7 +343,7 @@ pub fn makeTypeInfoBits( ecLevel: &ErrorCorrectionLevel, maskPattern: u32, bits: &mut BitArray, -) -> Result<(), Exceptions> { +) -> Result<()> { if !QRCode::isValidMaskPattern(maskPattern as i32) { return Err(Exceptions::WriterException(Some( "Invalid mask pattern".to_owned(), @@ -375,7 +371,7 @@ pub fn makeTypeInfoBits( // Make bit vector of version information. On success, store the result in "bits" and return true. // See 8.10 of JISX0510:2004 (p.45) for details. -pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()> { bits.appendBits(version.getVersionNumber(), 6)?; let bchCode = calculateBCHCode(version.getVersionNumber(), VERSION_INFO_POLY)?; bits.appendBits(bchCode, 12)?; @@ -413,7 +409,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> { +pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<()> { if matrix.get(8, matrix.getHeight() - 8) == 0 { return Err(Exceptions::WriterException(None)); } @@ -425,7 +421,7 @@ pub fn embedHorizontalSeparationPattern( xStart: u32, yStart: u32, matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +) -> Result<()> { for x in 0..8 { if !isEmpty(matrix.get(xStart + x, yStart)) { return Err(Exceptions::WriterException(None)); @@ -439,7 +435,7 @@ pub fn embedVerticalSeparationPattern( xStart: u32, yStart: u32, matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +) -> Result<()> { for y in 0..7 { if !isEmpty(matrix.get(xStart, yStart + y)) { return Err(Exceptions::WriterException(None)); @@ -466,9 +462,7 @@ pub fn embedPositionDetectionPattern(xStart: u32, yStart: u32, matrix: &mut Byte } // Embed position detection patterns and surrounding vertical/horizontal separators. -pub fn embedPositionDetectionPatternsAndSeparators( - matrix: &mut ByteMatrix, -) -> Result<(), Exceptions> { +pub fn embedPositionDetectionPatternsAndSeparators(matrix: &mut ByteMatrix) -> Result<()> { // Embed three big squares at corners. let pdpWidth = POSITION_DETECTION_PATTERN[0].len() as u32; // Left top corner. diff --git a/src/qrcode/encoder/minimal_encoder.rs b/src/qrcode/encoder/minimal_encoder.rs index bd44de7..e3a6cbd 100644 --- a/src/qrcode/encoder/minimal_encoder.rs +++ b/src/qrcode/encoder/minimal_encoder.rs @@ -19,7 +19,7 @@ use std::{fmt, rc::Rc}; use encoding::EncodingRef; use crate::{ - common::{BitArray, ECIEncoderSet}, + common::{BitArray, ECIEncoderSet, Result}, qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef}, Exceptions, }; @@ -145,11 +145,11 @@ impl MinimalEncoder { priorityCharset: Option, isGS1: bool, ecLevel: ErrorCorrectionLevel, - ) -> Result { + ) -> Result { MinimalEncoder::new(stringToEncode, priorityCharset, isGS1, ecLevel).encode(version) } - pub fn encode(&self, version: Option) -> Result { + pub fn encode(&self, version: Option) -> Result { if let Some(version) = version { // compute minimal encoding for a given version let result = self.encodeSpecificVersion(version)?; @@ -202,7 +202,7 @@ impl MinimalEncoder { } } - pub fn getVersion(versionSize: VersionSize) -> Result { + pub fn getVersion(versionSize: VersionSize) -> Result { match versionSize { VersionSize::SMALL => Version::getVersionForNumber(9), VersionSize::MEDIUM => Version::getVersionForNumber(26), @@ -243,7 +243,7 @@ impl MinimalEncoder { } } - pub fn getCompactedOrdinal(mode: Option) -> Result { + pub fn getCompactedOrdinal(mode: Option) -> Result { match mode { Some(Mode::NUMERIC) => Ok(2), Some(Mode::ALPHANUMERIC) => Ok(1), @@ -260,7 +260,7 @@ impl MinimalEncoder { edges: &mut [Vec>>>], position: usize, edge: Option>, - ) -> Result<(), Exceptions> { + ) -> Result<()> { let vertexIndex = position + edge .as_ref() @@ -295,7 +295,7 @@ impl MinimalEncoder { edges: &mut [Vec>>>], from: usize, previous: Option>, - ) -> Result<(), Exceptions> { + ) -> Result<()> { let mut start = 0; let mut end = self.encoders.len(); let priorityEncoderIndex = self.encoders.getPriorityEncoderIndex(); @@ -452,10 +452,7 @@ impl MinimalEncoder { Ok(()) } - pub fn encodeSpecificVersion( - &self, - version: VersionRef, - ) -> Result { + pub fn encodeSpecificVersion(&self, version: VersionRef) -> Result { // @SuppressWarnings("checkstyle:lineLength") /* A vertex represents a tuple of a position in the input, a mode and a character encoding where position 0 * denotes the position left of the first character, 1 the position left of the second character and so on. @@ -869,7 +866,7 @@ impl RXingResultList { /** * appends the bits */ - pub fn getBits(&self, bits: &mut BitArray) -> Result<(), Exceptions> { + pub fn getBits(&self, bits: &mut BitArray) -> Result<()> { for resultNode in &self.list { resultNode.getBits(bits)?; } @@ -1008,7 +1005,7 @@ impl RXingResultNode { /** * appends the bits */ - fn getBits(&self, bits: &mut BitArray) -> Result<(), Exceptions> { + fn getBits(&self, bits: &mut BitArray) -> Result<()> { bits.appendBits(self.mode.getBits() as u32, 4)?; if self.characterLength > 0 { let length = self.getCharacterCountIndicator(); diff --git a/src/qrcode/encoder/qrcode_encoder.rs b/src/qrcode/encoder/qrcode_encoder.rs index a6d21ac..50b5ad6 100644 --- a/src/qrcode/encoder/qrcode_encoder.rs +++ b/src/qrcode/encoder/qrcode_encoder.rs @@ -27,7 +27,7 @@ use unicode_segmentation::UnicodeSegmentation; use crate::{ common::{ reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonEncoder}, - BitArray, CharacterSetECI, + BitArray, CharacterSetECI, Result, }, qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef}, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Exceptions, @@ -66,7 +66,7 @@ pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 { * @throws WriterException if encoding can't succeed, because of for example invalid content * or configuration */ -pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result { +pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result { encode_with_hints(content, ecLevel, &HashMap::new()) } @@ -74,7 +74,7 @@ pub fn encode_with_hints( content: &str, ec_level: ErrorCorrectionLevel, hints: &EncodingHintDictionary, -) -> Result { +) -> Result { let version; let mut header_and_data_bits; let mode; @@ -264,7 +264,7 @@ fn recommendVersion( mode: Mode, header_bits: &BitArray, data_bits: &BitArray, -) -> Result { +) -> Result { // Hard part: need to know version to know how many bits length takes. But need to know how many // bits it takes to know version. First we take a guess at version by assuming version will be // the minimum, 1: @@ -365,7 +365,7 @@ fn chooseMaskPattern( ec_level: &ErrorCorrectionLevel, version: VersionRef, matrix: &mut ByteMatrix, -) -> Result { +) -> Result { let mut min_penalty = u32::MAX; // Lower penalty is better. let mut best_mask_pattern = -1; // We try all mask patterns to choose the best one. @@ -381,10 +381,7 @@ fn chooseMaskPattern( Ok(best_mask_pattern as u32) } -fn chooseVersion( - numInputBits: u32, - ecLevel: &ErrorCorrectionLevel, -) -> Result { +fn chooseVersion(numInputBits: u32, ecLevel: &ErrorCorrectionLevel) -> Result { for versionNum in 1..=40 { let version = Version::getVersionForNumber(versionNum)?; if willFit(numInputBits, version, ecLevel) { @@ -416,7 +413,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection /** * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). */ -pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<()> { let capacity = num_data_bytes * 8; if bits.getSize() > capacity as usize { return Err(Exceptions::WriterException(Some(format!( @@ -466,7 +463,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID( block_id: u32, // numDataBytesInBlock: &mut [u32], // numECBytesInBlock: &mut [u32], -) -> Result<(u32, u32), Exceptions> { +) -> Result<(u32, u32)> { if block_id >= num_rsblocks { return Err(Exceptions::WriterException(Some( "Block ID too large".to_owned(), @@ -527,7 +524,7 @@ pub fn interleaveWithECBytes( num_total_bytes: u32, num_data_bytes: u32, num_rsblocks: u32, -) -> Result { +) -> Result { // "bits" must have "getNumDataBytes" bytes of data. if bits.getSizeInBytes() as u32 != num_data_bytes { return Err(Exceptions::WriterException(Some( @@ -602,10 +599,7 @@ pub fn interleaveWithECBytes( Ok(result) } -pub fn generateECBytes( - dataBytes: &[u8], - num_ec_bytes_in_block: usize, -) -> Result, Exceptions> { +pub fn generateECBytes(dataBytes: &[u8], num_ec_bytes_in_block: usize) -> Result> { let num_data_bytes = dataBytes.len(); let mut to_encode = vec![0; num_data_bytes + num_ec_bytes_in_block]; for i in 0..num_data_bytes { @@ -627,7 +621,7 @@ pub fn generateECBytes( /** * Append mode info. On success, store the result in "bits". */ -pub fn appendModeInfo(mode: Mode, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn appendModeInfo(mode: Mode, bits: &mut BitArray) -> Result<()> { bits.appendBits(mode.getBits() as u32, 4) } @@ -639,7 +633,7 @@ pub fn appendLengthInfo( version: VersionRef, mode: Mode, bits: &mut BitArray, -) -> Result<(), Exceptions> { +) -> Result<()> { let numBits = mode.getCharacterCountBits(version); if num_letters >= (1 << numBits) { return Err(Exceptions::WriterException(Some(format!( @@ -659,7 +653,7 @@ pub fn appendBytes( mode: Mode, bits: &mut BitArray, encoding: EncodingRef, -) -> Result<(), Exceptions> { +) -> Result<()> { match mode { Mode::NUMERIC => appendNumericBytes(content, bits), Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits), @@ -671,7 +665,7 @@ pub fn appendBytes( } } -pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> { let length = content.len(); let mut i = 0; while i < length { @@ -712,7 +706,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce Ok(()) } -pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()> { let length = content.len(); let mut i = 0; while i < length { @@ -747,11 +741,7 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Ok(()) } -pub fn append8BitBytes( - content: &str, - bits: &mut BitArray, - encoding: EncodingRef, -) -> Result<(), Exceptions> { +pub fn append8BitBytes(content: &str, bits: &mut BitArray, encoding: EncodingRef) -> Result<()> { let bytes = encoding .encode(content, encoding::EncoderTrap::Strict) .map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?; @@ -761,7 +751,7 @@ pub fn append8BitBytes( Ok(()) } -pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> { +pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> { let sjis = &SHIFT_JIS_CHARSET; let bytes = sjis @@ -797,7 +787,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except Ok(()) } -fn appendECI(eci: &CharacterSetECI, bits: &mut BitArray) -> Result<(), Exceptions> { +fn appendECI(eci: &CharacterSetECI, bits: &mut BitArray) -> Result<()> { bits.appendBits(Mode::ECI.getBits() as u32, 4)?; // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.getValueSelf(), 8) diff --git a/src/qrcode/qr_code_reader.rs b/src/qrcode/qr_code_reader.rs index 023eb98..2e9e5a9 100644 --- a/src/qrcode/qr_code_reader.rs +++ b/src/qrcode/qr_code_reader.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use crate::{ - common::{BitMatrix, DecoderRXingResult, DetectorRXingResult}, + common::{BitMatrix, DecoderRXingResult, DetectorRXingResult, Result}, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, }; @@ -48,10 +48,7 @@ impl Reader for QRCodeReader { * @throws FormatException if a QR code cannot be decoded * @throws ChecksumException if error correction fails */ - fn decode( - &mut self, - image: &mut crate::BinaryBitmap, - ) -> Result { + fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result { self.decode_with_hints(image, &HashMap::new()) } @@ -59,7 +56,7 @@ impl Reader for QRCodeReader { &mut self, image: &mut crate::BinaryBitmap, hints: &crate::DecodingHintDictionary, - ) -> Result { + ) -> Result { let decoderRXingResult: DecoderRXingResult; let mut points: Vec; if matches!( @@ -149,7 +146,7 @@ impl QRCodeReader { * around it. This is a specialized method that works exceptionally fast in this special * case. */ - fn extractPureBits(image: &BitMatrix) -> Result { + fn extractPureBits(image: &BitMatrix) -> Result { let leftTopBlack = image.getTopLeftOnBit(); let rightBottomBlack = image.getBottomRightOnBit(); if leftTopBlack.is_none() || rightBottomBlack.is_none() { @@ -233,7 +230,7 @@ impl QRCodeReader { Ok(bits) } - fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result { + fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result { let height = image.getHeight(); let width = image.getWidth(); let mut x = leftTopBlack[0]; diff --git a/src/qrcode/qr_code_writer.rs b/src/qrcode/qr_code_writer.rs index b3a458a..d374156 100644 --- a/src/qrcode/qr_code_writer.rs +++ b/src/qrcode/qr_code_writer.rs @@ -17,7 +17,8 @@ use std::collections::HashMap; use crate::{ - common::BitMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, + common::{BitMatrix, Result}, + BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, }; use super::{ @@ -45,7 +46,7 @@ impl Writer for QRCodeWriter { format: &crate::BarcodeFormat, width: i32, height: i32, - ) -> Result { + ) -> Result { self.encode_with_hints(contents, format, width, height, &HashMap::new()) } @@ -56,7 +57,7 @@ impl Writer for QRCodeWriter { width: i32, height: i32, hints: &crate::EncodingHintDictionary, - ) -> Result { + ) -> Result { if contents.is_empty() { return Err(Exceptions::IllegalArgumentException(Some( "found empty contents".to_owned(), @@ -107,7 +108,7 @@ impl QRCodeWriter { width: i32, height: i32, quietZone: i32, - ) -> Result { + ) -> Result { let input = code.getMatrix(); if input.is_none() { return Err(Exceptions::IllegalStateException(Some( diff --git a/src/reader.rs b/src/reader.rs index 5224f9a..ca54467 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -16,7 +16,7 @@ //package com.google.zxing; -use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult}; +use crate::{common::Result, BinaryBitmap, DecodingHintDictionary, RXingResult}; /** * Implementations of this interface can decode an image of a barcode in some format into @@ -40,7 +40,7 @@ pub trait Reader { * @throws ChecksumException if a potential barcode is found but does not pass its checksum * @throws FormatException if a potential barcode is found but format is invalid */ - fn decode(&mut self, image: &mut BinaryBitmap) -> Result; + fn decode(&mut self, image: &mut BinaryBitmap) -> Result; /** * Locates and decodes a barcode in some format within an image. This method also accepts @@ -60,7 +60,7 @@ pub trait Reader { &mut self, image: &mut BinaryBitmap, hints: &DecodingHintDictionary, - ) -> Result; + ) -> Result; /** * Resets any internal state the implementation has after a decode, to prepare it diff --git a/src/rgb_luminance_source.rs b/src/rgb_luminance_source.rs index a069a32..7d8fe59 100644 --- a/src/rgb_luminance_source.rs +++ b/src/rgb_luminance_source.rs @@ -16,6 +16,7 @@ //package com.google.zxing; +use crate::common::Result; use crate::{Exceptions, LuminanceSource}; /** @@ -116,7 +117,7 @@ impl LuminanceSource for RGBLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, Exceptions> { + ) -> Result> { match RGBLuminanceSource::new_complex( &self.luminances, self.dataWidth, @@ -177,7 +178,7 @@ impl RGBLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result { + ) -> Result { if left + width > data_width || top + height > data_height { return Err(Exceptions::IllegalArgumentException(Some( "Crop rectangle does not fit within image data.".to_owned(), diff --git a/src/svg_luminance_source.rs b/src/svg_luminance_source.rs index f0c31ed..ee61438 100644 --- a/src/svg_luminance_source.rs +++ b/src/svg_luminance_source.rs @@ -1,3 +1,4 @@ +use crate::common::Result; use crate::{BufferedImageLuminanceSource, Exceptions, LuminanceSource}; use image::{DynamicImage, RgbaImage}; use resvg::{self, usvg::Options}; @@ -35,7 +36,7 @@ impl LuminanceSource for SVGLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, Exceptions> { + ) -> Result> { self.0.crop(left, top, width, height) } @@ -43,17 +44,17 @@ impl LuminanceSource for SVGLuminanceSource { self.0.isRotateSupported() } - fn rotateCounterClockwise(&self) -> Result, Exceptions> { + fn rotateCounterClockwise(&self) -> Result> { self.0.rotateCounterClockwise() } - fn rotateCounterClockwise45(&self) -> Result, Exceptions> { + fn rotateCounterClockwise45(&self) -> Result> { self.0.rotateCounterClockwise45() } } impl SVGLuminanceSource { - pub fn new(svg_data: &[u8]) -> Result { + 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")))); diff --git a/src/writer.rs b/src/writer.rs index f07064d..29f59f0 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -16,7 +16,10 @@ //package com.google.zxing; -use crate::{common::BitMatrix, BarcodeFormat, EncodingHintDictionary, Exceptions}; +use crate::{ + common::{BitMatrix, Result}, + BarcodeFormat, EncodingHintDictionary, +}; /** * The base class for all objects which encode/generate a barcode image. @@ -40,7 +43,7 @@ pub trait Writer { format: &BarcodeFormat, width: i32, height: i32, - ) -> Result; + ) -> Result; /** * @param contents The contents to encode in the barcode @@ -58,5 +61,5 @@ pub trait Writer { width: i32, height: i32, hints: &EncodingHintDictionary, - ) -> Result; + ) -> Result; } diff --git a/tests/common/abstract_black_box_test_case.rs b/tests/common/abstract_black_box_test_case.rs index 2225097..bb24d9c 100644 --- a/tests/common/abstract_black_box_test_case.rs +++ b/tests/common/abstract_black_box_test_case.rs @@ -26,9 +26,10 @@ use std::{ use encoding::Encoding; use rxing::{ - common::HybridBinarizer, pdf417::PDF417RXingResultMetadata, BarcodeFormat, BinaryBitmap, - BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue, RXingResultMetadataType, - RXingResultMetadataValue, Reader, + common::{HybridBinarizer, Result}, + pdf417::PDF417RXingResultMetadata, + BarcodeFormat, BinaryBitmap, BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue, + RXingResultMetadataType, RXingResultMetadataValue, Reader, }; use super::TestRXingResult; @@ -428,7 +429,7 @@ impl AbstractBlackBoxTestCase { expected_text: &str, expected_metadata: &HashMap, try_harder: bool, - ) -> Result { + ) -> Result { let suffix = format!( " ({}rotation: {})", if try_harder { "try harder, " } else { "" }, diff --git a/tests/common/pdf_417_multiimage_span.rs b/tests/common/pdf_417_multiimage_span.rs index b2d01f4..7a98925 100644 --- a/tests/common/pdf_417_multiimage_span.rs +++ b/tests/common/pdf_417_multiimage_span.rs @@ -25,9 +25,11 @@ use std::{ use encoding::Encoding; use rxing::{ - common::HybridBinarizer, multi::MultipleBarcodeReader, pdf417::PDF417RXingResultMetadata, + common::{HybridBinarizer, Result}, + multi::MultipleBarcodeReader, + pdf417::PDF417RXingResultMetadata, BarcodeFormat, BinaryBitmap, BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue, - Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, Reader, + RXingResult, RXingResultMetadataType, RXingResultMetadataValue, Reader, }; use super::TestRXingResult; @@ -571,7 +573,7 @@ impl PDF417MultiImageSpanAbstractBlackBoxTest expected_text: &str, expected_metadata: &HashMap, try_harder: bool, - ) -> Result { + ) -> Result { let suffix = format!( " ({}rotation: {})", if try_harder { "try harder, " } else { "" }, @@ -756,7 +758,7 @@ impl PDF417MultiImageSpanAbstractBlackBoxTest source: &mut BinaryBitmap, try_harder: bool, barcode_reader: &mut T, - ) -> Result, Exceptions> { + ) -> Result> { let mut hints = HashMap::new(); //new EnumMap<>(DecodeHintType.class); if try_harder { hints.insert(DecodeHintType::TRY_HARDER, DecodeHintValue::TryHarder(true));