refactor to use common result type

This commit is contained in:
Vukašin Stepanović
2023-02-14 22:56:03 +00:00
parent 145cf704fe
commit 8ee616d96b
160 changed files with 829 additions and 901 deletions

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{DecoderRXingResult, DetectorRXingResult}, common::{DecoderRXingResult, DetectorRXingResult, Result},
exceptions::Exceptions, exceptions::Exceptions,
BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, RXingResult, BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, RXingResult,
RXingResultMetadataType, RXingResultMetadataValue, Reader, RXingResultMetadataType, RXingResultMetadataValue, Reader,
@@ -41,7 +41,7 @@ impl Reader for AztecReader {
* @throws NotFoundException if a Data Matrix code cannot be found * @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded * @throws FormatException if a Data Matrix code cannot be decoded
*/ */
fn decode(&mut self, image: &mut BinaryBitmap) -> Result<RXingResult, Exceptions> { fn decode(&mut self, image: &mut BinaryBitmap) -> Result<RXingResult> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -49,7 +49,7 @@ impl Reader for AztecReader {
&mut self, &mut self,
image: &mut BinaryBitmap, image: &mut BinaryBitmap,
hints: &HashMap<DecodeHintType, DecodeHintValue>, hints: &HashMap<DecodeHintType, DecodeHintValue>,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
// let notFoundException = None; // let notFoundException = None;
// let formatException = None; // let formatException = None;
let mut detector = Detector::new(image.getBlackMatrix()); let mut detector = Detector::new(image.getBlackMatrix());

View File

@@ -19,8 +19,9 @@ use std::collections::HashMap;
use encoding::EncodingRef; use encoding::EncodingRef;
use crate::{ use crate::{
common::BitMatrix, exceptions::Exceptions, BarcodeFormat, EncodeHintType, EncodeHintValue, common::{BitMatrix, Result},
Writer, exceptions::Exceptions,
BarcodeFormat, EncodeHintType, EncodeHintValue, Writer,
}; };
use super::encoder::{aztec_encoder, AztecCode}; use super::encoder::{aztec_encoder, AztecCode};
@@ -38,7 +39,7 @@ impl Writer for AztecWriter {
format: &crate::BarcodeFormat, format: &crate::BarcodeFormat,
width: i32, width: i32,
height: i32, height: i32,
) -> Result<crate::common::BitMatrix, crate::exceptions::Exceptions> { ) -> Result<crate::common::BitMatrix> {
self.encode_with_hints(contents, format, width, height, &HashMap::new()) self.encode_with_hints(contents, format, width, height, &HashMap::new())
} }
@@ -49,7 +50,7 @@ impl Writer for AztecWriter {
width: i32, width: i32,
height: i32, height: i32,
hints: &std::collections::HashMap<crate::EncodeHintType, crate::EncodeHintValue>, hints: &std::collections::HashMap<crate::EncodeHintType, crate::EncodeHintValue>,
) -> Result<crate::common::BitMatrix, crate::exceptions::Exceptions> { ) -> Result<crate::common::BitMatrix> {
let mut charset = None; // Do not add any ECI code by default let mut charset = None; // Do not add any ECI code by default
let mut ecc_percent = aztec_encoder::DEFAULT_EC_PERCENT; let mut ecc_percent = aztec_encoder::DEFAULT_EC_PERCENT;
let mut layers = aztec_encoder::DEFAULT_AZTEC_LAYERS; let mut layers = aztec_encoder::DEFAULT_AZTEC_LAYERS;
@@ -93,7 +94,7 @@ fn encode(
charset: Option<EncodingRef>, charset: Option<EncodingRef>,
ecc_percent: u32, ecc_percent: u32,
layers: i32, layers: i32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
if format != BarcodeFormat::AZTEC { if format != BarcodeFormat::AZTEC {
return Err(Exceptions::IllegalArgumentException(Some(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"can only encode AZTEC, but got {format:?}" "can only encode AZTEC, but got {format:?}"
@@ -108,7 +109,7 @@ fn encode(
renderRXingResult(&aztec, width, height) renderRXingResult(&aztec, width, height)
} }
fn renderRXingResult(code: &AztecCode, width: u32, height: u32) -> Result<BitMatrix, Exceptions> { fn renderRXingResult(code: &AztecCode, width: u32, height: u32) -> Result<BitMatrix> {
let input = code.getMatrix(); let input = code.getMatrix();
let input_width = input.getWidth(); let input_width = input.getWidth();

View File

@@ -19,7 +19,7 @@ use crate::{
reedsolomon::{ reedsolomon::{
get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonDecoder, get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonDecoder,
}, },
BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult, BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult, Result,
}, },
exceptions::Exceptions, exceptions::Exceptions,
}; };
@@ -73,9 +73,7 @@ const DIGIT_TABLE: [&str; 16] = [
// private AztecDetectorRXingResult ddata; // private AztecDetectorRXingResult ddata;
pub fn decode( pub fn decode(detectorRXingResult: &AztecDetectorRXingResult) -> Result<DecoderRXingResult> {
detectorRXingResult: &AztecDetectorRXingResult,
) -> Result<DecoderRXingResult, Exceptions> {
//let mut detectorRXingResult = detectorRXingResult.clone(); //let mut detectorRXingResult = detectorRXingResult.clone();
let matrix = detectorRXingResult.getBits(); let matrix = detectorRXingResult.getBits();
let rawbits = extract_bits(detectorRXingResult, matrix); let rawbits = extract_bits(detectorRXingResult, matrix);
@@ -94,7 +92,7 @@ pub fn decode(
} }
/// This method is used for testing the high-level encoder /// This method is used for testing the high-level encoder
pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String, Exceptions> { pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String> {
get_encoded_data(correctedBits) get_encoded_data(correctedBits)
} }
@@ -103,7 +101,7 @@ pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String, Exceptions> {
* *
* @return the decoded string * @return the decoded string
*/ */
fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> { fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
let end_index = corrected_bits.len(); let end_index = corrected_bits.len();
let mut latch_table = Table::Upper; // table most recently latched to let mut latch_table = Table::Upper; // table most recently latched to
let mut shift_table = Table::Upper; // table to use for the next read let mut 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 table the table used
* @param code the code of the character * @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 { match table {
Table::Upper => Ok(UPPER_TABLE[code as usize]), Table::Upper => Ok(UPPER_TABLE[code as usize]),
Table::Lower => Ok(LOWER_TABLE[code as usize]), Table::Lower => Ok(LOWER_TABLE[code as usize]),
@@ -337,7 +335,7 @@ impl CorrectedBitsRXingResult {
fn correct_bits( fn correct_bits(
ddata: &AztecDetectorRXingResult, ddata: &AztecDetectorRXingResult,
rawbits: &[bool], rawbits: &[bool],
) -> Result<CorrectedBitsRXingResult, Exceptions> { ) -> Result<CorrectedBitsRXingResult> {
let gf: GenericGFRef; let gf: GenericGFRef;
let codeword_size; let codeword_size;

View File

@@ -20,7 +20,7 @@ use crate::{
common::{ common::{
detector::{MathUtils, WhiteRectangleDetector}, detector::{MathUtils, WhiteRectangleDetector},
reedsolomon::{self, ReedSolomonDecoder}, reedsolomon::{self, ReedSolomonDecoder},
BitMatrix, DefaultGridSampler, GridSampler, BitMatrix, DefaultGridSampler, GridSampler, Result,
}, },
exceptions::Exceptions, exceptions::Exceptions,
RXingResultPoint, ResultPoint, RXingResultPoint, ResultPoint,
@@ -64,7 +64,7 @@ impl<'a> Detector<'_> {
} }
} }
pub fn detect_false(&mut self) -> Result<AztecDetectorRXingResult, Exceptions> { pub fn detect_false(&mut self) -> Result<AztecDetectorRXingResult> {
self.detect(false) self.detect(false)
} }
@@ -75,7 +75,7 @@ impl<'a> Detector<'_> {
* @return {@link AztecDetectorRXingResult} encapsulating results of detecting an Aztec Code * @return {@link AztecDetectorRXingResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException if no Aztec Code can be found * @throws NotFoundException if no Aztec Code can be found
*/ */
pub fn detect(&mut self, is_mirror: bool) -> Result<AztecDetectorRXingResult, Exceptions> { pub fn detect(&mut self, is_mirror: bool) -> Result<AztecDetectorRXingResult> {
// dbg!(self.image.to_string()); // dbg!(self.image.to_string());
// 1. Get the center of the aztec matrix // 1. Get the center of the aztec matrix
let p_center = self.get_matrix_center(); let p_center = self.get_matrix_center();
@@ -118,10 +118,7 @@ impl<'a> Detector<'_> {
* @param bullsEyeCorners the array of bull's eye corners * @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters * @throws NotFoundException in case of too many errors or invalid parameters
*/ */
fn extractParameters( fn extractParameters(&mut self, bulls_eye_corners: &[RXingResultPoint]) -> Result<()> {
&mut self,
bulls_eye_corners: &[RXingResultPoint],
) -> Result<(), Exceptions> {
if !self.is_valid(&bulls_eye_corners[0]) if !self.is_valid(&bulls_eye_corners[0])
|| !self.is_valid(&bulls_eye_corners[1]) || !self.is_valid(&bulls_eye_corners[1])
|| !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[2])
@@ -179,7 +176,7 @@ impl<'a> Detector<'_> {
Ok(()) Ok(())
} }
fn get_rotation(sides: &[u32], length: u32) -> Result<u32, Exceptions> { fn get_rotation(sides: &[u32], length: u32) -> Result<u32> {
// In a normal pattern, we expect to See // In a normal pattern, we expect to See
// ** .* D A // ** .* D A
// * * // * *
@@ -222,7 +219,7 @@ impl<'a> Detector<'_> {
* @param compact true if this is a compact Aztec code * @param compact true if this is a compact Aztec code
* @throws NotFoundException if the array contains too many errors * @throws NotFoundException if the array contains too many errors
*/ */
fn get_corrected_parameter_data(parameterData: u64, compact: bool) -> Result<u32, Exceptions> { fn get_corrected_parameter_data(parameterData: u64, compact: bool) -> Result<u32> {
let mut parameter_data = parameterData; let mut parameter_data = parameterData;
let num_codewords: i32; let num_codewords: i32;
@@ -269,10 +266,7 @@ impl<'a> Detector<'_> {
* @return The corners of the bull-eye * @return The corners of the bull-eye
* @throws NotFoundException If no valid bull-eye can be found * @throws NotFoundException If no valid bull-eye can be found
*/ */
fn get_bulls_eye_corners( fn get_bulls_eye_corners(&mut self, pCenter: Point) -> Result<[RXingResultPoint; 4]> {
&mut self,
pCenter: Point,
) -> Result<[RXingResultPoint; 4], Exceptions> {
let mut pina = pCenter; let mut pina = pCenter;
let mut pinb = pCenter; let mut pinb = pCenter;
let mut pinc = pCenter; let mut pinc = pCenter;
@@ -504,7 +498,7 @@ impl<'a> Detector<'_> {
top_right: &RXingResultPoint, top_right: &RXingResultPoint,
bottom_right: &RXingResultPoint, bottom_right: &RXingResultPoint,
bottom_left: &RXingResultPoint, bottom_left: &RXingResultPoint,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let sampler = DefaultGridSampler::default(); let sampler = DefaultGridSampler::default();
let dimension = self.get_dimension(); let dimension = self.get_dimension();

View File

@@ -21,7 +21,7 @@ use crate::{
reedsolomon::{ reedsolomon::{
get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder, get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder,
}, },
BitArray, BitMatrix, BitArray, BitMatrix, Result,
}, },
exceptions::Exceptions, 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) * @param data input data string; must be encodable as ISO/IEC 8859-1 (Latin-1)
* @return Aztec symbol matrix with metadata * @return Aztec symbol matrix with metadata
*/ */
pub fn encode_simple(data: &str) -> Result<AztecCode, Exceptions> { pub fn encode_simple(data: &str) -> Result<AztecCode> {
let Ok(bytes) = encoding::all::ISO_8859_1 let Ok(bytes) = encoding::all::ISO_8859_1
.encode(data, encoding::EncoderTrap::Replace) else { .encode(data, encoding::EncoderTrap::Replace) else {
return Err(Exceptions::IllegalArgumentException(Some(format!("'{data}' cannot be encoded as ISO_8859_1")))); 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<AztecCode, Exceptions> {
* @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers * @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers
* @return Aztec symbol matrix with metadata * @return Aztec symbol matrix with metadata
*/ */
pub fn encode( pub fn encode(data: &str, minECCPercent: u32, userSpecifiedLayers: i32) -> Result<AztecCode> {
data: &str,
minECCPercent: u32,
userSpecifiedLayers: i32,
) -> Result<AztecCode, Exceptions> {
if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) { if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) {
encode_bytes(&bytes, minECCPercent, userSpecifiedLayers) encode_bytes(&bytes, minECCPercent, userSpecifiedLayers)
} else { } else {
@@ -98,7 +94,7 @@ pub fn encode_with_charset(
minECCPercent: u32, minECCPercent: u32,
userSpecifiedLayers: i32, userSpecifiedLayers: i32,
charset: encoding::EncodingRef, charset: encoding::EncodingRef,
) -> Result<AztecCode, Exceptions> { ) -> Result<AztecCode> {
if let Ok(bytes) = charset.encode(data, encoding::EncoderTrap::Strict) { if let Ok(bytes) = charset.encode(data, encoding::EncoderTrap::Strict) {
encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset) encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset)
} else { } else {
@@ -114,7 +110,7 @@ pub fn encode_with_charset(
* @param data input data string * @param data input data string
* @return Aztec symbol matrix with metadata * @return Aztec symbol matrix with metadata
*/ */
pub fn encode_bytes_simple(data: &[u8]) -> Result<AztecCode, Exceptions> { pub fn encode_bytes_simple(data: &[u8]) -> Result<AztecCode> {
encode_bytes(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS) encode_bytes(data, DEFAULT_EC_PERCENT, DEFAULT_AZTEC_LAYERS)
} }
@@ -131,7 +127,7 @@ pub fn encode_bytes(
data: &[u8], data: &[u8],
minECCPercent: u32, minECCPercent: u32,
userSpecifiedLayers: i32, userSpecifiedLayers: i32,
) -> Result<AztecCode, Exceptions> { ) -> Result<AztecCode> {
encode_bytes_with_charset( encode_bytes_with_charset(
data, data,
minECCPercent, minECCPercent,
@@ -156,7 +152,7 @@ pub fn encode_bytes_with_charset(
min_eccpercent: u32, min_eccpercent: u32,
user_specified_layers: i32, user_specified_layers: i32,
charset: encoding::EncodingRef, charset: encoding::EncodingRef,
) -> Result<AztecCode, Exceptions> { ) -> Result<AztecCode> {
// High-level encode // High-level encode
let bits = HighLevelEncoder::with_charset(data.into(), charset).encode()?; let bits = HighLevelEncoder::with_charset(data.into(), charset).encode()?;
@@ -378,7 +374,7 @@ pub fn generateModeMessage(
compact: bool, compact: bool,
layers: u32, layers: u32,
messageSizeInWords: u32, messageSizeInWords: u32,
) -> Result<BitArray, Exceptions> { ) -> Result<BitArray> {
let mut mode_message = BitArray::new(); let mut mode_message = BitArray::new();
if compact { if compact {
mode_message.appendBits(layers - 1, 2)?; mode_message.appendBits(layers - 1, 2)?;
@@ -431,11 +427,7 @@ fn drawModeMessage(matrix: &mut BitMatrix, compact: bool, matrixSize: u32, modeM
} }
} }
fn generateCheckWords( fn generateCheckWords(bitArray: &BitArray, totalBits: usize, wordSize: usize) -> Result<BitArray> {
bitArray: &BitArray,
totalBits: usize,
wordSize: usize,
) -> Result<BitArray, Exceptions> {
// bitArray is guaranteed to be a multiple of the wordSize, so no padding needed // bitArray is guaranteed to be a multiple of the wordSize, so no padding needed
let message_size_in_words = bitArray.getSize() / wordSize; let message_size_in_words = bitArray.getSize() / wordSize;
let mut rs = ReedSolomonEncoder::new(getGF(wordSize)?)?; let mut rs = ReedSolomonEncoder::new(getGF(wordSize)?)?;
@@ -475,7 +467,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve
message message
} }
fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> { fn getGF(wordSize: usize) -> Result<GenericGFRef> {
match wordSize { match wordSize {
4 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecParam)), 4 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecParam)),
6 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData6)), 6 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData6)),
@@ -488,7 +480,7 @@ fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> {
} }
} }
pub fn stuffBits(bits: &BitArray, word_size: usize) -> Result<BitArray, Exceptions> { pub fn stuffBits(bits: &BitArray, word_size: usize) -> Result<BitArray> {
let mut out = BitArray::new(); let mut out = BitArray::new();
let n = bits.getSize() as isize; let n = bits.getSize() as isize;

View File

@@ -16,7 +16,7 @@
use std::fmt; use std::fmt;
use crate::{common::BitArray, Exceptions}; use crate::common::{BitArray, Result};
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub struct BinaryShiftToken { 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; let bsbc = self.binary_shift_byte_count as usize;
for i in 0..bsbc { for i in 0..bsbc {
// for (int i = 0; i < bsbc; i++) { // for (int i = 0; i < bsbc; i++) {

View File

@@ -15,7 +15,7 @@
*/ */
use crate::{ use crate::{
common::{BitArray, CharacterSetECI}, common::{BitArray, CharacterSetECI, Result},
exceptions::Exceptions, exceptions::Exceptions,
}; };
@@ -240,7 +240,7 @@ impl HighLevelEncoder {
/** /**
* @return text represented by this encoder encoded as a {@link BitArray} * @return text represented by this encoder encoded as a {@link BitArray}
*/ */
pub fn encode(&self) -> Result<BitArray, Exceptions> { pub fn encode(&self) -> Result<BitArray> {
let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0); let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0);
if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) { if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) {
if eci != CharacterSetECI::ISO8859_1 { if eci != CharacterSetECI::ISO8859_1 {

View File

@@ -16,7 +16,7 @@
use std::fmt; use std::fmt;
use crate::{common::BitArray, Exceptions}; use crate::common::{BitArray, Result};
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub struct SimpleToken { 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) bit_array.appendBits(self.value as u32, self.bit_count as usize)
} }

View File

@@ -18,7 +18,10 @@ use std::fmt;
use encoding::Encoding; use encoding::Encoding;
use crate::{common::BitArray, exceptions::Exceptions}; use crate::{
common::{BitArray, Result},
exceptions::Exceptions,
};
use super::{HighLevelEncoder, Token}; use super::{HighLevelEncoder, Token};
@@ -70,7 +73,7 @@ impl State {
self.bit_count self.bit_count
} }
pub fn appendFLGn(self, eci: u32) -> Result<Self, Exceptions> { pub fn appendFLGn(self, eci: u32) -> Result<Self> {
let bit_count = self.bit_count; let bit_count = self.bit_count;
let mode = self.mode; let mode = self.mode;
let result = self.shiftAndAppend(HighLevelEncoder::MODE_PUNCT as u32, 0); // 0: FLG(n) 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 new_mode_bit_count <= other.bit_count
} }
pub fn toBitArray(self, text: &[u8]) -> Result<BitArray, Exceptions> { pub fn toBitArray(self, text: &[u8]) -> Result<BitArray> {
let mut symbols = Vec::new(); let mut symbols = Vec::new();
let tok = self.endBinaryShift(text.len() as u32).token; let tok = self.endBinaryShift(text.len() as u32).token;
for tkn in tok.into_iter() { for tkn in tok.into_iter() {

View File

@@ -14,7 +14,10 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{common::BitArray, Exceptions}; use crate::{
common::{BitArray, Result},
Exceptions,
};
use super::{BinaryShiftToken, SimpleToken}; use super::{BinaryShiftToken, SimpleToken};
@@ -26,7 +29,7 @@ pub enum TokenType {
} }
impl 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]; // let token = &self.tokens[self.current_pointer];
match self { match self {
TokenType::Simple(a) => a.appendTo(bit_array, text), TokenType::Simple(a) => a.appendTo(bit_array, text),

View File

@@ -19,8 +19,8 @@
use std::{borrow::Cow, rc::Rc}; use std::{borrow::Cow, rc::Rc};
use crate::{ use crate::{
common::{BitArray, BitMatrix}, common::{BitArray, BitMatrix, Result},
Exceptions, LuminanceSource, LuminanceSource,
}; };
/** /**
@@ -51,7 +51,7 @@ pub trait Binarizer {
* @return The array of bits for this row (true means black). * @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized * @throws NotFoundException if row can't be binarized
*/ */
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions>; fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>>;
/** /**
* Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive * 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). * @return The 2D array of bits for the image (true means black).
* @throws NotFoundException if image can't be binarized to make a matrix * @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 * Creates a new object with the same type as this Binarizer implementation, but with pristine

View File

@@ -19,8 +19,8 @@
use std::{borrow::Cow, fmt, rc::Rc}; use std::{borrow::Cow, fmt, rc::Rc};
use crate::{ use crate::{
common::{BitArray, BitMatrix}, common::{BitArray, BitMatrix, Result},
Binarizer, Exceptions, Binarizer,
}; };
/** /**
@@ -68,7 +68,7 @@ impl BinaryBitmap {
* @return The array of bits for this row (true means black). * @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized * @throws NotFoundException if row can't be binarized
*/ */
pub fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions> { pub fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
self.binarizer.getBlackRow(y) self.binarizer.getBlackRow(y)
} }

View File

@@ -19,6 +19,7 @@ use std::rc::Rc;
use image::{DynamicImage, ImageBuffer, Luma}; use image::{DynamicImage, ImageBuffer, Luma};
use imageproc::geometric_transformations::rotate_about_center; use imageproc::geometric_transformations::rotate_about_center;
use crate::common::Result;
use crate::LuminanceSource; use crate::LuminanceSource;
// const MINUS_45_IN_RADIANS: f32 = -0.7853981633974483; // Math.toRadians(-45.0) // const MINUS_45_IN_RADIANS: f32 = -0.7853981633974483; // Math.toRadians(-45.0)
@@ -164,7 +165,7 @@ impl LuminanceSource for BufferedImageLuminanceSource {
top: usize, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Box<dyn LuminanceSource>, crate::exceptions::Exceptions> { ) -> Result<Box<dyn LuminanceSource>> {
Ok(Box::new(Self { Ok(Box::new(Self {
image: self.image.clone(), image: self.image.clone(),
width, width,
@@ -178,9 +179,7 @@ impl LuminanceSource for BufferedImageLuminanceSource {
true true
} }
fn rotateCounterClockwise( fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>> {
&self,
) -> Result<Box<dyn LuminanceSource>, crate::exceptions::Exceptions> {
let img = self.image.rotate270(); let img = self.image.rotate270();
Ok(Box::new(Self { Ok(Box::new(Self {
width: img.width() as usize, width: img.width() as usize,
@@ -191,9 +190,7 @@ impl LuminanceSource for BufferedImageLuminanceSource {
})) }))
} }
fn rotateCounterClockwise45( fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>> {
&self,
) -> Result<Box<dyn LuminanceSource>, crate::exceptions::Exceptions> {
let img = rotate_about_center( let img = rotate_about_center(
&self.image.to_luma8(), &self.image.to_luma8(),
MINUS_45_IN_RADIANS, MINUS_45_IN_RADIANS,

View File

@@ -16,6 +16,7 @@
// package com.google.zxing.client.result; // package com.google.zxing.client.result;
use crate::common::Result;
use crate::exceptions::Exceptions; use crate::exceptions::Exceptions;
use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser}; use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser};
@@ -79,7 +80,7 @@ impl AddressBookParsedRXingResult {
email_types: Vec<String>, email_types: Vec<String>,
addresses: Vec<String>, addresses: Vec<String>,
address_types: Vec<String>, address_types: Vec<String>,
) -> Result<Self, Exceptions> { ) -> Result<Self> {
Self::with_details( Self::with_details(
names, names,
Vec::new(), Vec::new(),
@@ -118,7 +119,7 @@ impl AddressBookParsedRXingResult {
title: String, title: String,
urls: Vec<String>, urls: Vec<String>,
geo: Vec<String>, geo: Vec<String>,
) -> Result<Self, Exceptions> { ) -> Result<Self> {
if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"Phone numbers and types lengths differ".to_owned(), "Phone numbers and types lengths differ".to_owned(),

View File

@@ -32,6 +32,7 @@ use chrono_tz::Tz;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use crate::common::Result;
use crate::exceptions::Exceptions; use crate::exceptions::Exceptions;
use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType}; use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType};
@@ -109,7 +110,7 @@ impl CalendarParsedRXingResult {
description: String, description: String,
latitude: f64, latitude: f64,
longitude: f64, longitude: f64,
) -> Result<Self, Exceptions> { ) -> Result<Self> {
let start = Self::parseDate(startString.clone())?; let start = Self::parseDate(startString.clone())?;
let end = if endString.is_empty() { let end = if endString.is_empty() {
let durationMS = Self::parseDurationMS(&durationString)?; let durationMS = Self::parseDurationMS(&durationString)?;
@@ -164,7 +165,7 @@ impl CalendarParsedRXingResult {
* @param when The string to parse * @param when The string to parse
* @throws ParseException if not able to parse as a date * @throws ParseException if not able to parse as a date
*/ */
fn parseDate(when: String) -> Result<i64, Exceptions> { fn parseDate(when: String) -> Result<i64> {
if !DATE_TIME.is_match(&when) { if !DATE_TIME.is_match(&when) {
return Err(Exceptions::ParseException(Some(when))); return Err(Exceptions::ParseException(Some(when)));
} }
@@ -243,7 +244,7 @@ impl CalendarParsedRXingResult {
} }
} }
fn parseDurationMS(durationString: &str) -> Result<i64, Exceptions> { fn parseDurationMS(durationString: &str) -> Result<i64> {
if durationString.is_empty() { if durationString.is_empty() {
return Ok(-1); return Ok(-1);
} }
@@ -279,7 +280,7 @@ impl CalendarParsedRXingResult {
// return durationMS; // return durationMS;
} }
fn parseDateTimeString(dateTimeString: &str) -> Result<i64, Exceptions> { fn parseDateTimeString(dateTimeString: &str) -> Result<i64> {
if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") {
Ok(dtm.timestamp()) Ok(dtm.timestamp())
} else { } else {

View File

@@ -33,7 +33,7 @@ use urlencoding::decode;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{exceptions::Exceptions, RXingResult}; use crate::{common::Result, exceptions::Exceptions, RXingResult};
use super::{ use super::{
AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser, AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser,
@@ -296,7 +296,7 @@ pub fn appendKeyValue(keyValue: &str, result: &mut HashMap<String, String>) {
// } // }
} }
pub fn urlDecode(encoded: &str) -> Result<String, Exceptions> { pub fn urlDecode(encoded: &str) -> Result<String> {
if let Ok(decoded) = decode(encoded) { if let Ok(decoded) = decode(encoded) {
Ok(decoded.to_string()) Ok(decoded.to_string())
} else { } else {

View File

@@ -17,7 +17,8 @@
use regex::Regex; use regex::Regex;
use crate::{ use crate::{
client::result::VINParsedRXingResult, exceptions::Exceptions, BarcodeFormat, RXingResult, client::result::VINParsedRXingResult, common::Result, exceptions::Exceptions, BarcodeFormat,
RXingResult,
}; };
use super::ParsedClientResult; use super::ParsedClientResult;
@@ -67,7 +68,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
const IOQ: &str = "[IOQ]"; const IOQ: &str = "[IOQ]";
const AZ09: &str = "[A-Z0-9]{17}"; const AZ09: &str = "[A-Z0-9]{17}";
fn check_checksum(vin: &str) -> Result<bool, Exceptions> { fn check_checksum(vin: &str) -> Result<bool> {
let mut sum = 0; let mut sum = 0;
for i in 0..vin.len() { for i in 0..vin.len() {
sum += vin_position_weight(i + 1)? as u32 sum += vin_position_weight(i + 1)? as u32
@@ -85,7 +86,7 @@ fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
Ok(check_to_char == expected_check_char) Ok(check_to_char == expected_check_char)
} }
fn vin_char_value(c: char) -> Result<u32, Exceptions> { fn vin_char_value(c: char) -> Result<u32> {
match c { match c {
'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1), '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), 'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1),
@@ -97,7 +98,7 @@ fn vin_char_value(c: char) -> Result<u32, Exceptions> {
} }
} }
fn vin_position_weight(position: usize) -> Result<usize, Exceptions> { fn vin_position_weight(position: usize) -> Result<usize> {
match position { match position {
1..=7 => Ok(9 - position), 1..=7 => Ok(9 - position),
8 => Ok(10), 8 => Ok(10),
@@ -109,7 +110,7 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
} }
} }
fn check_char(remainder: u8) -> Result<char, Exceptions> { fn check_char(remainder: u8) -> Result<char> {
match remainder { match remainder {
0..=9 => Ok((b'0' + remainder) as char), 0..=9 => Ok((b'0' + remainder) as char),
10 => Ok('X'), 10 => Ok('X'),
@@ -119,7 +120,7 @@ fn check_char(remainder: u8) -> Result<char, Exceptions> {
} }
} }
fn model_year(c: char) -> Result<u32, Exceptions> { fn model_year(c: char) -> Result<u32> {
match c { match c {
'E'..='H' => Ok((c as u8 as u32 - b'E' as u32) + 1984), '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), 'J'..='N' => Ok((c as u8 as u32 - b'J' as u32) + 1988),

View File

@@ -20,6 +20,7 @@
use std::{cmp, fmt}; use std::{cmp, fmt};
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
static LOAD_FACTOR: f32 = 0.75f32; static LOAD_FACTOR: f32 = 0.75f32;
@@ -165,7 +166,7 @@ impl BitArray {
* @param start start of range, inclusive. * @param start start of range, inclusive.
* @param end end of range, exclusive * @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; let mut end = end;
if end < start || end > self.size { if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None)); 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 * @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 * @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<bool, Exceptions> { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool> {
let mut end = end; let mut end = end;
if end < start || end > self.size { if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None)); return Err(Exceptions::IllegalArgumentException(None));
@@ -251,7 +252,7 @@ impl BitArray {
* @param value {@code int} containing bits to append * @param value {@code int} containing bits to append
* @param numBits bits from value 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 { if num_bits > 32 {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"num bits must be between 0 and 32".to_owned(), "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 { if self.size != other.size {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"Sizes don't match".to_owned(), "Sizes don't match".to_owned(),

View File

@@ -20,6 +20,7 @@
use std::fmt; use std::fmt;
use crate::common::Result;
use crate::{Exceptions, RXingResultPoint}; use crate::{Exceptions, RXingResultPoint};
use super::BitArray; use super::BitArray;
@@ -53,7 +54,7 @@ impl BitMatrix {
* *
* @param dimension height and width * @param dimension height and width
*/ */
pub fn with_single_dimension(dimension: u32) -> Result<Self, Exceptions> { pub fn with_single_dimension(dimension: u32) -> Result<Self> {
Self::new(dimension, dimension) Self::new(dimension, dimension)
} }
@@ -63,7 +64,7 @@ impl BitMatrix {
* @param width bit matrix width * @param width bit matrix width
* @param height bit matrix height * @param height bit matrix height
*/ */
pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> { pub fn new(width: u32, height: u32) -> Result<Self> {
if width < 1 || height < 1 { if width < 1 || height < 1 {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"Both dimensions must be greater than 0".to_owned(), "Both dimensions must be greater than 0".to_owned(),
@@ -120,7 +121,7 @@ impl BitMatrix {
string_representation: &str, string_representation: &str,
set_string: &str, set_string: &str,
unset_string: &str, unset_string: &str,
) -> Result<Self, Exceptions> { ) -> Result<Self> {
// cannot pass nulls in rust // cannot pass nulls in rust
// if (stringRepresentation == null) { // if (stringRepresentation == null) {
// throw new IllegalArgumentException(); // throw new IllegalArgumentException();
@@ -308,7 +309,7 @@ impl BitMatrix {
* *
* @param mask XOR mask * @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 if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size
{ {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
@@ -350,13 +351,7 @@ impl BitMatrix {
* @param width The width of the region * @param width The width of the region
* @param height The height of the region * @param height The height of the region
*/ */
pub fn setRegion( pub fn setRegion(&mut self, left: u32, top: u32, width: u32, height: u32) -> Result<()> {
&mut self,
left: u32,
top: u32,
width: u32,
height: u32,
) -> Result<(), Exceptions> {
// if top < 0 || left < 0 { // if top < 0 || left < 0 {
// return Err(Exceptions::IllegalArgumentException( // return Err(Exceptions::IllegalArgumentException(
// "Left and top must be nonnegative".to_owned(), // "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) * @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 { match degrees % 360 {
0 => Ok(()), 0 => Ok(()),
90 => { 90 => {

View File

@@ -18,6 +18,7 @@
use std::cmp; use std::cmp;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
/** /**
@@ -68,7 +69,7 @@ impl BitSource {
* bits of the int * bits of the int
* @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
*/ */
pub fn readBits(&mut self, numBits: usize) -> Result<u32, Exceptions> { pub fn readBits(&mut self, numBits: usize) -> Result<u32> {
if !(1..=32).contains(&numBits) || numBits > self.available() { if !(1..=32).contains(&numBits) || numBits > self.available() {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
numBits.to_string(), numBits.to_string(),

View File

@@ -25,6 +25,7 @@
use encoding::EncodingRef; use encoding::EncodingRef;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
/** /**
@@ -215,7 +216,7 @@ impl CharacterSetECI {
* unsupported * unsupported
* @throws FormatException if ECI value is invalid * @throws FormatException if ECI value is invalid
*/ */
pub fn getCharacterSetECIByValue(value: u32) -> Result<CharacterSetECI, Exceptions> { pub fn getCharacterSetECIByValue(value: u32) -> Result<CharacterSetECI> {
match value { match value {
0 | 2 => Ok(CharacterSetECI::Cp437), 0 | 2 => Ok(CharacterSetECI::Cp437),
1 | 3 => Ok(CharacterSetECI::ISO8859_1), 1 | 3 => Ok(CharacterSetECI::ISO8859_1),

View File

@@ -18,6 +18,7 @@
// import com.google.zxing.NotFoundException; // import com.google.zxing.NotFoundException;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{BitMatrix, GridSampler, PerspectiveTransform}; use super::{BitMatrix, GridSampler, PerspectiveTransform};
@@ -50,7 +51,7 @@ impl GridSampler for DefaultGridSampler {
p3FromY: f32, p3FromY: f32,
p4FromX: f32, p4FromX: f32,
p4FromY: f32, p4FromY: f32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let transform = PerspectiveTransform::quadrilateralToQuadrilateral( let transform = PerspectiveTransform::quadrilateralToQuadrilateral(
p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX,
p2FromY, p3FromX, p3FromY, p4FromX, p4FromY, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY,
@@ -65,7 +66,7 @@ impl GridSampler for DefaultGridSampler {
dimensionX: u32, dimensionX: u32,
dimensionY: u32, dimensionY: u32,
transform: &PerspectiveTransform, transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
if dimensionX == 0 || dimensionY == 0 { if dimensionX == 0 || dimensionY == 0 {
return Err(Exceptions::NotFoundException(None)); return Err(Exceptions::NotFoundException(None));
} }

View File

@@ -17,7 +17,10 @@
//package com.google.zxing.common.detector; //package com.google.zxing.common.detector;
use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; use crate::{
common::{BitMatrix, Result},
Exceptions, RXingResultPoint, ResultPoint,
};
/** /**
* <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image. * <p>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 * third, the rightmost
* @throws NotFoundException if no Data Matrix Code can be found * @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 height = self.image.getHeight() as i32;
let width = self.image.getWidth() as i32; let width = self.image.getWidth() as i32;
let halfHeight = height / 2; let halfHeight = height / 2;
@@ -155,7 +158,7 @@ impl<'a> MonochromeRectangleDetector<'_> {
top: i32, top: i32,
bottom: i32, bottom: i32,
maxWhiteRun: i32, maxWhiteRun: i32,
) -> Result<RXingResultPoint, Exceptions> { ) -> Result<RXingResultPoint> {
let mut lastRange_z: Option<[i32; 2]> = None; let mut lastRange_z: Option<[i32; 2]> = None;
let mut y: i32 = centerY; let mut y: i32 = centerY;
let mut x: i32 = centerX; let mut x: i32 = centerX;

View File

@@ -16,7 +16,10 @@
//package com.google.zxing.common.detector; //package com.google.zxing.common.detector;
use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint}; use crate::{
common::{BitMatrix, Result},
Exceptions, RXingResultPoint, ResultPoint,
};
use super::MathUtils; use super::MathUtils;
@@ -43,7 +46,7 @@ pub struct WhiteRectangleDetector<'a> {
} }
impl<'a> WhiteRectangleDetector<'_> { impl<'a> WhiteRectangleDetector<'_> {
pub fn new_from_image(image: &'a BitMatrix) -> Result<WhiteRectangleDetector<'a>, Exceptions> { pub fn new_from_image(image: &'a BitMatrix) -> Result<WhiteRectangleDetector<'a>> {
WhiteRectangleDetector::new( WhiteRectangleDetector::new(
image, image,
INIT_SIZE, INIT_SIZE,
@@ -64,7 +67,7 @@ impl<'a> WhiteRectangleDetector<'_> {
initSize: i32, initSize: i32,
x: i32, x: i32,
y: i32, y: i32,
) -> Result<WhiteRectangleDetector<'a>, Exceptions> { ) -> Result<WhiteRectangleDetector<'a>> {
let halfsize = initSize / 2; let halfsize = initSize / 2;
let leftInit = x - halfsize; let leftInit = x - halfsize;
@@ -105,7 +108,7 @@ impl<'a> WhiteRectangleDetector<'_> {
* leftmost and the third, the rightmost * leftmost and the third, the rightmost
* @throws NotFoundException if no Data Matrix Code can be found * @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 left: i32 = self.leftInit;
let mut right: i32 = self.rightInit; let mut right: i32 = self.rightInit;
let mut up: i32 = self.upInit; let mut up: i32 = self.upInit;

View File

@@ -18,7 +18,7 @@
use std::fmt::Display; use std::fmt::Display;
use crate::Exceptions; use crate::common::Result;
/** /**
* Interface to navigate a sequence of ECIs and bytes. * Interface to navigate a sequence of ECIs and bytes.
@@ -50,7 +50,7 @@ pub trait ECIInput: Display {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if the value at the {@code index} argument is an ECI (@see #isECI) * if the value at the {@code index} argument is an ECI (@see #isECI)
*/ */
fn charAt(&self, index: usize) -> Result<char, Exceptions>; fn charAt(&self, index: usize) -> Result<char>;
/** /**
* Returns a {@code CharSequence} that is a subsequence of this sequence. * Returns a {@code CharSequence} that is a subsequence of this sequence.
@@ -72,7 +72,7 @@ pub trait ECIInput: Display {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if a value in the range {@code start}-{@code end} is an ECI (@see #isECI) * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI)
*/ */
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions>; fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>>;
/** /**
* Determines if a value is an ECI * 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 * if the {@code index} argument is negative or not less than
* {@code length()} * {@code length()}
*/ */
fn isECI(&self, index: u32) -> Result<bool, Exceptions>; fn isECI(&self, index: u32) -> Result<bool>;
/** /**
* Returns the {@code int} ECI value at the specified index. An index ranges from zero * 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 * @throws IllegalArgumentException
* if the value at the {@code index} argument is not an ECI (@see #isECI) * if the value at the {@code index} argument is not an ECI (@see #isECI)
*/ */
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions>; fn getECIValue(&self, index: usize) -> Result<i32>;
fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool, Exceptions>; fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool>;
} }

View File

@@ -25,7 +25,7 @@ use std::fmt;
use encoding::{Encoding, EncodingRef}; use encoding::{Encoding, EncodingRef};
use crate::Exceptions; use crate::common::Result;
use super::CharacterSetECI; use super::CharacterSetECI;
@@ -103,7 +103,7 @@ impl ECIStringBuilder {
* @param value ECI value to append, as an int * @param value ECI value to append, as an int
* @throws FormatException on invalid ECI value * @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(); self.encodeCurrentBytesIfAny();
if let Ok(character_set_eci) = CharacterSetECI::getCharacterSetECIByValue(value) { if let Ok(character_set_eci) = CharacterSetECI::getCharacterSetECIByValue(value) {

View File

@@ -24,6 +24,7 @@ use std::{borrow::Cow, rc::Rc};
use once_cell::unsync::OnceCell; use once_cell::unsync::OnceCell;
use crate::common::Result;
use crate::{Binarizer, Exceptions, LuminanceSource}; use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{BitArray, BitMatrix}; 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. // Applies simple sharpening to the row data to improve performance of the 1D Readers.
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions> { fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
let row = self.black_row_cache[y].get_or_try_init(|| { let row = self.black_row_cache[y].get_or_try_init(|| {
let source = self.getLuminanceSource(); let source = self.getLuminanceSource();
let width = source.getWidth(); 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. // 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 let matrix = self
.black_matrix .black_matrix
.get_or_try_init(|| Self::build_black_matrix(&self.source))?; .get_or_try_init(|| Self::build_black_matrix(&self.source))?;
@@ -138,7 +139,7 @@ impl GlobalHistogramBinarizer {
} }
} }
fn build_black_matrix(source: &Box<dyn LuminanceSource>) -> Result<BitMatrix, Exceptions> { fn build_black_matrix(source: &Box<dyn LuminanceSource>) -> Result<BitMatrix> {
// let source = source.getLuminanceSource(); // let source = source.getLuminanceSource();
let width = source.getWidth(); let width = source.getWidth();
let height = source.getHeight(); let height = source.getHeight();
@@ -192,7 +193,7 @@ impl GlobalHistogramBinarizer {
// // } // // }
// } // }
fn estimateBlackPoint(buckets: &[u32]) -> Result<u32, Exceptions> { fn estimateBlackPoint(buckets: &[u32]) -> Result<u32> {
// Find the tallest peak in the histogram. // Find the tallest peak in the histogram.
let numBuckets = buckets.len(); let numBuckets = buckets.len();
let mut maxBucketCount = 0; let mut maxBucketCount = 0;

View File

@@ -18,6 +18,7 @@
// import com.google.zxing.NotFoundException; // import com.google.zxing.NotFoundException;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{BitMatrix, PerspectiveTransform}; use super::{BitMatrix, PerspectiveTransform};
@@ -108,7 +109,7 @@ pub trait GridSampler {
p3FromY: f32, p3FromY: f32,
p4FromX: f32, p4FromX: f32,
p4FromY: f32, p4FromY: f32,
) -> Result<BitMatrix, Exceptions>; ) -> Result<BitMatrix>;
fn sample_grid( fn sample_grid(
&self, &self,
@@ -116,7 +117,7 @@ pub trait GridSampler {
dimensionX: u32, dimensionX: u32,
dimensionY: u32, dimensionY: u32,
transform: &PerspectiveTransform, transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions>; ) -> Result<BitMatrix>;
/** /**
* <p>Checks a set of points that have been transformed to sample points on an image against * <p>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 * @param points actual points in x1,y1,...,xn,yn form
* @throws NotFoundException if an endpoint is lies outside the image boundaries * @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 width = image.getWidth();
let height = image.getHeight(); let height = image.getHeight();
// Check and nudge points from start until we see some that are OK: // Check and nudge points from start until we see some that are OK:

View File

@@ -24,7 +24,8 @@ use std::{borrow::Cow, rc::Rc};
use once_cell::unsync::OnceCell; use once_cell::unsync::OnceCell;
use crate::{Binarizer, Exceptions, LuminanceSource}; use crate::common::Result;
use crate::{Binarizer, LuminanceSource};
use super::{BitArray, BitMatrix, GlobalHistogramBinarizer}; use super::{BitArray, BitMatrix, GlobalHistogramBinarizer};
@@ -57,7 +58,7 @@ impl Binarizer for HybridBinarizer {
self.ghb.getLuminanceSource() self.ghb.getLuminanceSource()
} }
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions> { fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
self.ghb.getBlackRow(y) 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 * 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. * 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 let matrix = self
.black_matrix .black_matrix
.get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?; .get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?;
@@ -102,7 +103,7 @@ impl HybridBinarizer {
} }
} }
fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result<BitMatrix, Exceptions> { fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result<BitMatrix> {
// let matrix; // let matrix;
let source = ghb.getLuminanceSource(); let source = ghb.getLuminanceSource();
let width = source.getWidth(); let width = source.getWidth();

View File

@@ -19,6 +19,7 @@ use std::{fmt, rc::Rc};
use encoding::EncodingRef; use encoding::EncodingRef;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{ECIEncoderSet, ECIInput}; use super::{ECIEncoderSet, ECIInput};
@@ -65,7 +66,7 @@ impl ECIInput for MinimalECIInput {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if the value at the {@code index} argument is an ECI (@see #isECI) * if the value at the {@code index} argument is an ECI (@see #isECI)
*/ */
fn charAt(&self, index: usize) -> Result<char, Exceptions> { fn charAt(&self, index: usize) -> Result<char> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(Some( return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(), index.to_string(),
@@ -103,7 +104,7 @@ impl ECIInput for MinimalECIInput {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if a value in the range {@code start}-{@code end} is an ECI (@see #isECI) * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI)
*/ */
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> { fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>> {
if start > end || end > self.length() { if start > end || end > self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None)); return Err(Exceptions::IndexOutOfBoundsException(None));
} }
@@ -131,7 +132,7 @@ impl ECIInput for MinimalECIInput {
* if the {@code index} argument is negative or not less than * if the {@code index} argument is negative or not less than
* {@code length()} * {@code length()}
*/ */
fn isECI(&self, index: u32) -> Result<bool, Exceptions> { fn isECI(&self, index: u32) -> Result<bool> {
if index >= self.length() as u32 { if index >= self.length() as u32 {
return Err(Exceptions::IndexOutOfBoundsException(None)); return Err(Exceptions::IndexOutOfBoundsException(None));
} }
@@ -156,7 +157,7 @@ impl ECIInput for MinimalECIInput {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if the value at the {@code index} argument is not an ECI (@see #isECI) * if the value at the {@code index} argument is not an ECI (@see #isECI)
*/ */
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> { fn getECIValue(&self, index: usize) -> Result<i32> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None)); return Err(Exceptions::IndexOutOfBoundsException(None));
} }
@@ -168,7 +169,7 @@ impl ECIInput for MinimalECIInput {
Ok((self.bytes[index] as u32 - 256) as i32) Ok((self.bytes[index] as u32 - 256) as i32)
} }
fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool, Exceptions> { fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool> {
if index + n > self.bytes.len() { if index + n > self.bytes.len() {
return Ok(false); return Ok(false);
} }
@@ -248,7 +249,7 @@ impl MinimalECIInput {
* if the {@code index} argument is negative or not less than * if the {@code index} argument is negative or not less than
* {@code length()} * {@code length()}
*/ */
pub fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> { pub fn isFNC1(&self, index: usize) -> Result<bool> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None)); return Err(Exceptions::IndexOutOfBoundsException(None));
} }

View File

@@ -24,6 +24,8 @@ pub use string_utils::*;
mod bit_array; mod bit_array;
pub use bit_array::*; pub use bit_array::*;
pub type Result<T, E = crate::Exceptions> = std::result::Result<T, E>;
/* /*
* Copyright 2007 ZXing authors * Copyright 2007 ZXing authors
* *

View File

@@ -3,6 +3,7 @@ use std::{borrow::Cow, rc::Rc};
use image::{DynamicImage, ImageBuffer, Luma}; use image::{DynamicImage, ImageBuffer, Luma};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use crate::common::Result;
use crate::{Binarizer, Exceptions, LuminanceSource}; use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{BitArray, BitMatrix}; use super::{BitArray, BitMatrix};
@@ -16,7 +17,7 @@ pub struct OtsuLevelBinarizer {
} }
impl OtsuLevelBinarizer { impl OtsuLevelBinarizer {
fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result<BitMatrix, Exceptions> { fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result<BitMatrix> {
let image_buffer = { let image_buffer = {
let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.getWidth() as u32, source.getHeight() as u32, source.getMatrix()) else { let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.getWidth() as u32, source.getHeight() as u32, source.getMatrix()) else {
return Err(Exceptions::IllegalArgumentException(None)) return Err(Exceptions::IllegalArgumentException(None))
@@ -49,10 +50,7 @@ impl Binarizer for OtsuLevelBinarizer {
&self.source &self.source
} }
fn getBlackRow( fn getBlackRow(&self, y: usize) -> Result<std::borrow::Cow<super::BitArray>> {
&self,
y: usize,
) -> Result<std::borrow::Cow<super::BitArray>, crate::Exceptions> {
let row = self.black_row_cache[y].get_or_try_init(|| { let row = self.black_row_cache[y].get_or_try_init(|| {
let matrix = self.getBlackMatrix()?; let matrix = self.getBlackMatrix()?;
Ok(matrix.getRow(y as u32)) Ok(matrix.getRow(y as u32))
@@ -61,7 +59,7 @@ impl Binarizer for OtsuLevelBinarizer {
Ok(Cow::Borrowed(row)) Ok(Cow::Borrowed(row))
} }
fn getBlackMatrix(&self) -> Result<&super::BitMatrix, crate::Exceptions> { fn getBlackMatrix(&self) -> Result<&super::BitMatrix> {
let matrix = self let matrix = self
.black_matrix .black_matrix
.get_or_try_init(|| Self::generate_threshold_matrix(self.source.as_ref()))?; .get_or_try_init(|| Self::generate_threshold_matrix(self.source.as_ref()))?;

View File

@@ -1,5 +1,6 @@
use std::fmt; use std::fmt;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{GenericGFPoly, GenericGFRef}; use super::{GenericGFPoly, GenericGFRef};
@@ -131,7 +132,7 @@ impl GenericGF {
/** /**
* @return base 2 log of a in GF(size) * @return base 2 log of a in GF(size)
*/ */
pub fn log(&self, a: i32) -> Result<i32, Exceptions> { pub fn log(&self, a: i32) -> Result<i32> {
if a == 0 { if a == 0 {
return Err(Exceptions::IllegalArgumentException(None)); return Err(Exceptions::IllegalArgumentException(None));
} }
@@ -142,7 +143,7 @@ impl GenericGF {
/** /**
* @return multiplicative inverse of a * @return multiplicative inverse of a
*/ */
pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> { pub fn inverse(&self, a: i32) -> Result<i32> {
if a == 0 { if a == 0 {
return Err(Exceptions::ArithmeticException(None)); return Err(Exceptions::ArithmeticException(None));
} }

View File

@@ -18,6 +18,7 @@
use std::fmt; use std::fmt;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{GenericGF, GenericGFRef}; use super::{GenericGF, GenericGFRef};
@@ -47,7 +48,7 @@ impl GenericGFPoly {
* or if leading coefficient is 0 and this is not a * or if leading coefficient is 0 and this is not a
* constant polynomial (that is, it is not the monomial "0") * constant polynomial (that is, it is not the monomial "0")
*/ */
pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result<Self, Exceptions> { pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result<Self> {
if coefficients.is_empty() { if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(String::from( return Err(Exceptions::IllegalArgumentException(Some(String::from(
"coefficients cannot be empty", "coefficients cannot be empty",
@@ -138,7 +139,7 @@ impl GenericGFPoly {
result result
} }
pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly> {
if self.field != other.field { if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"GenericGFPolys do not have same GenericGF field".to_owned(), "GenericGFPolys do not have same GenericGF field".to_owned(),
@@ -174,7 +175,7 @@ impl GenericGFPoly {
GenericGFPoly::new(self.field, &sumDiff) GenericGFPoly::new(self.field, &sumDiff)
} }
pub fn multiply(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> { pub fn multiply(&self, other: &GenericGFPoly) -> Result<GenericGFPoly> {
if self.field != other.field { if self.field != other.field {
//if (!field.equals(other.field)) { //if (!field.equals(other.field)) {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
@@ -229,11 +230,7 @@ impl GenericGFPoly {
GenericGFPoly::new(self.field, &[1]).unwrap() GenericGFPoly::new(self.field, &[1]).unwrap()
} }
pub fn multiply_by_monomial( pub fn multiply_by_monomial(&self, degree: usize, coefficient: i32) -> Result<GenericGFPoly> {
&self,
degree: usize,
coefficient: i32,
) -> Result<GenericGFPoly, Exceptions> {
if coefficient == 0 { if coefficient == 0 {
return Ok(self.getZero()); return Ok(self.getZero());
} }
@@ -247,10 +244,7 @@ impl GenericGFPoly {
GenericGFPoly::new(self.field, &product) GenericGFPoly::new(self.field, &product)
} }
pub fn divide( pub fn divide(&self, other: &GenericGFPoly) -> Result<(GenericGFPoly, GenericGFPoly)> {
&self,
other: &GenericGFPoly,
) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> {
if self.field != other.field { if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"GenericGFPolys do not have same GenericGF field".to_owned(), "GenericGFPolys do not have same GenericGF field".to_owned(),

View File

@@ -16,6 +16,7 @@
//package com.google.zxing.common.reedsolomon; //package com.google.zxing.common.reedsolomon;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{GenericGF, GenericGFPoly, GenericGFRef}; use super::{GenericGF, GenericGFPoly, GenericGFRef};
@@ -60,7 +61,7 @@ impl ReedSolomonDecoder {
* @param twoS number of error-correction codewords available * @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason * @throws ReedSolomonException if decoding fails for any reason
*/ */
pub fn decode(&self, received: &mut Vec<i32>, twoS: i32) -> Result<usize, Exceptions> { pub fn decode(&self, received: &mut Vec<i32>, twoS: i32) -> Result<usize> {
let poly = GenericGFPoly::new(self.field, received)?; let poly = GenericGFPoly::new(self.field, received)?;
let mut syndromeCoefficients = vec![0; twoS as usize]; let mut syndromeCoefficients = vec![0; twoS as usize];
let mut noError = true; let mut noError = true;
@@ -113,7 +114,7 @@ impl ReedSolomonDecoder {
a: &GenericGFPoly, a: &GenericGFPoly,
b: &GenericGFPoly, b: &GenericGFPoly,
R: usize, R: usize,
) -> Result<Vec<GenericGFPoly>, Exceptions> { ) -> Result<Vec<GenericGFPoly>> {
// Assume a's degree is >= b's // Assume a's degree is >= b's
let mut a = a.clone(); let mut a = a.clone();
let mut b = b.clone(); let mut b = b.clone();
@@ -184,7 +185,7 @@ impl ReedSolomonDecoder {
Ok(vec![sigma, omega]) Ok(vec![sigma, omega])
} }
fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result<Vec<usize>, Exceptions> { fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result<Vec<usize>> {
// This is a direct application of Chien's search // This is a direct application of Chien's search
let numErrors = errorLocator.getDegree(); let numErrors = errorLocator.getDegree();
if numErrors == 1 { if numErrors == 1 {
@@ -216,7 +217,7 @@ impl ReedSolomonDecoder {
&self, &self,
errorEvaluator: &GenericGFPoly, errorEvaluator: &GenericGFPoly,
errorLocations: &Vec<usize>, errorLocations: &Vec<usize>,
) -> Result<Vec<i32>, Exceptions> { ) -> Result<Vec<i32>> {
// This is directly applying Forney's Formula // This is directly applying Forney's Formula
let s = errorLocations.len(); let s = errorLocations.len();
let mut result = vec![0; s]; let mut result = vec![0; s];

View File

@@ -19,6 +19,7 @@
//import java.util.ArrayList; //import java.util.ArrayList;
//import java.util.List; //import java.util.List;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{GenericGFPoly, GenericGFRef}; use super::{GenericGFPoly, GenericGFRef};
@@ -35,7 +36,7 @@ pub struct ReedSolomonEncoder {
} }
impl ReedSolomonEncoder { impl ReedSolomonEncoder {
pub fn new(field: GenericGFRef) -> Result<Self, Exceptions> { pub fn new(field: GenericGFRef) -> Result<Self> {
let n = field; let n = field;
Ok(Self { Ok(Self {
cachedGenerators: vec![GenericGFPoly::new(n, &[1])?], cachedGenerators: vec![GenericGFPoly::new(n, &[1])?],
@@ -71,7 +72,7 @@ impl ReedSolomonEncoder {
Some(rv) Some(rv)
} }
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> { pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<()> {
if ec_bytes == 0 { if ec_bytes == 0 {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"No error correction bytes".to_owned(), "No error correction bytes".to_owned(),

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{BitMatrix, DecoderRXingResult, DetectorRXingResult}, common::{BitMatrix, DecoderRXingResult, DetectorRXingResult, Result},
BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult,
RXingResultMetadataType, RXingResultMetadataValue, Reader, RXingResultMetadataType, RXingResultMetadataValue, Reader,
}; };
@@ -52,10 +52,7 @@ impl Reader for DataMatrixReader {
* @throws FormatException if a Data Matrix code cannot be decoded * @throws FormatException if a Data Matrix code cannot be decoded
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, crate::Exceptions> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -71,7 +68,7 @@ impl Reader for DataMatrixReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
let try_harder = matches!( let try_harder = matches!(
hints.get(&DecodeHintType::TRY_HARDER), hints.get(&DecodeHintType::TRY_HARDER),
Some(DecodeHintValue::TryHarder(true)) Some(DecodeHintValue::TryHarder(true))
@@ -84,7 +81,7 @@ impl Reader for DataMatrixReader {
points.clear(); points.clear();
} else { } else {
//Result<DatamatrixDetectorResult, Exceptions> //Result<DatamatrixDetectorResult, Exceptions>
decoderRXingResult = if let Ok(fnd) = || -> Result<DecoderRXingResult, Exceptions> { decoderRXingResult = if let Ok(fnd) = || -> Result<DecoderRXingResult> {
let detectorRXingResult = let detectorRXingResult =
zxing_cpp_detector::detect(image.getBlackMatrix(), try_harder, true)?; zxing_cpp_detector::detect(image.getBlackMatrix(), try_harder, true)?;
let decoded = DECODER.decode(detectorRXingResult.getBits())?; let decoded = DECODER.decode(detectorRXingResult.getBits())?;
@@ -93,7 +90,7 @@ impl Reader for DataMatrixReader {
}() { }() {
fnd fnd
} else if try_harder { } else if try_harder {
if let Ok(fnd) = || -> Result<DecoderRXingResult, Exceptions> { if let Ok(fnd) = || -> Result<DecoderRXingResult> {
let detectorRXingResult = Detector::new(image.getBlackMatrix())?.detect()?; let detectorRXingResult = Detector::new(image.getBlackMatrix())?.detect()?;
let decoded = DECODER.decode(detectorRXingResult.getBits())?; let decoded = DECODER.decode(detectorRXingResult.getBits())?;
points = detectorRXingResult.getPoints().to_vec(); 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 * around it. This is a specialized method that works exceptionally fast in this special
* case. * case.
*/ */
fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix, Exceptions> { fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix> {
let Some(leftTopBlack) = image.getTopLeftOnBit() else { let Some(leftTopBlack) = image.getTopLeftOnBit() else {
return Err(Exceptions::NotFoundException(None)) return Err(Exceptions::NotFoundException(None))
}; };
@@ -226,7 +223,7 @@ impl DataMatrixReader {
Ok(bits) Ok(bits)
} }
fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result<u32, Exceptions> { fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result<u32> {
let width = image.getWidth(); let width = image.getWidth();
let mut x = leftTopBlack[0]; let mut x = leftTopBlack[0];
let y = leftTopBlack[1]; let y = leftTopBlack[1];

View File

@@ -20,8 +20,9 @@ use std::collections::HashMap;
use encoding::EncodingRef; use encoding::EncodingRef;
use crate::{ use crate::{
common::BitMatrix, qrcode::encoder::ByteMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, common::{BitMatrix, Result},
Exceptions, Writer, qrcode::encoder::ByteMatrix,
BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
}; };
use super::encoder::{ use super::encoder::{
@@ -47,7 +48,7 @@ impl Writer for DataMatrixWriter {
format: &crate::BarcodeFormat, format: &crate::BarcodeFormat,
width: i32, width: i32,
height: i32, height: i32,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
self.encode_with_hints(contents, format, width, height, &HashMap::new()) self.encode_with_hints(contents, format, width, height, &HashMap::new())
} }
@@ -58,7 +59,7 @@ impl Writer for DataMatrixWriter {
width: i32, width: i32,
height: i32, height: i32,
hints: &crate::EncodingHintDictionary, hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
if contents.is_empty() { if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"Found empty contents".to_owned(), "Found empty contents".to_owned(),
@@ -189,7 +190,7 @@ impl DataMatrixWriter {
symbolInfo: &SymbolInfo, symbolInfo: &SymbolInfo,
width: u32, width: u32,
height: u32, height: u32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let symbolWidth = symbolInfo.getSymbolDataWidth()?; let symbolWidth = symbolInfo.getSymbolDataWidth()?;
let symbolHeight = symbolInfo.getSymbolDataHeight()?; let symbolHeight = symbolInfo.getSymbolDataHeight()?;
@@ -255,7 +256,7 @@ impl DataMatrixWriter {
matrix: &ByteMatrix, matrix: &ByteMatrix,
reqWidth: u32, reqWidth: u32,
reqHeight: u32, reqHeight: u32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let matrixWidth = matrix.getWidth(); let matrixWidth = matrix.getWidth();
let matrixHeight = matrix.getHeight(); let matrixHeight = matrix.getHeight();
let outputWidth = reqWidth.max(matrixWidth); let outputWidth = reqWidth.max(matrixWidth);

View File

@@ -14,7 +14,10 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{common::BitMatrix, Exceptions}; use crate::{
common::{BitMatrix, Result},
Exceptions,
};
use super::{Version, VersionRef}; use super::{Version, VersionRef};
@@ -31,7 +34,7 @@ impl BitMatrixParser {
* @param bitMatrix {@link BitMatrix} to parse * @param bitMatrix {@link BitMatrix} to parse
* @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2 * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2
*/ */
pub fn new(bitMatrix: &BitMatrix) -> Result<Self, Exceptions> { pub fn new(bitMatrix: &BitMatrix) -> Result<Self> {
let dimension = bitMatrix.getHeight(); let dimension = bitMatrix.getHeight();
if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 { if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 {
return Err(Exceptions::FormatException(None)); return Err(Exceptions::FormatException(None));
@@ -64,7 +67,7 @@ impl BitMatrixParser {
* @throws FormatException if the dimensions of the mapping matrix are not valid * @throws FormatException if the dimensions of the mapping matrix are not valid
* Data Matrix dimensions. * Data Matrix dimensions.
*/ */
fn readVersion(bitMatrix: &BitMatrix) -> Result<VersionRef, Exceptions> { fn readVersion(bitMatrix: &BitMatrix) -> Result<VersionRef> {
let numRows = bitMatrix.getHeight(); let numRows = bitMatrix.getHeight();
let numColumns = bitMatrix.getWidth(); let numColumns = bitMatrix.getWidth();
Version::getVersionForDimensions(numRows, numColumns) Version::getVersionForDimensions(numRows, numColumns)
@@ -78,7 +81,7 @@ impl BitMatrixParser {
* @return bytes encoded within the Data Matrix Code * @return bytes encoded within the Data Matrix Code
* @throws FormatException if the exact number of bytes expected is not read * @throws FormatException if the exact number of bytes expected is not read
*/ */
pub fn readCodewords(&mut self) -> Result<Vec<u8>, Exceptions> { pub fn readCodewords(&mut self) -> Result<Vec<u8>> {
let mut result = vec![0u8; self.version.getTotalCodewords() as usize]; let mut result = vec![0u8; self.version.getTotalCodewords() as usize];
let mut resultOffset = 0; let mut resultOffset = 0;
@@ -447,10 +450,7 @@ impl BitMatrixParser {
* @param bitMatrix Original {@link BitMatrix} with alignment patterns * @param bitMatrix Original {@link BitMatrix} with alignment patterns
* @return BitMatrix that has the alignment patterns removed * @return BitMatrix that has the alignment patterns removed
*/ */
fn extractDataRegion( fn extractDataRegion(bitMatrix: &BitMatrix, version: VersionRef) -> Result<BitMatrix> {
bitMatrix: &BitMatrix,
version: VersionRef,
) -> Result<BitMatrix, Exceptions> {
// dbg!(bitMatrix.to_string()); // dbg!(bitMatrix.to_string());
let symbolSizeRows = version.getSymbolSizeRows(); let symbolSizeRows = version.getSymbolSizeRows();
let symbolSizeColumns = version.getSymbolSizeColumns(); let symbolSizeColumns = version.getSymbolSizeColumns();

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::Version; use super::Version;
@@ -52,7 +53,7 @@ impl DataBlock {
rawCodewords: &[u8], rawCodewords: &[u8],
version: &Version, version: &Version,
fix259: bool, fix259: bool,
) -> Result<Vec<DataBlock>, Exceptions> { ) -> Result<Vec<DataBlock>> {
// Figure out the number and size of data blocks used by this version // Figure out the number and size of data blocks used by this version
let ecBlocks = version.getECBlocks(); let ecBlocks = version.getECBlocks();

View File

@@ -14,12 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{ use crate::common::{
common::{ reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder},
reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder}, BitMatrix, DecoderRXingResult, Result,
BitMatrix, DecoderRXingResult,
},
Exceptions,
}; };
use super::{decoded_bit_stream_parser, BitMatrixParser, DataBlock}; 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 FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
pub fn decode(&self, bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(&self, bits: &BitMatrix) -> Result<DecoderRXingResult> {
let decoded = self.perform_decode(bits, false, false); let decoded = self.perform_decode(bits, false, false);
if decoded.is_ok() { if decoded.is_ok() {
return decoded; return decoded;
@@ -58,7 +55,7 @@ impl Decoder {
self.perform_decode(&Self::flip_bitmatrix(bits)?, false, true) self.perform_decode(&Self::flip_bitmatrix(bits)?, false, true)
} }
fn flip_bitmatrix(bits: &BitMatrix) -> Result<BitMatrix, Exceptions> { fn flip_bitmatrix(bits: &BitMatrix) -> Result<BitMatrix> {
let mut res = BitMatrix::new(bits.getHeight(), bits.getWidth())?; let mut res = BitMatrix::new(bits.getHeight(), bits.getWidth())?;
for y in 0..res.getHeight() { for y in 0..res.getHeight() {
for x in 0..res.getWidth() { for x in 0..res.getWidth() {
@@ -84,7 +81,7 @@ impl Decoder {
* @throws FormatException if the Data Matrix Code cannot be decoded * @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> { pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult> {
self.perform_decode(&BitMatrix::parse_bools(image), false, false) self.perform_decode(&BitMatrix::parse_bools(image), false, false)
} }
@@ -102,7 +99,7 @@ impl Decoder {
bits: &BitMatrix, bits: &BitMatrix,
fix259: bool, fix259: bool,
is_flipped: bool, is_flipped: bool,
) -> Result<DecoderRXingResult, Exceptions> { ) -> Result<DecoderRXingResult> {
// Construct a parser and read version, error-correction level // Construct a parser and read version, error-correction level
let mut parser = BitMatrixParser::new(bits)?; let mut parser = BitMatrixParser::new(bits)?;
@@ -153,11 +150,7 @@ impl Decoder {
* @param numDataCodewords number of codewords that are data bytes * @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
fn correctErrors( fn correctErrors(&self, codewordBytes: &mut [u8], numDataCodewords: u32) -> Result<()> {
&self,
codewordBytes: &mut [u8],
numDataCodewords: u32,
) -> Result<(), Exceptions> {
let _numCodewords = codewordBytes.len(); let _numCodewords = codewordBytes.len();
// First read into an array of ints // First read into an array of ints
// let codewordsInts = vec![0i32;numCodewords]; // let codewordsInts = vec![0i32;numCodewords];

View File

@@ -17,7 +17,7 @@
use encoding::Encoding; use encoding::Encoding;
use crate::{ use crate::{
common::{BitSource, DecoderRXingResult, ECIStringBuilder}, common::{BitSource, DecoderRXingResult, ECIStringBuilder, Result},
Exceptions, 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_236: &str = "[)>\u{001E}05\u{001D}";
const VALUE_237: &str = "[)>\u{001E}06\u{001D}"; const VALUE_237: &str = "[)>\u{001E}06\u{001D}";
pub fn decode(bytes: &[u8], is_flipped: bool) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(bytes: &[u8], is_flipped: bool) -> Result<DecoderRXingResult> {
let mut bits = BitSource::new(bytes.to_vec()); let mut bits = BitSource::new(bytes.to_vec());
let mut result = ECIStringBuilder::with_capacity(100); let mut result = ECIStringBuilder::with_capacity(100);
let mut resultTrailer = String::new(); let mut resultTrailer = String::new();
@@ -217,7 +217,7 @@ fn decodeAsciiSegment(
resultTrailer: &mut String, resultTrailer: &mut String,
fnc1positions: &mut Vec<usize>, fnc1positions: &mut Vec<usize>,
is_gs1: &mut bool, is_gs1: &mut bool,
) -> Result<Mode, Exceptions> { ) -> Result<Mode> {
let mut upperShift = false; let mut upperShift = false;
let mut firstFNC1Position = 1; let mut firstFNC1Position = 1;
let mut firstCodeword = true; let mut firstCodeword = true;
@@ -353,7 +353,7 @@ fn decodeC40Segment(
bits: &mut BitSource, bits: &mut BitSource,
result: &mut ECIStringBuilder, result: &mut ECIStringBuilder,
fnc1positions: &mut Vec<usize>, fnc1positions: &mut Vec<usize>,
) -> Result<(), Exceptions> { ) -> Result<()> {
// Three C40 values are encoded in a 16-bit value as // Three C40 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time // 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, bits: &mut BitSource,
result: &mut ECIStringBuilder, result: &mut ECIStringBuilder,
fnc1positions: &mut Vec<usize>, fnc1positions: &mut Vec<usize>,
) -> Result<(), Exceptions> { ) -> Result<()> {
// Three Text values are encoded in a 16-bit value as // Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time // 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 * See ISO 16022:2006, 5.2.7
*/ */
fn decodeAnsiX12Segment( fn decodeAnsiX12Segment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<()> {
bits: &mut BitSource,
result: &mut ECIStringBuilder,
) -> Result<(), Exceptions> {
// Three ANSI X12 values are encoded in a 16-bit value as // Three ANSI X12 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (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 * See ISO 16022:2006, 5.2.8 and Annex C Table C.3
*/ */
fn decodeEdifactSegment( fn decodeEdifactSegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<()> {
bits: &mut BitSource,
result: &mut ECIStringBuilder,
) -> Result<(), Exceptions> {
loop { loop {
// If there is only two or less bytes left then it will be encoded as ASCII // If there is only two or less bytes left then it will be encoded as ASCII
if bits.available() <= 16 { if bits.available() <= 16 {
@@ -727,7 +721,7 @@ fn decodeBase256Segment(
bits: &mut BitSource, bits: &mut BitSource,
result: &mut ECIStringBuilder, result: &mut ECIStringBuilder,
byteSegments: &mut Vec<Vec<u8>>, byteSegments: &mut Vec<Vec<u8>>,
) -> Result<(), Exceptions> { ) -> Result<()> {
// Figure out how long the Base 256 Segment is. // Figure out how long the Base 256 Segment is.
let mut codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed let mut codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed
let d1 = unrandomize255State(bits.readBits(8)?, codewordPosition); let d1 = unrandomize255State(bits.readBits(8)?, codewordPosition);
@@ -772,10 +766,7 @@ fn decodeBase256Segment(
/** /**
* See ISO 16022:2007, 5.4.1 * See ISO 16022:2007, 5.4.1
*/ */
fn decodeECISegment( fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<bool> {
bits: &mut BitSource,
result: &mut ECIStringBuilder,
) -> Result<bool, Exceptions> {
let firstByte = bits.readBits(8)?; let firstByte = bits.readBits(8)?;
if firstByte <= 127 { if firstByte <= 127 {
result.appendECI(firstByte - 1)?; result.appendECI(firstByte - 1)?;
@@ -797,10 +788,7 @@ fn decodeECISegment(
/** /**
* See ISO 16022:2006, 5.6 * See ISO 16022:2006, 5.6
*/ */
fn parse_structured_append( fn parse_structured_append(bits: &mut BitSource, sai: &mut StructuredAppendInfo) -> Result<()> {
bits: &mut BitSource,
sai: &mut StructuredAppendInfo,
) -> Result<(), Exceptions> {
// 5.6.2 Table 8 // 5.6.2 Table 8
let symbolSequenceIndicator = bits.readBits(8)?; let symbolSequenceIndicator = bits.readBits(8)?;
sai.index = (symbolSequenceIndicator >> 4) as i32; sai.index = (symbolSequenceIndicator >> 4) as i32;

View File

@@ -17,6 +17,7 @@
use core::fmt; use core::fmt;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
static VERSIONS: Lazy<Vec<Version>> = Lazy::new(Version::buildVersions); static VERSIONS: Lazy<Vec<Version>> = Lazy::new(Version::buildVersions);
@@ -100,10 +101,7 @@ impl Version {
* @return Version for a Data Matrix Code of those dimensions * @return Version for a Data Matrix Code of those dimensions
* @throws FormatException if dimensions do correspond to a valid Data Matrix size * @throws FormatException if dimensions do correspond to a valid Data Matrix size
*/ */
pub fn getVersionForDimensions( pub fn getVersionForDimensions(numRows: u32, numColumns: u32) -> Result<&'static Version> {
numRows: u32,
numColumns: u32,
) -> Result<&'static Version, Exceptions> {
if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 {
return Err(Exceptions::FormatException(None)); return Err(Exceptions::FormatException(None));
} }

View File

@@ -15,7 +15,9 @@
*/ */
use crate::{ use crate::{
common::{detector::WhiteRectangleDetector, BitMatrix, DefaultGridSampler, GridSampler}, common::{
detector::WhiteRectangleDetector, BitMatrix, DefaultGridSampler, GridSampler, Result,
},
Exceptions, RXingResultPoint, ResultPoint, Exceptions, RXingResultPoint, ResultPoint,
}; };
@@ -32,7 +34,7 @@ pub struct Detector<'a> {
rectangleDetector: WhiteRectangleDetector<'a>, rectangleDetector: WhiteRectangleDetector<'a>,
} }
impl<'a> Detector<'_> { impl<'a> Detector<'_> {
pub fn new(image: &'a BitMatrix) -> Result<Detector<'a>, Exceptions> { pub fn new(image: &'a BitMatrix) -> Result<Detector<'a>> {
Ok(Detector { Ok(Detector {
rectangleDetector: WhiteRectangleDetector::new_from_image(image)?, rectangleDetector: WhiteRectangleDetector::new_from_image(image)?,
image, image,
@@ -45,7 +47,7 @@ impl<'a> Detector<'_> {
* @return {@link DetectorRXingResult} encapsulating results of detecting a Data Matrix Code * @return {@link DetectorRXingResult} encapsulating results of detecting a Data Matrix Code
* @throws NotFoundException if no Data Matrix Code can be found * @throws NotFoundException if no Data Matrix Code can be found
*/ */
pub fn detect(&self) -> Result<DatamatrixDetectorResult, Exceptions> { pub fn detect(&self) -> Result<DatamatrixDetectorResult> {
let cornerPoints = self.rectangleDetector.detect()?; let cornerPoints = self.rectangleDetector.detect()?;
let mut points = self.detectSolid1(cornerPoints); let mut points = self.detectSolid1(cornerPoints);
@@ -331,7 +333,7 @@ impl<'a> Detector<'_> {
topRight: &RXingResultPoint, topRight: &RXingResultPoint,
dimensionX: u32, dimensionX: u32,
dimensionY: u32, dimensionY: u32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let sampler = DefaultGridSampler::default(); let sampler = DefaultGridSampler::default();
sampler.sample_grid_detailed( sampler.sample_grid_detailed(

View File

@@ -14,7 +14,7 @@ macro_rules! CHECK {
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use crate::{ use crate::{
common::{BitMatrix, DefaultGridSampler, GridSampler}, common::{BitMatrix, DefaultGridSampler, GridSampler, Result},
datamatrix::detector::{ datamatrix::detector::{
zxing_cpp_detector::{util::intersect, BitMatrixCursor, Quadrilateral, RegressionLine}, zxing_cpp_detector::{util::intersect, BitMatrixCursor, Quadrilateral, RegressionLine},
DatamatrixDetectorResult, DatamatrixDetectorResult,
@@ -37,7 +37,7 @@ use super::{DMRegressionLine, EdgeTracer};
fn Scan( fn Scan(
startTracer: &mut EdgeTracer, startTracer: &mut EdgeTracer,
lines: &mut [DMRegressionLine; 4], lines: &mut [DMRegressionLine; 4],
) -> Result<DatamatrixDetectorResult, Exceptions> { ) -> Result<DatamatrixDetectorResult> {
while startTracer.step(None) { while startTracer.step(None) {
//log(startTracer.p); //log(startTracer.p);
@@ -261,7 +261,7 @@ pub fn detect(
image: &BitMatrix, image: &BitMatrix,
tryHarder: bool, tryHarder: bool,
tryRotate: bool, tryRotate: bool,
) -> Result<DatamatrixDetectorResult, Exceptions> { ) -> Result<DatamatrixDetectorResult> {
// #ifdef PRINT_DEBUG // #ifdef PRINT_DEBUG
// LogMatrixWriter lmw(log, image, 1, "dm-log.pnm"); // LogMatrixWriter lmw(log, image, 1, "dm-log.pnm");
// // tryRotate = tryHarder = false; // // tryRotate = tryHarder = false;

View File

@@ -1,3 +1,4 @@
use crate::common::Result;
use crate::{Exceptions, RXingResultPoint}; use crate::{Exceptions, RXingResultPoint};
use super::{ use super::{
@@ -74,7 +75,7 @@ impl RegressionLine for DMRegressionLine {
self.c = f32::NAN; 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() { if self.direction_inward == RXingResultPoint::default() {
return Err(Exceptions::IllegalStateException(None)); return Err(Exceptions::IllegalStateException(None));
} }
@@ -235,11 +236,7 @@ impl DMRegressionLine {
self.points.reverse(); self.points.reverse();
} }
pub fn modules( pub fn modules(&mut self, beg: &RXingResultPoint, end: &RXingResultPoint) -> Result<f64> {
&mut self,
beg: &RXingResultPoint,
end: &RXingResultPoint,
) -> Result<f64, Exceptions> {
if self.points.len() <= 3 { if self.points.len() <= 3 {
return Err(Exceptions::IllegalStateException(None)); return Err(Exceptions::IllegalStateException(None));
} }

View File

@@ -1,6 +1,10 @@
use std::{cell::RefCell, rc::Rc}; 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}; use super::{BitMatrixCursor, Direction, RegressionLine, StepResult, Value};
@@ -170,7 +174,7 @@ impl<'a> EdgeTracer<'_> {
dEdge: &RXingResultPoint, dEdge: &RXingResultPoint,
maxStepSize: i32, maxStepSize: i32,
goodDirection: bool, goodDirection: bool,
) -> Result<StepResult, Exceptions> { ) -> Result<StepResult> {
let dEdge = RXingResultPoint::mainDirection(*dEdge); let dEdge = RXingResultPoint::mainDirection(*dEdge);
for breadth in 1..=(if maxStepSize == 1 { for breadth in 1..=(if maxStepSize == 1 {
2 2
@@ -262,7 +266,7 @@ impl<'a> EdgeTracer<'_> {
&mut self, &mut self,
dEdge: &RXingResultPoint, dEdge: &RXingResultPoint,
line: &mut T, line: &mut T,
) -> Result<bool, Exceptions> { ) -> Result<bool> {
line.setDirectionInward(dEdge); line.setDirectionInward(dEdge);
loop { loop {
// log(self.p); // log(self.p);
@@ -295,7 +299,7 @@ impl<'a> EdgeTracer<'_> {
line: &mut T, line: &mut T,
maxStepSize: i32, maxStepSize: i32,
finishLine: &mut T, finishLine: &mut T,
) -> Result<bool, Exceptions> { ) -> Result<bool> {
let mut maxStepSize = maxStepSize; let mut maxStepSize = maxStepSize;
line.setDirectionInward(dEdge); line.setDirectionInward(dEdge);
let mut gaps = 0; let mut gaps = 0;
@@ -437,7 +441,7 @@ impl<'a> EdgeTracer<'_> {
&mut self, &mut self,
dir: &mut RXingResultPoint, dir: &mut RXingResultPoint,
corner: &mut RXingResultPoint, corner: &mut RXingResultPoint,
) -> Result<bool, Exceptions> { ) -> Result<bool> {
self.step(None); self.step(None);
// log(p); // log(p);
*corner = self.p; *corner = self.p;

View File

@@ -1,4 +1,5 @@
use crate::{Exceptions, RXingResultPoint}; use crate::common::Result;
use crate::RXingResultPoint;
pub trait RegressionLine { pub trait RegressionLine {
// points: Vec<RXingResultPoint>, // points: Vec<RXingResultPoint>,
@@ -76,12 +77,12 @@ pub trait RegressionLine {
// a = b = c = NAN; // a = b = c = NAN;
// } // }
fn add(&mut self, p: &RXingResultPoint) -> Result<(), Exceptions>; //{ fn add(&mut self, p: &RXingResultPoint) -> Result<()>; //{
// assert(_directionInward != PointF()); // assert(_directionInward != PointF());
// _points.push_back(p); // _points.push_back(p);
// if (_points.size() == 1) // if (_points.size() == 1)
// c = dot(normal(), p); // c = dot(normal(), p);
// } // }
fn pop_back(&mut self); // { _points.pop_back(); } fn pop_back(&mut self); // { _points.pop_back(); }

View File

@@ -1,3 +1,4 @@
use crate::common::Result;
use crate::{Exceptions, RXingResultPoint}; use crate::{Exceptions, RXingResultPoint};
use super::{DMRegressionLine, Direction, RegressionLine}; use super::{DMRegressionLine, Direction, RegressionLine};
@@ -21,10 +22,7 @@ pub fn float_max<T: PartialOrd>(a: T, b: T) -> T {
} }
#[inline(always)] #[inline(always)]
pub fn intersect( pub fn intersect(l1: &DMRegressionLine, l2: &DMRegressionLine) -> Result<RXingResultPoint> {
l1: &DMRegressionLine,
l2: &DMRegressionLine,
) -> Result<RXingResultPoint, Exceptions> {
if !(l1.isValid() && l2.isValid()) { if !(l1.isValid() && l2.isValid()) {
return Err(Exceptions::IllegalStateException(None)); return Err(Exceptions::IllegalStateException(None));
} }

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{high_level_encoder, Encoder}; use super::{high_level_encoder, Encoder};
@@ -21,7 +22,7 @@ use super::{high_level_encoder, Encoder};
pub struct ASCIIEncoder; pub struct ASCIIEncoder;
impl Encoder for ASCIIEncoder { impl Encoder for ASCIIEncoder {
fn encode(&self, context: &mut super::EncoderContext) -> Result<(), Exceptions> { fn encode(&self, context: &mut super::EncoderContext) -> Result<()> {
//step B //step B
let n = let n =
high_level_encoder::determineConsecutiveDigitCount(context.getMessage(), context.pos); high_level_encoder::determineConsecutiveDigitCount(context.getMessage(), context.pos);
@@ -99,7 +100,7 @@ impl ASCIIEncoder {
pub fn new() -> Self { pub fn new() -> Self {
Self Self
} }
fn encodeASCIIDigits(digit1: char, digit2: char) -> Result<char, Exceptions> { fn encodeASCIIDigits(digit1: char, digit2: char) -> Result<char> {
if high_level_encoder::isDigit(digit1) && high_level_encoder::isDigit(digit2) { if high_level_encoder::isDigit(digit1) && high_level_encoder::isDigit(digit2) {
let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48);
Ok((num + 130) as char) Ok((num + 130) as char)

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{ use super::{
@@ -27,7 +28,7 @@ impl Encoder for Base256Encoder {
BASE256_ENCODATION 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(); let mut buffer = String::new();
buffer.push('\0'); //Initialize length field buffer.push('\0'); //Initialize length field
while context.hasMoreCharacters() { while context.hasMoreCharacters() {

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::high_level_encoder::{ use super::high_level_encoder::{
@@ -25,7 +26,7 @@ use super::{Encoder, EncoderContext};
pub struct C40Encoder; pub struct C40Encoder;
impl Encoder for 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( self.encode_with_encode_char_fn(
context, context,
&Self::encodeChar_c40, &Self::encodeChar_c40,
@@ -48,9 +49,9 @@ impl C40Encoder {
&self, &self,
context: &mut super::EncoderContext, context: &mut super::EncoderContext,
encodeChar: &dyn Fn(char, &mut String) -> u32, 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, getEncodingMode: &dyn Fn() -> usize,
) -> Result<(), Exceptions> { ) -> Result<()> {
//step C //step C
let mut buffer = String::new(); let mut buffer = String::new();
while context.hasMoreCharacters() { while context.hasMoreCharacters() {
@@ -110,7 +111,7 @@ impl C40Encoder {
handleEOD(context, &mut buffer) 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) self.encodeMaximal(context, &Self::encodeChar_c40, &Self::handleEOD_c40)
} }
@@ -118,8 +119,8 @@ impl C40Encoder {
&self, &self,
context: &mut EncoderContext, context: &mut EncoderContext,
encodeChar: &dyn Fn(char, &mut String) -> u32, encodeChar: &dyn Fn(char, &mut String) -> u32,
handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<(), Exceptions>, handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<()>,
) -> Result<(), Exceptions> { ) -> Result<()> {
let mut buffer = String::new(); let mut buffer = String::new();
let mut lastCharSize = 0; let mut lastCharSize = 0;
let mut backtrackStartPosition = context.pos; let mut backtrackStartPosition = context.pos;
@@ -181,7 +182,7 @@ impl C40Encoder {
pub(super) fn writeNextTriplet( pub(super) fn writeNextTriplet(
context: &mut EncoderContext, context: &mut EncoderContext,
buffer: &mut String, buffer: &mut String,
) -> Result<(), Exceptions> { ) -> Result<()> {
context.writeCodewords( context.writeCodewords(
&Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?, &Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?,
); );
@@ -196,10 +197,7 @@ impl C40Encoder {
* @param context the encoder context * @param context the encoder context
* @param buffer the buffer with the remaining encoded characters * @param buffer the buffer with the remaining encoded characters
*/ */
pub fn handleEOD_c40( pub fn handleEOD_c40(context: &mut EncoderContext, buffer: &mut String) -> Result<()> {
context: &mut EncoderContext,
buffer: &mut String,
) -> Result<(), Exceptions> {
let unwritten = (buffer.chars().count() / 3) * 2; let unwritten = (buffer.chars().count() / 3) * 2;
let rest = buffer.chars().count() % 3; let rest = buffer.chars().count() % 3;

View File

@@ -14,12 +14,12 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::Exceptions; use crate::common::Result;
use super::EncoderContext; use super::EncoderContext;
pub trait Encoder { pub trait Encoder {
fn getEncodingMode(&self) -> usize; fn getEncodingMode(&self) -> usize;
fn encode(&self, context: &mut EncoderContext) -> Result<(), Exceptions>; fn encode(&self, context: &mut EncoderContext) -> Result<()>;
} }

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
const EMPTY_BIT_VAL: u8 = 13; const EMPTY_BIT_VAL: u8 = 13;
@@ -73,7 +74,7 @@ impl DefaultPlacement {
self.bits[row * self.numcols + col] == EMPTY_BIT_VAL 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 pos = 0;
let mut row = 4_isize; let mut row = 4_isize;
let mut col = 0_isize; let mut col = 0_isize;
@@ -147,7 +148,7 @@ impl DefaultPlacement {
Ok(()) 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 row = row;
let mut col = col; let mut col = col;
@@ -178,7 +179,7 @@ impl DefaultPlacement {
* @param col the column * @param col the column
* @param pos character position * @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 - 2, pos, 1)?;
self.module(row - 2, col - 1, pos, 2)?; self.module(row - 2, col - 1, pos, 2)?;
self.module(row - 1, col - 2, pos, 3)?; self.module(row - 1, col - 2, pos, 3)?;
@@ -190,7 +191,7 @@ impl DefaultPlacement {
Ok(()) 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, 0, pos, 1)?;
self.module(self.numrows as isize - 1, 1, pos, 2)?; self.module(self.numrows as isize - 1, 1, pos, 2)?;
self.module(self.numrows as isize - 1, 2, pos, 3)?; self.module(self.numrows as isize - 1, 2, pos, 3)?;
@@ -202,7 +203,7 @@ impl DefaultPlacement {
Ok(()) 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 - 3, 0, pos, 1)?;
self.module(self.numrows as isize - 2, 0, pos, 2)?; self.module(self.numrows as isize - 2, 0, pos, 2)?;
self.module(self.numrows as isize - 1, 0, pos, 3)?; self.module(self.numrows as isize - 1, 0, pos, 3)?;
@@ -214,7 +215,7 @@ impl DefaultPlacement {
Ok(()) 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 - 3, 0, pos, 1)?;
self.module(self.numrows as isize - 2, 0, pos, 2)?; self.module(self.numrows as isize - 2, 0, pos, 2)?;
self.module(self.numrows as isize - 1, 0, pos, 3)?; self.module(self.numrows as isize - 1, 0, pos, 3)?;
@@ -226,7 +227,7 @@ impl DefaultPlacement {
Ok(()) 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, 0, pos, 1)?;
self.module(self.numrows as isize - 1, self.numcols as isize - 1, pos, 2)?; self.module(self.numrows as isize - 1, self.numcols as isize - 1, pos, 2)?;
self.module(0, self.numcols as isize - 3, pos, 3)?; self.module(0, self.numcols as isize - 3, pos, 3)?;

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{high_level_encoder, Encoder, EncoderContext}; use super::{high_level_encoder, Encoder, EncoderContext};
@@ -24,7 +25,7 @@ impl Encoder for EdifactEncoder {
high_level_encoder::EDIFACT_ENCODATION 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 //step F
let mut buffer = String::new(); let mut buffer = String::new();
while context.hasMoreCharacters() { while context.hasMoreCharacters() {
@@ -65,8 +66,8 @@ impl EdifactEncoder {
* @param context the encoder context * @param context the encoder context
* @param buffer the buffer with the remaining encoded characters * @param buffer the buffer with the remaining encoded characters
*/ */
fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<()> {
let mut runner = || -> Result<(), Exceptions> { let mut runner = || -> Result<()> {
let count = buffer.chars().count(); let count = buffer.chars().count();
if count == 0 { if count == 0 {
return Ok(()); //Already finished return Ok(()); //Already finished
@@ -135,7 +136,7 @@ impl EdifactEncoder {
res res
} }
fn encodeChar(c: char, sb: &mut String) -> Result<(), Exceptions> { fn encodeChar(c: char, sb: &mut String) -> Result<()> {
if (' '..='?').contains(&c) { if (' '..='?').contains(&c) {
sb.push(c); sb.push(c);
} else if ('@'..='^').contains(&c) { } else if ('@'..='^').contains(&c) {
@@ -146,7 +147,7 @@ impl EdifactEncoder {
Ok(()) Ok(())
} }
fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> { fn encodeToCodewords(sb: &str) -> Result<String> {
let len = sb.chars().count(); let len = sb.chars().count();
if len == 0 { if len == 0 {
return Err(Exceptions::IllegalStateException(Some( return Err(Exceptions::IllegalStateException(Some(

View File

@@ -16,6 +16,7 @@
use std::rc::Rc; use std::rc::Rc;
use crate::common::Result;
use crate::{Dimension, Exceptions}; use crate::{Dimension, Exceptions};
use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint}; use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint};
@@ -40,13 +41,13 @@ impl<'a> EncoderContext<'_> {
pub fn with_symbol_info_lookup( pub fn with_symbol_info_lookup(
msg: &str, msg: &str,
symbol_lookup: Rc<SymbolInfoLookup<'a>>, symbol_lookup: Rc<SymbolInfoLookup<'a>>,
) -> Result<EncoderContext<'a>, Exceptions> { ) -> Result<EncoderContext<'a>> {
let mut new_self = EncoderContext::new(msg)?; let mut new_self = EncoderContext::new(msg)?;
new_self.symbol_lookup = symbol_lookup.clone(); new_self.symbol_lookup = symbol_lookup.clone();
Ok(new_self) Ok(new_self)
} }
pub fn new(msg: &str) -> Result<Self, Exceptions> { pub fn new(msg: &str) -> Result<Self> {
//From this point on Strings are not Unicode anymore! //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 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()); // let sb = String::with_capacity(msgBinary.len());

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::SymbolInfo; use super::SymbolInfo;
@@ -152,7 +153,7 @@ const ALOG: [u32; 255] = {
* @param symbolInfo information about the symbol to be encoded * @param symbolInfo information about the symbol to be encoded
* @return the codewords with interleaved error correction. * @return the codewords with interleaved error correction.
*/ */
pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String, Exceptions> { pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String> {
if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"The number of codewords does not match the selected symbol".to_owned(), "The number of codewords does not match the selected symbol".to_owned(),
@@ -217,7 +218,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
Ok(sb) Ok(sb)
} }
fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptions> { fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String> {
let mut table = -1_isize; let mut table = -1_isize;
for (i, set) in FACTOR_SETS.iter().enumerate() { for (i, set) in FACTOR_SETS.iter().enumerate() {
// for i in 0..FACTOR_SETS.len() { // for i in 0..FACTOR_SETS.len() {

View File

@@ -18,6 +18,7 @@ use std::rc::Rc;
use encoding::{self, EncodingRef}; use encoding::{self, EncodingRef};
use crate::common::Result;
use crate::{Dimension, Exceptions}; use crate::{Dimension, Exceptions};
use super::{ use super::{
@@ -134,7 +135,7 @@ fn randomize253State(codewordPosition: u32) -> String {
* @param msg the message * @param msg the message
* @return the encoded message (the char values range from 0 to 255) * @return the encoded message (the char values range from 0 to 255)
*/ */
pub fn encodeHighLevel(msg: &str) -> Result<String, Exceptions> { pub fn encodeHighLevel(msg: &str) -> Result<String> {
encodeHighLevelWithDimensionForceC40(msg, SymbolShapeHint::FORCE_NONE, None, None, false) encodeHighLevelWithDimensionForceC40(msg, SymbolShapeHint::FORCE_NONE, None, None, false)
} }
@@ -148,7 +149,7 @@ pub fn encodeHighLevel(msg: &str) -> Result<String, Exceptions> {
pub fn encodeHighLevelSIL( pub fn encodeHighLevelSIL(
msg: &str, msg: &str,
symbol_lookup: Option<Rc<SymbolInfoLookup>>, symbol_lookup: Option<Rc<SymbolInfoLookup>>,
) -> Result<String, Exceptions> { ) -> Result<String> {
encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
msg, msg,
SymbolShapeHint::FORCE_NONE, SymbolShapeHint::FORCE_NONE,
@@ -175,7 +176,7 @@ pub fn encodeHighLevelWithDimension(
shape: SymbolShapeHint, shape: SymbolShapeHint,
minSize: Option<Dimension>, minSize: Option<Dimension>,
maxSize: Option<Dimension>, maxSize: Option<Dimension>,
) -> Result<String, Exceptions> { ) -> Result<String> {
encodeHighLevelWithDimensionForceC40(msg, shape, minSize, maxSize, false) encodeHighLevelWithDimensionForceC40(msg, shape, minSize, maxSize, false)
} }
@@ -186,7 +187,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
maxSize: Option<Dimension>, maxSize: Option<Dimension>,
forceC40: bool, forceC40: bool,
symbol_lookup: Option<Rc<SymbolInfoLookup>>, symbol_lookup: Option<Rc<SymbolInfoLookup>>,
) -> Result<String, Exceptions> { ) -> Result<String> {
//the codewords 0..255 are encoded as Unicode characters //the codewords 0..255 are encoded as Unicode characters
let c40Encoder = Rc::new(C40Encoder::new()); let c40Encoder = Rc::new(C40Encoder::new());
let encoders: [Rc<dyn Encoder>; 6] = [ let encoders: [Rc<dyn Encoder>; 6] = [
@@ -284,7 +285,7 @@ pub fn encodeHighLevelWithDimensionForceC40(
minSize: Option<Dimension>, minSize: Option<Dimension>,
maxSize: Option<Dimension>, maxSize: Option<Dimension>,
forceC40: bool, forceC40: bool,
) -> Result<String, Exceptions> { ) -> Result<String> {
encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup( encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
msg, shape, minSize, maxSize, forceC40, None, msg, shape, minSize, maxSize, forceC40, None,
) )
@@ -608,7 +609,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 {
idx - startpos idx - startpos
} }
pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { pub fn illegalCharacter(c: char) -> Result<()> {
// let hex = Integer.toHexString(c); // let hex = Integer.toHexString(c);
// hex = "0000".substring(0, 4 - hex.length()) + hex; // hex = "0000".substring(0, 4 - hex.length()) + hex;
Err(Exceptions::IllegalArgumentException(Some(format!( Err(Exceptions::IllegalArgumentException(Some(format!(

View File

@@ -19,7 +19,7 @@ use std::{fmt, rc::Rc};
use encoding::{self, EncodingRef}; use encoding::{self, EncodingRef};
use crate::{ use crate::{
common::{ECIInput, MinimalECIInput}, common::{ECIInput, MinimalECIInput, Result},
Exceptions, Exceptions,
}; };
@@ -134,7 +134,7 @@ fn isInTextShift2Set(ch: char, fnc1: Option<char>) -> bool {
* @param msg the message * @param msg the message
* @return the encoded message (the char values range from 0 to 255) * @return the encoded message (the char values range from 0 to 255)
*/ */
pub fn encodeHighLevel(msg: &str) -> Result<String, Exceptions> { pub fn encodeHighLevel(msg: &str) -> Result<String> {
encodeHighLevelWithDetails(msg, None, None, SymbolShapeHint::FORCE_NONE) encodeHighLevelWithDetails(msg, None, None, SymbolShapeHint::FORCE_NONE)
} }
@@ -156,7 +156,7 @@ pub fn encodeHighLevelWithDetails(
priorityCharset: Option<EncodingRef>, priorityCharset: Option<EncodingRef>,
fnc1: Option<char>, fnc1: Option<char>,
shape: SymbolShapeHint, shape: SymbolShapeHint,
) -> Result<String, Exceptions> { ) -> Result<String> {
let mut msg = msg; let mut msg = msg;
let mut macroId = 0; let mut macroId = 0;
if msg.starts_with(high_level_encoder::MACRO_05_HEADER) if msg.starts_with(high_level_encoder::MACRO_05_HEADER)
@@ -201,7 +201,7 @@ fn encode(
fnc1: Option<char>, fnc1: Option<char>,
shape: SymbolShapeHint, shape: SymbolShapeHint,
macroId: i32, macroId: i32,
) -> Result<Vec<u8>, Exceptions> { ) -> Result<Vec<u8>> {
Ok(encodeMinimally(Rc::new(Input::new( Ok(encodeMinimally(Rc::new(Input::new(
input, input,
priorityCharset, priorityCharset,
@@ -213,7 +213,7 @@ fn encode(
.to_vec()) .to_vec())
} }
fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<(), Exceptions> { fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<()> {
let vertexIndex = (edge.fromPosition + edge.characterLength) as usize; let vertexIndex = (edge.fromPosition + edge.characterLength) as usize;
if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none()
|| edges[vertexIndex][edge.getEndMode()?.ordinal()] || edges[vertexIndex][edge.getEndMode()?.ordinal()]
@@ -239,7 +239,7 @@ fn getNumberOfC40Words(
from: u32, from: u32,
c40: bool, c40: bool,
characterLength: &mut [u32], characterLength: &mut [u32],
) -> Result<u32, Exceptions> { ) -> Result<u32> {
let mut thirdsCount = 0; let mut thirdsCount = 0;
for i in (from as usize)..input.length() { for i in (from as usize)..input.length() {
// for (int i = from; i < input.length(); i++) { // for (int i = from; i < input.length(); i++) {
@@ -282,7 +282,7 @@ fn addEdges(
edges: &mut [Vec<Option<Rc<Edge>>>], edges: &mut [Vec<Option<Rc<Edge>>>],
from: u32, from: u32,
previous: Option<Rc<Edge>>, previous: Option<Rc<Edge>>,
) -> Result<(), Exceptions> { ) -> Result<()> {
if input.isECI(from)? { if input.isECI(from)? {
addEdge( addEdge(
edges, edges,
@@ -409,7 +409,7 @@ fn addEdges(
Ok(()) Ok(())
} }
fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> { fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult> {
// @SuppressWarnings("checkstyle:lineLength") // @SuppressWarnings("checkstyle:lineLength")
/* The minimal encoding is computed by Dijkstra. The acyclic graph is modeled as follows: /* 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 * 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, fromPosition: u32,
characterLength: u32, characterLength: u32,
previous: Option<Rc<Edge>>, previous: Option<Rc<Edge>>,
) -> Result<Self, Exceptions> { ) -> Result<Self> {
if fromPosition + characterLength > input.length() as u32 { if fromPosition + characterLength > input.length() as u32 {
return Err(Exceptions::FormatException(None)); return Err(Exceptions::FormatException(None));
} }
@@ -804,7 +804,7 @@ impl Edge {
// if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode} // if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode}
} }
pub fn getPreviousMode(previous: Option<Rc<Edge>>) -> Result<Mode, Exceptions> { pub fn getPreviousMode(previous: Option<Rc<Edge>>) -> Result<Mode> {
if let Some(prev) = previous { if let Some(prev) = previous {
prev.getEndMode() prev.getEndMode()
} else { } 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. * - 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. * Returns mode in all other cases.
* */ * */
pub fn getEndMode(&self) -> Result<Mode, Exceptions> { pub fn getEndMode(&self) -> Result<Mode> {
let mode = self.mode; let mode = self.mode;
if mode == Mode::Edf { if mode == Mode::Edf {
if self.characterLength < 4 { if self.characterLength < 4 {
@@ -856,7 +856,7 @@ impl Edge {
* two consecutive digits and a non extended character or of 4 digits. * two consecutive digits and a non extended character or of 4 digits.
* Returns 0 in any other case * Returns 0 in any other case
**/ **/
pub fn getLastASCII(&self) -> Result<u32, Exceptions> { pub fn getLastASCII(&self) -> Result<u32> {
let length = self.input.length() as u32; let length = self.input.length() as u32;
let from = self.fromPosition + self.characterLength; let from = self.fromPosition + self.characterLength;
if length - from > 4 || from >= length { if length - from > 4 || from >= length {
@@ -1000,7 +1000,7 @@ impl Edge {
} }
} }
pub fn getX12Words(&self) -> Result<Vec<u8>, Exceptions> { pub fn getX12Words(&self) -> Result<Vec<u8>> {
assert!(self.characterLength % 3 == 0); assert!(self.characterLength % 3 == 0);
let mut result = vec![0u8; self.characterLength as usize / 3 * 2]; let mut result = vec![0u8; self.characterLength as usize / 3 * 2];
let mut i = 0; let mut i = 0;
@@ -1096,7 +1096,7 @@ impl Edge {
} }
} }
pub fn getC40Words(&self, c40: bool, fnc1: Option<char>) -> Result<Vec<u8>, Exceptions> { pub fn getC40Words(&self, c40: bool, fnc1: Option<char>) -> Result<Vec<u8>> {
let mut c40Values: Vec<u8> = Vec::new(); let mut c40Values: Vec<u8> = Vec::new();
let fromPosition = self.fromPosition as usize; let fromPosition = self.fromPosition as usize;
for i in 0..self.characterLength as usize { for i in 0..self.characterLength as usize {
@@ -1156,7 +1156,7 @@ impl Edge {
Ok(result) Ok(result)
} }
pub fn getEDFBytes(&self) -> Result<Vec<u8>, Exceptions> { pub fn getEDFBytes(&self) -> Result<Vec<u8>> {
let numberOfThirds = (self.characterLength as f32 / 4.0).ceil() as usize; let numberOfThirds = (self.characterLength as f32 / 4.0).ceil() as usize;
let mut result = vec![0u8; numberOfThirds * 3]; let mut result = vec![0u8; numberOfThirds * 3];
let mut pos = self.fromPosition as usize; let mut pos = self.fromPosition as usize;
@@ -1190,7 +1190,7 @@ impl Edge {
Ok(result) Ok(result)
} }
pub fn getLatchBytes(&self) -> Result<Vec<u8>, Exceptions> { pub fn getLatchBytes(&self) -> Result<Vec<u8>> {
match Self::getPreviousMode(self.previous.clone())? { match Self::getPreviousMode(self.previous.clone())? {
Mode::Ascii | Mode::B256 => Mode::Ascii | Mode::B256 =>
//after B256 ends (via length) we are back to ASCII //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 // Important: The function does not return the length bytes (one or two) in case of B256 encoding
pub fn getDataBytes(&self) -> Result<Vec<u8>, Exceptions> { pub fn getDataBytes(&self) -> Result<Vec<u8>> {
match self.mode { match self.mode {
Mode::Ascii => { Mode::Ascii => {
if self.input.isECI(self.fromPosition)? { if self.input.isECI(self.fromPosition)? {
@@ -1272,7 +1272,7 @@ struct RXingResult {
bytes: Vec<u8>, bytes: Vec<u8>,
} }
impl RXingResult { impl RXingResult {
pub fn new(solution: Option<Rc<Edge>>) -> Result<Self, Exceptions> { pub fn new(solution: Option<Rc<Edge>>) -> Result<Self> {
let solution = if let Some(edge) = solution { let solution = if let Some(edge) = solution {
edge edge
} else { } else {
@@ -1427,10 +1427,10 @@ impl Input {
pub fn length(&self) -> usize { pub fn length(&self) -> usize {
self.internal.length() self.internal.length()
} }
pub fn isECI(&self, index: u32) -> Result<bool, Exceptions> { pub fn isECI(&self, index: u32) -> Result<bool> {
self.internal.isECI(index) self.internal.isECI(index)
} }
pub fn charAt(&self, index: usize) -> Result<char, Exceptions> { pub fn charAt(&self, index: usize) -> Result<char> {
self.internal.charAt(index) self.internal.charAt(index)
} }
pub fn getFNC1Character(&self) -> Option<char> { pub fn getFNC1Character(&self) -> Option<char> {
@@ -1440,13 +1440,13 @@ impl Input {
Some(self.internal.getFNC1Character() as u8 as char) Some(self.internal.getFNC1Character() as u8 as char)
} }
} }
fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool, Exceptions> { fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool> {
self.internal.haveNCharacters(index, n) self.internal.haveNCharacters(index, n)
} }
fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> { fn isFNC1(&self, index: usize) -> Result<bool> {
self.internal.isFNC1(index) self.internal.isFNC1(index)
} }
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> { fn getECIValue(&self, index: usize) -> Result<i32> {
self.internal.getECIValue(index) self.internal.getECIValue(index)
} }
} }

View File

@@ -16,6 +16,7 @@
use std::fmt; use std::fmt;
use crate::common::Result;
use crate::{Dimension, Exceptions}; use crate::{Dimension, Exceptions};
use super::SymbolShapeHint; use super::SymbolShapeHint;
@@ -122,7 +123,7 @@ impl SymbolInfo {
new_symbol new_symbol
} }
fn getHorizontalDataRegions(&self) -> Result<u32, Exceptions> { fn getHorizontalDataRegions(&self) -> Result<u32> {
match self.dataRegions { match self.dataRegions {
1 => Ok(1), 1 => Ok(1),
2 | 4 => Ok(2), 2 | 4 => Ok(2),
@@ -134,7 +135,7 @@ impl SymbolInfo {
} }
} }
fn getVerticalDataRegions(&self) -> Result<u32, Exceptions> { fn getVerticalDataRegions(&self) -> Result<u32> {
match self.dataRegions { match self.dataRegions {
1 | 2 => Ok(1), 1 | 2 => Ok(1),
4 => Ok(2), 4 => Ok(2),
@@ -146,19 +147,19 @@ impl SymbolInfo {
} }
} }
pub fn getSymbolDataWidth(&self) -> Result<u32, Exceptions> { pub fn getSymbolDataWidth(&self) -> Result<u32> {
Ok(self.getHorizontalDataRegions()? * self.matrixWidth) Ok(self.getHorizontalDataRegions()? * self.matrixWidth)
} }
pub fn getSymbolDataHeight(&self) -> Result<u32, Exceptions> { pub fn getSymbolDataHeight(&self) -> Result<u32> {
Ok(self.getVerticalDataRegions()? * self.matrixHeight) Ok(self.getVerticalDataRegions()? * self.matrixHeight)
} }
pub fn getSymbolWidth(&self) -> Result<u32, Exceptions> { pub fn getSymbolWidth(&self) -> Result<u32> {
Ok(self.getSymbolDataWidth()? + (self.getHorizontalDataRegions()? * 2)) Ok(self.getSymbolDataWidth()? + (self.getHorizontalDataRegions()? * 2))
} }
pub fn getSymbolHeight(&self) -> Result<u32, Exceptions> { pub fn getSymbolHeight(&self) -> Result<u32> {
Ok(self.getSymbolDataHeight()? + (self.getVerticalDataRegions()? * 2)) Ok(self.getSymbolDataHeight()? + (self.getVerticalDataRegions()? * 2))
} }
@@ -236,7 +237,7 @@ impl<'a> SymbolInfoLookup<'a> {
self.0 = Some(override_symbols); self.0 = Some(override_symbols);
} }
pub fn lookup(&self, dataCodewords: u32) -> Result<Option<&'a SymbolInfo>, Exceptions> { pub fn lookup(&self, dataCodewords: u32) -> Result<Option<&'a SymbolInfo>> {
self.lookup_with_codewords_shape_fail(dataCodewords, SymbolShapeHint::FORCE_NONE, true) self.lookup_with_codewords_shape_fail(dataCodewords, SymbolShapeHint::FORCE_NONE, true)
} }
@@ -244,7 +245,7 @@ impl<'a> SymbolInfoLookup<'a> {
&self, &self,
dataCodewords: u32, dataCodewords: u32,
shape: SymbolShapeHint, shape: SymbolShapeHint,
) -> Result<Option<&'a SymbolInfo>, Exceptions> { ) -> Result<Option<&'a SymbolInfo>> {
self.lookup_with_codewords_shape_fail(dataCodewords, shape, true) self.lookup_with_codewords_shape_fail(dataCodewords, shape, true)
} }
@@ -253,7 +254,7 @@ impl<'a> SymbolInfoLookup<'a> {
dataCodewords: u32, dataCodewords: u32,
allowRectangular: bool, allowRectangular: bool,
fail: bool, fail: bool,
) -> Result<Option<&'a SymbolInfo>, Exceptions> { ) -> Result<Option<&'a SymbolInfo>> {
let shape = if allowRectangular { let shape = if allowRectangular {
SymbolShapeHint::FORCE_NONE SymbolShapeHint::FORCE_NONE
} else { } else {
@@ -267,7 +268,7 @@ impl<'a> SymbolInfoLookup<'a> {
dataCodewords: u32, dataCodewords: u32,
shape: SymbolShapeHint, shape: SymbolShapeHint,
fail: bool, fail: bool,
) -> Result<Option<&'a SymbolInfo>, Exceptions> { ) -> Result<Option<&'a SymbolInfo>> {
self.lookup_with_codewords_shape_size_fail(dataCodewords, shape, &None, &None, fail) self.lookup_with_codewords_shape_size_fail(dataCodewords, shape, &None, &None, fail)
} }
@@ -279,7 +280,7 @@ impl<'a> SymbolInfoLookup<'a> {
maxSize: &Option<Dimension>, maxSize: &Option<Dimension>,
fail: bool, fail: bool,
// alternate_symbols_chart: Option<&'a Vec<SymbolInfo>>, // alternate_symbols_chart: Option<&'a Vec<SymbolInfo>>,
) -> Result<Option<&'a SymbolInfo>, Exceptions> { ) -> Result<Option<&'a SymbolInfo>> {
let symbol_search_chart: &Vec<SymbolInfo> = if self.0.is_none() { let symbol_search_chart: &Vec<SymbolInfo> = if self.0.is_none() {
&PROD_SYMBOLS &PROD_SYMBOLS
} else { } else {

View File

@@ -15,6 +15,7 @@
*/ */
use super::{high_level_encoder, C40Encoder, Encoder}; use super::{high_level_encoder, C40Encoder, Encoder};
use crate::common::Result;
pub struct TextEncoder(C40Encoder); pub struct TextEncoder(C40Encoder);
impl Encoder for TextEncoder { impl Encoder for TextEncoder {
@@ -22,7 +23,7 @@ impl Encoder for TextEncoder {
high_level_encoder::TEXT_ENCODATION 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( self.0.encode_with_encode_char_fn(
context, context,
&Self::encodeChar, &Self::encodeChar,

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{high_level_encoder, C40Encoder, Encoder, EncoderContext}; use super::{high_level_encoder, C40Encoder, Encoder, EncoderContext};
@@ -24,7 +25,7 @@ impl Encoder for X12Encoder {
high_level_encoder::X12_ENCODATION 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 //step C
let mut buffer = String::new(); let mut buffer = String::new();
while context.hasMoreCharacters() { while context.hasMoreCharacters() {
@@ -58,7 +59,7 @@ impl X12Encoder {
Self(C40Encoder::new()) Self(C40Encoder::new())
} }
fn encodeChar(c: char, sb: &mut String) -> Result<u32, Exceptions> { fn encodeChar(c: char, sb: &mut String) -> Result<u32> {
match c { match c {
'\r' => sb.push('\0'), '\r' => sb.push('\0'),
'*' => sb.push('\u{1}'), '*' => sb.push('\u{1}'),
@@ -77,7 +78,7 @@ impl X12Encoder {
Ok(1) Ok(1)
} }
fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> { fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<()> {
context.updateSymbolInfo(); context.updateSymbolInfo();
let available = context let available = context
.getSymbolInfo() .getSymbolInfo()

View File

@@ -6,7 +6,7 @@ use std::{
}; };
use crate::{ use crate::{
common::{BitMatrix, HybridBinarizer}, common::{BitMatrix, HybridBinarizer, Result},
multi::{GenericMultipleBarcodeReader, MultipleBarcodeReader}, multi::{GenericMultipleBarcodeReader, MultipleBarcodeReader},
BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, BarcodeFormat, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary,
Exceptions, Luma8LuminanceSource, MultiFormatReader, RXingResult, Reader, Exceptions, Luma8LuminanceSource, MultiFormatReader, RXingResult, Reader,
@@ -16,10 +16,7 @@ use crate::{
use crate::BufferedImageLuminanceSource; use crate::BufferedImageLuminanceSource;
#[cfg(feature = "svg_read")] #[cfg(feature = "svg_read")]
pub fn detect_in_svg( pub fn detect_in_svg(file_name: &str, barcode_type: Option<BarcodeFormat>) -> Result<RXingResult> {
file_name: &str,
barcode_type: Option<BarcodeFormat>,
) -> Result<RXingResult, Exceptions> {
detect_in_svg_with_hints(file_name, barcode_type, &mut HashMap::new()) 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, file_name: &str,
barcode_type: Option<BarcodeFormat>, barcode_type: Option<BarcodeFormat>,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
use std::{fs::File, io::Read}; use std::{fs::File, io::Read};
use crate::SVGLuminanceSource; use crate::SVGLuminanceSource;
@@ -73,7 +70,7 @@ pub fn detect_in_svg_with_hints(
} }
#[cfg(feature = "svg_read")] #[cfg(feature = "svg_read")]
pub fn detect_multiple_in_svg(file_name: &str) -> Result<Vec<RXingResult>, Exceptions> { pub fn detect_multiple_in_svg(file_name: &str) -> Result<Vec<RXingResult>> {
detect_multiple_in_svg_with_hints(file_name, &mut HashMap::new()) 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<Vec<RXingResult>, Excep
pub fn detect_multiple_in_svg_with_hints( pub fn detect_multiple_in_svg_with_hints(
file_name: &str, file_name: &str,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions> { ) -> Result<Vec<RXingResult>> {
use std::{fs::File, io::Read}; use std::{fs::File, io::Read};
use crate::SVGLuminanceSource; use crate::SVGLuminanceSource;
@@ -120,10 +117,7 @@ pub fn detect_multiple_in_svg_with_hints(
} }
#[cfg(feature = "image")] #[cfg(feature = "image")]
pub fn detect_in_file( pub fn detect_in_file(file_name: &str, barcode_type: Option<BarcodeFormat>) -> Result<RXingResult> {
file_name: &str,
barcode_type: Option<BarcodeFormat>,
) -> Result<RXingResult, Exceptions> {
detect_in_file_with_hints(file_name, barcode_type, &mut HashMap::new()) 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, file_name: &str,
barcode_type: Option<BarcodeFormat>, barcode_type: Option<BarcodeFormat>,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
let Ok(img) = image::open(file_name) else { let Ok(img) = image::open(file_name) else {
return Err(Exceptions::IllegalArgumentException(Some(format!("file '{file_name}' not found or cannot be opened")))); return Err(Exceptions::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")] #[cfg(feature = "image")]
pub fn detect_multiple_in_file(file_name: &str) -> Result<Vec<RXingResult>, Exceptions> { pub fn detect_multiple_in_file(file_name: &str) -> Result<Vec<RXingResult>> {
detect_multiple_in_file_with_hints(file_name, &mut HashMap::new()) 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<Vec<RXingResult>, Exce
pub fn detect_multiple_in_file_with_hints( pub fn detect_multiple_in_file_with_hints(
file_name: &str, file_name: &str,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions> { ) -> Result<Vec<RXingResult>> {
let img = image::open(file_name).map_err(|e| { let img = image::open(file_name).map_err(|e| {
Exceptions::RuntimeException(Some(format!("couldn't read {file_name}: {e}"))) Exceptions::RuntimeException(Some(format!("couldn't read {file_name}: {e}")))
})?; })?;
@@ -190,7 +184,7 @@ pub fn detect_in_luma(
width: u32, width: u32,
height: u32, height: u32,
barcode_type: Option<BarcodeFormat>, barcode_type: Option<BarcodeFormat>,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
detect_in_luma_with_hints(luma, height, width, barcode_type, &mut HashMap::new()) 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, height: u32,
barcode_type: Option<BarcodeFormat>, barcode_type: Option<BarcodeFormat>,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
let mut multi_format_reader = MultiFormatReader::default(); let mut multi_format_reader = MultiFormatReader::default();
if let Some(bc_type) = barcode_type { if let Some(bc_type) = barcode_type {
@@ -222,11 +216,7 @@ pub fn detect_in_luma_with_hints(
) )
} }
pub fn detect_multiple_in_luma( pub fn detect_multiple_in_luma(luma: Vec<u8>, width: u32, height: u32) -> Result<Vec<RXingResult>> {
luma: Vec<u8>,
width: u32,
height: u32,
) -> Result<Vec<RXingResult>, Exceptions> {
detect_multiple_in_luma_with_hints(luma, width, height, &mut HashMap::new()) 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, width: u32,
height: u32, height: u32,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions> { ) -> Result<Vec<RXingResult>> {
let multi_format_reader = MultiFormatReader::default(); let multi_format_reader = MultiFormatReader::default();
let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader);
@@ -252,7 +242,7 @@ pub fn detect_multiple_in_luma_with_hints(
} }
#[cfg(feature = "image")] #[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(); let image: image::DynamicImage = bit_matrix.into();
match image.save(file_name) { match image.save(file_name) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
@@ -263,7 +253,7 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Excepti
} }
#[cfg(feature = "svg_write")] #[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(); let svg: svg::Document = bit_matrix.into();
match svg::save(file_name, &svg) { 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); let path = PathBuf::from(file_name);
#[allow(unused_variables)] #[allow(unused_variables)]

View File

@@ -1,3 +1,4 @@
use crate::common::Result;
use crate::LuminanceSource; use crate::LuminanceSource;
/// A simple luma8 source for bytes, supports cropping but not rotation /// A simple luma8 source for bytes, supports cropping but not rotation
@@ -67,7 +68,7 @@ impl LuminanceSource for Luma8LuminanceSource {
top: usize, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Box<dyn LuminanceSource>, crate::Exceptions> { ) -> Result<Box<dyn LuminanceSource>> {
Ok(Box::new(Self { Ok(Box::new(Self {
dimensions: (width as u32, height as u32), dimensions: (width as u32, height as u32),
origin: (left as u32, top as u32), origin: (left as u32, top as u32),
@@ -81,7 +82,7 @@ impl LuminanceSource for Luma8LuminanceSource {
true true
} }
fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, crate::Exceptions> { fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>> {
let mut new_matrix = Self { let mut new_matrix = Self {
dimensions: self.dimensions, dimensions: self.dimensions,
origin: self.origin, origin: self.origin,
@@ -94,7 +95,7 @@ impl LuminanceSource for Luma8LuminanceSource {
Ok(Box::new(new_matrix)) Ok(Box::new(new_matrix))
} }
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, crate::Exceptions> { fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>> {
Err(crate::Exceptions::UnsupportedOperationException(Some( Err(crate::Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support rotation by 45 degrees.".to_owned(), "This luminance source does not support rotation by 45 degrees.".to_owned(),
))) )))

View File

@@ -16,6 +16,7 @@
//package com.google.zxing; //package com.google.zxing;
use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
/** /**
@@ -90,7 +91,7 @@ pub trait LuminanceSource {
_top: usize, _top: usize,
_width: usize, _width: usize,
_height: usize, _height: usize,
) -> Result<Box<dyn LuminanceSource>, Exceptions> { ) -> Result<Box<dyn LuminanceSource>> {
Err(Exceptions::UnsupportedOperationException(Some( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support cropping.".to_owned(), "This luminance source does not support cropping.".to_owned(),
))) )))
@@ -117,7 +118,7 @@ pub trait LuminanceSource {
* *
* @return A rotated version of this object. * @return A rotated version of this object.
*/ */
fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> { fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>> {
Err(Exceptions::UnsupportedOperationException(Some( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support rotation by 90 degrees.".to_owned(), "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. * @return A rotated version of this object.
*/ */
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> { fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>> {
Err(Exceptions::UnsupportedOperationException(Some( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support rotation by 45 degrees.".to_owned(), "This luminance source does not support rotation by 45 degrees.".to_owned(),
))) )))

View File

@@ -16,7 +16,10 @@
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::{common::DecoderRXingResult, Exceptions}; use crate::{
common::{DecoderRXingResult, Result},
Exceptions,
};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
/** /**
@@ -78,7 +81,7 @@ static SETS: Lazy<[String; 5]> = Lazy::new(|| {
] ]
}); });
pub fn decode(bytes: &[u8], mode: u8) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(bytes: &[u8], mode: u8) -> Result<DecoderRXingResult> {
let mut result = String::with_capacity(144); let mut result = String::with_capacity(144);
match mode { match mode {
2 | 3 => { 2 | 3 => {

View File

@@ -21,7 +21,7 @@ use once_cell::sync::Lazy;
use crate::{ use crate::{
common::{ common::{
reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder}, reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder},
BitMatrix, DecoderRXingResult, BitMatrix, DecoderRXingResult, Result,
}, },
DecodingHintDictionary, Exceptions, DecodingHintDictionary, Exceptions,
}; };
@@ -45,14 +45,14 @@ static RS_DECODER: Lazy<ReedSolomonDecoder> = Lazy::new(|| {
)) ))
}); });
pub fn decode(bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(bits: &BitMatrix) -> Result<DecoderRXingResult> {
decode_with_hints(bits, &HashMap::new()) decode_with_hints(bits, &HashMap::new())
} }
pub fn decode_with_hints( pub fn decode_with_hints(
bits: &BitMatrix, bits: &BitMatrix,
_hints: &DecodingHintDictionary, _hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> { ) -> Result<DecoderRXingResult> {
let parser = BitMatrixParser::new(bits); let parser = BitMatrixParser::new(bits);
let mut codewords = parser.readCodewords(); let mut codewords = parser.readCodewords();
@@ -88,7 +88,7 @@ fn correctErrors(
dataCodewords: u32, dataCodewords: u32,
ecCodewords: u32, ecCodewords: u32,
mode: u32, mode: u32,
) -> Result<(), Exceptions> { ) -> Result<()> {
let codewords = dataCodewords + ecCodewords; let codewords = dataCodewords + ecCodewords;
// in EVEN or ODD mode only half the codewords // in EVEN or ODD mode only half the codewords

View File

@@ -4,6 +4,7 @@ use num::integer::Roots;
use crate::{ use crate::{
common::{ common::{
detector::MathUtils, BitMatrix, DefaultGridSampler, DetectorRXingResult, GridSampler, detector::MathUtils, BitMatrix, DefaultGridSampler, DetectorRXingResult, GridSampler,
Result,
}, },
Exceptions, RXingResultPoint, Exceptions, RXingResultPoint,
}; };
@@ -315,7 +316,7 @@ impl Circle<'_> {
} }
} }
pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionResult, Exceptions> { pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionResult> {
// find concentric circles // find concentric circles
let Some( mut circles) = find_concentric_circles(image) else { let Some( mut circles) = find_concentric_circles(image) else {
return Err(Exceptions::NotFoundException(None)); 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 RIGHT_SHIFT_PERCENT_ADJUST: f32 = 0.03;
const ACCEPTED_SCALES: [f64; 5] = [0.065, 0.069, 0.07, 0.075, 0.08]; const ACCEPTED_SCALES: [f64; 5] = [0.065, 0.069, 0.07, 0.075, 0.08];
fn box_symbol( fn box_symbol(image: &BitMatrix, circle: &mut Circle) -> Result<([(f32, f32); 4], f32)> {
image: &BitMatrix,
circle: &mut Circle,
) -> Result<([(f32, f32); 4], f32), Exceptions> {
let (left_boundary, right_boundary, top_boundary, bottom_boundary) = let (left_boundary, right_boundary, top_boundary, bottom_boundary) =
calculate_simple_boundary(circle, Some(image), None, false); 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 /// Read appropriate bits from a bitmatrix for the maxicode decoder
pub fn read_bits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> { pub fn read_bits(image: &BitMatrix) -> Result<BitMatrix> {
let enclosingRectangle = image let enclosingRectangle = image
.getEnclosingRectangle() .getEnclosingRectangle()
.ok_or(Exceptions::NotFoundException(None))?; .ok_or(Exceptions::NotFoundException(None))?;

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{BitMatrix, DetectorRXingResult}, common::{BitMatrix, DetectorRXingResult, Result},
BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult, BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult,
RXingResultMetadataType, Reader, RXingResultMetadataType, Reader,
}; };
@@ -41,10 +41,7 @@ impl Reader for MaxiCodeReader {
* @throws FormatException if a MaxiCode cannot be decoded * @throws FormatException if a MaxiCode cannot be decoded
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, crate::Exceptions> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -60,7 +57,7 @@ impl Reader for MaxiCodeReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
// Note that MaxiCode reader effectively always assumes PURE_BARCODE mode // Note that MaxiCode reader effectively always assumes PURE_BARCODE mode
// and can't detect it in an image // and can't detect it in an image
let try_harder = matches!( let try_harder = matches!(
@@ -123,7 +120,7 @@ impl MaxiCodeReader {
* around it. This is a specialized method that works exceptionally fast in this special * around it. This is a specialized method that works exceptionally fast in this special
* case. * case.
*/ */
fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> { fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix> {
let enclosingRectangleOption = image.getEnclosingRectangle(); let enclosingRectangleOption = image.getEnclosingRectangle();
if enclosingRectangleOption.is_none() { if enclosingRectangleOption.is_none() {
return Err(Exceptions::NotFoundException(None)); return Err(Exceptions::NotFoundException(None));

View File

@@ -16,6 +16,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::common::Result;
use crate::{Exceptions, RXingResult, RXingResultPoint, Reader, ResultPoint}; use crate::{Exceptions, RXingResult, RXingResultPoint, Reader, ResultPoint};
/** /**
@@ -29,10 +30,7 @@ use crate::{Exceptions, RXingResult, RXingResultPoint, Reader, ResultPoint};
*/ */
pub struct ByQuadrantReader<T: Reader>(T); pub struct ByQuadrantReader<T: Reader>(T);
impl<T: Reader> Reader for ByQuadrantReader<T> { impl<T: Reader> Reader for ByQuadrantReader<T> {
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, crate::Exceptions> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -40,7 +38,7 @@ impl<T: Reader> Reader for ByQuadrantReader<T> {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
let width = image.getWidth(); let width = image.getWidth();
let height = image.getHeight(); let height = image.getHeight();
let halfWidth = width / 2; let halfWidth = width / 2;

View File

@@ -17,8 +17,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult, RXingResultPoint, Reader, common::Result, BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult,
ResultPoint, RXingResultPoint, Reader, ResultPoint,
}; };
use super::MultipleBarcodeReader; use super::MultipleBarcodeReader;
@@ -44,7 +44,7 @@ impl<T: Reader> MultipleBarcodeReader for GenericMultipleBarcodeReader<T> {
fn decode_multiple( fn decode_multiple(
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
) -> Result<Vec<crate::RXingResult>, crate::Exceptions> { ) -> Result<Vec<crate::RXingResult>> {
self.decode_multiple_with_hints(image, &HashMap::new()) self.decode_multiple_with_hints(image, &HashMap::new())
} }
@@ -52,7 +52,7 @@ impl<T: Reader> MultipleBarcodeReader for GenericMultipleBarcodeReader<T> {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<Vec<crate::RXingResult>, crate::Exceptions> { ) -> Result<Vec<crate::RXingResult>> {
let mut results = Vec::new(); let mut results = Vec::new();
self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0);
if results.is_empty() { if results.is_empty() {

View File

@@ -14,7 +14,7 @@
* limitations under the License. * 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. * 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 * @author Sean Owen
*/ */
pub trait MultipleBarcodeReader { pub trait MultipleBarcodeReader {
fn decode_multiple(&mut self, image: &mut BinaryBitmap) fn decode_multiple(&mut self, image: &mut BinaryBitmap) -> Result<Vec<RXingResult>>;
-> Result<Vec<RXingResult>, Exceptions>;
fn decode_multiple_with_hints( fn decode_multiple_with_hints(
&mut self, &mut self,
image: &mut BinaryBitmap, image: &mut BinaryBitmap,
hints: &DecodingHintDictionary, hints: &DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions>; ) -> Result<Vec<RXingResult>>;
} }

View File

@@ -15,7 +15,7 @@
*/ */
use crate::{ use crate::{
common::BitMatrix, common::{BitMatrix, Result},
qrcode::detector::{Detector, QRCodeDetectorResult}, qrcode::detector::{Detector, QRCodeDetectorResult},
DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
}; };
@@ -37,10 +37,7 @@ impl<'a> MultiDetector<'_> {
// private static final DetectorRXingResult[] EMPTY_DETECTOR_RESULTS = new DetectorRXingResult[0]; // private static final DetectorRXingResult[] EMPTY_DETECTOR_RESULTS = new DetectorRXingResult[0];
pub fn detectMulti( pub fn detectMulti(&self, hints: &DecodingHintDictionary) -> Result<Vec<QRCodeDetectorResult>> {
&self,
hints: &DecodingHintDictionary,
) -> Result<Vec<QRCodeDetectorResult>, Exceptions> {
let image = self.0.getImage(); let image = self.0.getImage();
let resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) = let resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) =
hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK) hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK)

View File

@@ -17,7 +17,7 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use crate::{ use crate::{
common::BitMatrix, common::{BitMatrix, Result},
qrcode::detector::{FinderPattern, FinderPatternFinder, FinderPatternInfo}, qrcode::detector::{FinderPattern, FinderPatternFinder, FinderPatternInfo},
result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions, result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions,
RXingResultPointCallback, RXingResultPointCallback,
@@ -82,7 +82,7 @@ impl<'a> MultiFinderPatternFinder<'_> {
* size differs from the average among those patterns the least * size differs from the average among those patterns the least
* @throws NotFoundException if 3 such finder patterns do not exist * @throws NotFoundException if 3 such finder patterns do not exist
*/ */
fn selectMultipleBestPatterns(&self) -> Result<Vec<[FinderPattern; 3]>, Exceptions> { fn selectMultipleBestPatterns(&self) -> Result<Vec<[FinderPattern; 3]>> {
let mut possibleCenters = Vec::new(); let mut possibleCenters = Vec::new();
for fp in self.0.getPossibleCenters() { for fp in self.0.getPossibleCenters() {
if fp.getCount() >= 2 { if fp.getCount() >= 2 {
@@ -216,10 +216,7 @@ impl<'a> MultiFinderPatternFinder<'_> {
} }
} }
pub fn findMulti( pub fn findMulti(&mut self, hints: &DecodingHintDictionary) -> Result<Vec<FinderPatternInfo>> {
&mut self,
hints: &DecodingHintDictionary,
) -> Result<Vec<FinderPatternInfo>, Exceptions> {
let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER); let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER);
let image = self.0.getImage().clone(); let image = self.0.getImage().clone();
let maxI = image.getHeight(); let maxI = image.getHeight();

View File

@@ -17,7 +17,7 @@
use std::{cmp::Ordering, collections::HashMap}; use std::{cmp::Ordering, collections::HashMap};
use crate::{ use crate::{
common::DetectorRXingResult, common::{DetectorRXingResult, Result},
multi::MultipleBarcodeReader, multi::MultipleBarcodeReader,
qrcode::{ qrcode::{
decoder::{self, QRCodeDecoderMetaData}, decoder::{self, QRCodeDecoderMetaData},
@@ -40,7 +40,7 @@ impl MultipleBarcodeReader for QRCodeMultiReader {
fn decode_multiple( fn decode_multiple(
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
) -> Result<Vec<crate::RXingResult>, crate::Exceptions> { ) -> Result<Vec<crate::RXingResult>> {
self.decode_multiple_with_hints(image, &HashMap::new()) self.decode_multiple_with_hints(image, &HashMap::new())
} }
@@ -48,11 +48,11 @@ impl MultipleBarcodeReader for QRCodeMultiReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<Vec<crate::RXingResult>, crate::Exceptions> { ) -> Result<Vec<crate::RXingResult>> {
let mut results = Vec::new(); let mut results = Vec::new();
let detectorRXingResults = MultiDetector::new(image.getBlackMatrix()).detectMulti(hints)?; let detectorRXingResults = MultiDetector::new(image.getBlackMatrix()).detectMulti(hints)?;
for detectorRXingResult in detectorRXingResults { for detectorRXingResult in detectorRXingResults {
let mut proc = || -> Result<(), Exceptions> { let mut proc = || -> Result<()> {
let decoderRXingResult = decoder::qrcode_decoder::decode_bitmatrix_with_hints( let decoderRXingResult = decoder::qrcode_decoder::decode_bitmatrix_with_hints(
detectorRXingResult.getBits(), detectorRXingResult.getBits(),
hints, hints,
@@ -126,7 +126,7 @@ impl QRCodeMultiReader {
Self(QRCodeReader::new()) Self(QRCodeReader::new())
} }
fn processStructuredAppend(results: Vec<RXingResult>) -> Result<Vec<RXingResult>, Exceptions> { fn processStructuredAppend(results: Vec<RXingResult>) -> Result<Vec<RXingResult>> {
let mut newRXingResults = Vec::new(); let mut newRXingResults = Vec::new();
let mut saRXingResults = Vec::new(); let mut saRXingResults = Vec::new();
for result in &results { for result in &results {

View File

@@ -16,6 +16,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::common::Result;
use crate::{ use crate::{
aztec::AztecReader, datamatrix::DataMatrixReader, maxicode::MaxiCodeReader, aztec::AztecReader, datamatrix::DataMatrixReader, maxicode::MaxiCodeReader,
oned::MultiFormatOneDReader, pdf417::PDF417Reader, qrcode::QRCodeReader, BarcodeFormat, oned::MultiFormatOneDReader, pdf417::PDF417Reader, qrcode::QRCodeReader, BarcodeFormat,
@@ -47,10 +48,7 @@ impl Reader for MultiFormatReader {
* @return The contents of the image * @return The contents of the image
* @throws NotFoundException Any errors which occurred * @throws NotFoundException Any errors which occurred
*/ */
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, crate::Exceptions> {
self.set_ints(&HashMap::new()); self.set_ints(&HashMap::new());
self.decode_internal(image) self.decode_internal(image)
} }
@@ -67,7 +65,7 @@ impl Reader for MultiFormatReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
self.set_ints(hints); self.set_ints(hints);
self.decode_internal(image) self.decode_internal(image)
} }
@@ -88,10 +86,7 @@ impl MultiFormatReader {
* @return The contents of the image * @return The contents of the image
* @throws NotFoundException Any errors which occurred * @throws NotFoundException Any errors which occurred
*/ */
pub fn decode_with_state( pub fn decode_with_state(&mut self, image: &mut BinaryBitmap) -> Result<RXingResult> {
&mut self,
image: &mut BinaryBitmap,
) -> Result<RXingResult, Exceptions> {
// Make sure to set up the default state so we don't crash // Make sure to set up the default state so we don't crash
if self.readers.is_empty() { if self.readers.is_empty() {
self.set_ints(&HashMap::new()); self.set_ints(&HashMap::new());
@@ -170,7 +165,7 @@ impl MultiFormatReader {
self.readers = readers; self.readers = readers;
} }
pub fn decode_internal(&mut self, image: &mut BinaryBitmap) -> Result<RXingResult, Exceptions> { pub fn decode_internal(&mut self, image: &mut BinaryBitmap) -> Result<RXingResult> {
if !self.readers.is_empty() { if !self.readers.is_empty() {
for reader in self.readers.iter_mut() { for reader in self.readers.iter_mut() {
let res = reader.decode_with_hints(image, &self.hints); let res = reader.decode_with_hints(image, &self.hints);

View File

@@ -18,6 +18,7 @@ use std::collections::HashMap;
use crate::{ use crate::{
aztec::AztecWriter, aztec::AztecWriter,
common::Result,
datamatrix::DataMatrixWriter, datamatrix::DataMatrixWriter,
oned::{ oned::{
CodaBarWriter, Code128Writer, Code39Writer, Code93Writer, EAN13Writer, EAN8Writer, CodaBarWriter, Code128Writer, Code39Writer, Code93Writer, EAN13Writer, EAN8Writer,
@@ -44,7 +45,7 @@ impl Writer for MultiFormatWriter {
format: &crate::BarcodeFormat, format: &crate::BarcodeFormat,
width: i32, width: i32,
height: i32, height: i32,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
self.encode_with_hints(contents, format, width, height, &HashMap::new()) self.encode_with_hints(contents, format, width, height, &HashMap::new())
} }
@@ -55,7 +56,7 @@ impl Writer for MultiFormatWriter {
width: i32, width: i32,
height: i32, height: i32,
hints: &crate::EncodingHintDictionary, hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
let writer: Box<dyn Writer> = match format { let writer: Box<dyn Writer> = match format {
BarcodeFormat::EAN_8 => Box::<EAN8Writer>::default(), BarcodeFormat::EAN_8 => Box::<EAN8Writer>::default(),
BarcodeFormat::UPC_E => Box::<UPCEWriter>::default(), BarcodeFormat::UPC_E => Box::<UPCEWriter>::default(),

View File

@@ -16,7 +16,7 @@
use rxing_one_d_proc_derive::OneDReader; use rxing_one_d_proc_derive::OneDReader;
use crate::common::BitArray; use crate::common::{BitArray, Result};
use crate::BarcodeFormat; use crate::BarcodeFormat;
use crate::DecodeHintValue; use crate::DecodeHintValue;
use crate::Exceptions; use crate::Exceptions;
@@ -54,7 +54,7 @@ impl OneDReader for CodaBarReader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
self.counters.fill(0); self.counters.fill(0);
// Arrays.fill(counters, 0); // Arrays.fill(counters, 0);
self.setCounters(row)?; 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; // First, sum up the total size of our four categories of stripe sizes;
let mut sizes = [0, 0, 0, 0]; let mut sizes = [0, 0, 0, 0];
let mut counts = [0, 0, 0, 0]; let mut counts = [0, 0, 0, 0];
@@ -305,7 +305,7 @@ impl CodaBarReader {
* uses our builtin "counters" member for storage. * uses our builtin "counters" member for storage.
* @param row row to count from * @param row row to count from
*/ */
fn setCounters(&mut self, row: &BitArray) -> Result<(), Exceptions> { fn setCounters(&mut self, row: &BitArray) -> Result<()> {
self.counterLength = 0; self.counterLength = 0;
// Start from the first white bit. // Start from the first white bit.
let mut i = row.getNextUnset(0); let mut i = row.getNextUnset(0);
@@ -339,7 +339,7 @@ impl CodaBarReader {
} }
} }
fn findStartPattern(&mut self) -> Result<u32, Exceptions> { fn findStartPattern(&mut self) -> Result<u32> {
let mut i = 1; let mut i = 1;
while i < self.counterLength { while i < self.counterLength {
// for (int i = 1; i < counterLength; i += 2) { // for (int i = 1; i < counterLength; i += 2) {

View File

@@ -16,6 +16,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use super::{CodaBarReader, OneDimensionalCodeWriter}; use super::{CodaBarReader, OneDimensionalCodeWriter};
@@ -34,7 +35,7 @@ const DEFAULT_GUARD: char = START_END_CHARS[0];
pub struct CodaBarWriter; pub struct CodaBarWriter;
impl OneDimensionalCodeWriter for CodaBarWriter { impl OneDimensionalCodeWriter for CodaBarWriter {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, crate::Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let contents = if contents.chars().count() < 2 { let contents = if contents.chars().count() < 2 {
// Can't have a start/end guard, so tentatively add default guards // Can't have a start/end guard, so tentatively add default guards
format!("{DEFAULT_GUARD}{contents}{DEFAULT_GUARD}") format!("{DEFAULT_GUARD}{contents}{DEFAULT_GUARD}")

View File

@@ -16,7 +16,10 @@
use rxing_one_d_proc_derive::OneDReader; 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}; use super::{one_d_reader, OneDReader};
@@ -34,7 +37,7 @@ impl OneDReader for Code128Reader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
let convertFNC1 = hints.contains_key(&DecodeHintType::ASSUME_GS1); let convertFNC1 = hints.contains_key(&DecodeHintType::ASSUME_GS1);
let mut symbologyModifier = 0; let mut symbologyModifier = 0;
@@ -354,7 +357,7 @@ impl OneDReader for Code128Reader {
} }
} }
impl 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 width = row.getSize();
let rowOffset = row.getNextSet(0); let rowOffset = row.getNextSet(0);
@@ -410,12 +413,7 @@ impl Code128Reader {
Err(Exceptions::NotFoundException(None)) Err(Exceptions::NotFoundException(None))
} }
fn decodeCode( fn decodeCode(&self, row: &BitArray, counters: &mut [u32; 6], rowOffset: usize) -> Result<u8> {
&self,
row: &BitArray,
counters: &mut [u32; 6],
rowOffset: usize,
) -> Result<u8, Exceptions> {
one_d_reader::recordPattern(row, rowOffset, counters)?; one_d_reader::recordPattern(row, rowOffset, counters)?;
let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
let mut bestMatch = -1_isize; let mut bestMatch = -1_isize;

View File

@@ -16,6 +16,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use super::{code_128_reader, OneDimensionalCodeWriter}; use super::{code_128_reader, OneDimensionalCodeWriter};
@@ -58,7 +59,7 @@ enum CType {
pub struct Code128Writer; pub struct Code128Writer;
impl OneDimensionalCodeWriter for Code128Writer { impl OneDimensionalCodeWriter for Code128Writer {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
self.encode_oned_with_hints(contents, &HashMap::new()) self.encode_oned_with_hints(contents, &HashMap::new())
} }
@@ -70,7 +71,7 @@ impl OneDimensionalCodeWriter for Code128Writer {
&self, &self,
contents: &str, contents: &str,
hints: &crate::EncodingHintDictionary, hints: &crate::EncodingHintDictionary,
) -> Result<Vec<bool>, Exceptions> { ) -> Result<Vec<bool>> {
let forcedCodeSet = check(contents, hints)?; let forcedCodeSet = check(contents, hints)?;
let hasCompactionHint = matches!( let hasCompactionHint = matches!(
@@ -95,7 +96,7 @@ impl OneDimensionalCodeWriter for Code128Writer {
} }
} }
fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, Exceptions> { fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32> {
let length = contents.chars().count(); let length = contents.chars().count();
// Check length // Check length
if !(1..=80).contains(&length) { if !(1..=80).contains(&length) {
@@ -183,7 +184,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
Ok(forcedCodeSet) Ok(forcedCodeSet)
} }
fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exceptions> { fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>> {
let length = contents.chars().count(); let length = contents.chars().count();
let mut patterns: Vec<Vec<usize>> = Vec::new(); //new ArrayList<>(); // temporary storage for patterns let mut patterns: Vec<Vec<usize>> = Vec::new(); //new ArrayList<>(); // temporary storage for patterns
@@ -442,7 +443,7 @@ fn chooseCode(value: &str, start: usize, oldCode: usize) -> Option<usize> {
// minPath:Vec<Vec<Latch>>, // minPath:Vec<Vec<Latch>>,
// } // }
mod MinimalEncoder { mod MinimalEncoder {
use crate::{oned::code_128_reader, Exceptions}; use crate::{common::Result, oned::code_128_reader, Exceptions};
use super::{ use super::{
produceRXingResult, CODE_CODE_A, CODE_CODE_B, CODE_CODE_C, CODE_FNC_1, CODE_FNC_2, 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; const CODE_SHIFT: usize = 98;
pub fn encode(contents: &str) -> Result<Vec<bool>, Exceptions> { pub fn encode(contents: &str) -> Result<Vec<bool>> {
let length = contents.chars().count(); let length = contents.chars().count();
let mut memoizedCost = vec![vec![0_u32; length]; 4]; //new int[4][contents.length()]; let mut memoizedCost = vec![vec![0_u32; length]; 4]; //new int[4][contents.length()];
let mut minPath = vec![vec![Latch::None; length]; 4]; //new Latch[4][contents.length()]; let mut minPath = vec![vec![Latch::None; length]; 4]; //new Latch[4][contents.length()];
@@ -680,7 +681,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
position: usize, position: usize,
memoizedCost: &mut Vec<Vec<u32>>, memoizedCost: &mut Vec<Vec<u32>>,
minPath: &mut Vec<Vec<Latch>>, minPath: &mut Vec<Vec<Latch>>,
) -> Result<u32, Exceptions> { ) -> Result<u32> {
if position >= contents.chars().count() { if position >= contents.chars().count() {
return Err(Exceptions::IllegalStateException(None)); return Err(Exceptions::IllegalStateException(None));
} }

View File

@@ -37,9 +37,9 @@ use std::collections::HashMap;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{ use crate::{
common::{bit_matrix_test_case, BitMatrix}, common::{bit_matrix_test_case, BitMatrix, Result},
oned::{Code128Reader, OneDReader}, oned::{Code128Reader, OneDReader},
BarcodeFormat, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Exceptions, Writer, BarcodeFormat, EncodeHintType, EncodeHintValue, EncodingHintDictionary, Writer,
}; };
use super::Code128Writer; use super::Code128Writer;
@@ -469,7 +469,7 @@ fn testEncodeWithForcedCodeSetFailureCodeSetB() {
assert_eq!(expected, actual); assert_eq!(expected, actual);
} }
fn encode(toEncode: &str, compact: bool, expectedLoopback: &str) -> Result<BitMatrix, Exceptions> { fn encode(toEncode: &str, compact: bool, expectedLoopback: &str) -> Result<BitMatrix> {
let mut reader = Code128Reader::default(); let mut reader = Code128Reader::default();
let mut hints: EncodingHintDictionary = HashMap::new(); let mut hints: EncodingHintDictionary = HashMap::new();

View File

@@ -16,7 +16,7 @@
use rxing_one_d_proc_derive::OneDReader; use rxing_one_d_proc_derive::OneDReader;
use crate::common::BitArray; use crate::common::{BitArray, Result};
use crate::{BarcodeFormat, Exceptions, RXingResult}; use crate::{BarcodeFormat, Exceptions, RXingResult};
use super::{one_d_reader, OneDReader}; use super::{one_d_reader, OneDReader};
@@ -45,7 +45,7 @@ impl OneDReader for Code39Reader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
_hints: &DecodingHintDictionary, _hints: &DecodingHintDictionary,
) -> Result<crate::RXingResult, Exceptions> { ) -> Result<crate::RXingResult> {
let mut counters = [0_u32; 9]; let mut counters = [0_u32; 9];
self.decodeRowRXingResult.clear(); self.decodeRowRXingResult.clear();
@@ -204,7 +204,7 @@ impl Code39Reader {
} }
} }
fn findAsteriskPattern(row: &BitArray, counters: &mut [u32]) -> Result<Vec<u32>, Exceptions> { fn findAsteriskPattern(row: &BitArray, counters: &mut [u32]) -> Result<Vec<u32>> {
let width = row.getSize(); let width = row.getSize();
let rowOffset = row.getNextSet(0); let rowOffset = row.getNextSet(0);
@@ -300,7 +300,7 @@ impl Code39Reader {
-1 -1
} }
fn patternToChar(pattern: u32) -> Result<char, Exceptions> { fn patternToChar(pattern: u32) -> Result<char> {
for i in 0..Self::CHARACTER_ENCODINGS.len() { for i in 0..Self::CHARACTER_ENCODINGS.len() {
if Self::CHARACTER_ENCODINGS[i] == pattern { if Self::CHARACTER_ENCODINGS[i] == pattern {
return Self::ALPHABET_STRING return Self::ALPHABET_STRING
@@ -315,7 +315,7 @@ impl Code39Reader {
Err(Exceptions::NotFoundException(None)) Err(Exceptions::NotFoundException(None))
} }
fn decodeExtended(encoded: &str) -> Result<String, Exceptions> { fn decodeExtended(encoded: &str) -> Result<String> {
let length = encoded.chars().count(); let length = encoded.chars().count();
let mut decoded = String::with_capacity(length); //new StringBuilder(length); let mut decoded = String::with_capacity(length); //new StringBuilder(length);
let mut i = 0; let mut i = 0;

View File

@@ -16,6 +16,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use super::{Code39Reader, OneDimensionalCodeWriter}; use super::{Code39Reader, OneDimensionalCodeWriter};
@@ -29,7 +30,7 @@ use super::{Code39Reader, OneDimensionalCodeWriter};
pub struct Code39Writer; pub struct Code39Writer;
impl OneDimensionalCodeWriter for Code39Writer { impl OneDimensionalCodeWriter for Code39Writer {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let mut contents = contents.to_owned(); let mut contents = contents.to_owned();
let mut length = contents.chars().count(); let mut length = contents.chars().count();
if length > 80 { if length > 80 {
@@ -99,7 +100,7 @@ impl Code39Writer {
} }
} }
fn tryToConvertToExtendedMode(contents: &str) -> Result<String, Exceptions> { fn tryToConvertToExtendedMode(contents: &str) -> Result<String> {
// let length = contents.chars().count(); // let length = contents.chars().count();
let mut extendedContent = String::new(); //new StringBuilder(); let mut extendedContent = String::new(); //new StringBuilder();
for character in contents.chars() { for character in contents.chars() {

View File

@@ -16,7 +16,10 @@
use rxing_one_d_proc_derive::OneDReader; 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}; use super::{one_d_reader, OneDReader};
@@ -47,7 +50,7 @@ impl OneDReader for Code93Reader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
_hints: &crate::DecodingHintDictionary, _hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, Exceptions> { ) -> Result<crate::RXingResult> {
let start = self.findAsteriskPattern(row)?; let start = self.findAsteriskPattern(row)?;
// Read off white space // Read off white space
let mut nextStart = row.getNextSet(start[1]); 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 width = row.getSize();
let rowOffset = row.getNextSet(0); let rowOffset = row.getNextSet(0);
@@ -215,7 +218,7 @@ impl Code93Reader {
pattern pattern
} }
fn patternToChar(pattern: u32) -> Result<char, Exceptions> { fn patternToChar(pattern: u32) -> Result<char> {
for i in 0..Self::CHARACTER_ENCODINGS.len() { for i in 0..Self::CHARACTER_ENCODINGS.len() {
if Self::CHARACTER_ENCODINGS[i] == pattern { if Self::CHARACTER_ENCODINGS[i] == pattern {
return Ok(Self::ALPHABET[i]); return Ok(Self::ALPHABET[i]);
@@ -224,7 +227,7 @@ impl Code93Reader {
Err(Exceptions::NotFoundException(None)) Err(Exceptions::NotFoundException(None))
} }
fn decodeExtended(encoded: &str) -> Result<String, Exceptions> { fn decodeExtended(encoded: &str) -> Result<String> {
let length = encoded.chars().count(); let length = encoded.chars().count();
let mut decoded = String::with_capacity(length); let mut decoded = String::with_capacity(length);
let mut i = 0; let mut i = 0;
@@ -321,18 +324,14 @@ impl Code93Reader {
Ok(decoded) Ok(decoded)
} }
fn checkChecksums(result: &str) -> Result<(), Exceptions> { fn checkChecksums(result: &str) -> Result<()> {
let length = result.chars().count(); let length = result.chars().count();
Self::checkOneChecksum(result, length - 2, 20)?; Self::checkOneChecksum(result, length - 2, 20)?;
Self::checkOneChecksum(result, length - 1, 15)?; Self::checkOneChecksum(result, length - 1, 15)?;
Ok(()) Ok(())
} }
fn checkOneChecksum( fn checkOneChecksum(result: &str, checkPosition: usize, weightMax: u32) -> Result<()> {
result: &str,
checkPosition: usize,
weightMax: u32,
) -> Result<(), Exceptions> {
let mut weight = 1; let mut weight = 1;
let mut total = 0; let mut total = 0;
for i in (0..checkPosition).rev() { for i in (0..checkPosition).rev() {

View File

@@ -16,6 +16,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use super::{Code93Reader, OneDimensionalCodeWriter}; 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. * @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) * @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/ */
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let mut contents = Self::convertToExtended(contents)?; let mut contents = Self::convertToExtended(contents)?;
let length = contents.chars().count(); let length = contents.chars().count();
if length > 80 { if length > 80 {
@@ -142,7 +143,7 @@ impl Code93Writer {
total as usize % 47 total as usize % 47
} }
fn convertToExtended(contents: &str) -> Result<String, Exceptions> { fn convertToExtended(contents: &str) -> Result<String> {
let length = contents.chars().count(); let length = contents.chars().count();
let mut extendedContent = String::with_capacity(length * 2); let mut extendedContent = String::with_capacity(length * 2);
for character in contents.chars() { for character in contents.chars() {

View File

@@ -21,6 +21,7 @@ use super::UPCEANReader;
use super::upc_ean_reader; use super::upc_ean_reader;
use super::OneDReader; use super::OneDReader;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use crate::Exceptions; use crate::Exceptions;
@@ -43,7 +44,7 @@ impl UPCEANReader for EAN13Reader {
row: &crate::common::BitArray, row: &crate::common::BitArray,
startRange: &[usize; 2], startRange: &[usize; 2],
resultString: &mut String, resultString: &mut String,
) -> Result<usize, crate::Exceptions> { ) -> Result<usize> {
let mut counters = [0_u32; 4]; //decodeMiddleCounters; let mut counters = [0_u32; 4]; //decodeMiddleCounters;
// counters[0] = 0; // counters[0] = 0;
// counters[1] = 0; // counters[1] = 0;
@@ -145,10 +146,7 @@ impl EAN13Reader {
* encode digits * encode digits
* @throws NotFoundException if first digit cannot be determined * @throws NotFoundException if first digit cannot be determined
*/ */
fn determineFirstDigit( fn determineFirstDigit(resultString: &mut String, lgPatternFound: usize) -> Result<()> {
resultString: &mut String,
lgPatternFound: usize,
) -> Result<(), Exceptions> {
for d in 0..10 { for d in 0..10 {
// for (int d = 0; d < 10; d++) { // for (int d = 0; d < 10; d++) {
if lgPatternFound == Self::FIRST_DIGIT_ENCODINGS[d] { if lgPatternFound == Self::FIRST_DIGIT_ENCODINGS[d] {

View File

@@ -17,6 +17,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::{ use crate::{
common::Result,
oned::{upc_ean_reader, EAN13Reader}, oned::{upc_ean_reader, EAN13Reader},
BarcodeFormat, BarcodeFormat,
}; };
@@ -33,7 +34,7 @@ pub struct EAN13Writer;
impl UPCEANWriter for EAN13Writer {} impl UPCEANWriter for EAN13Writer {}
impl OneDimensionalCodeWriter for EAN13Writer { impl OneDimensionalCodeWriter for EAN13Writer {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, crate::Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let reader: EAN13Reader = EAN13Reader::default(); let reader: EAN13Reader = EAN13Reader::default();
let mut contents = contents.to_owned(); let mut contents = contents.to_owned();
let length = contents.chars().count(); let length = contents.chars().count();

View File

@@ -15,6 +15,7 @@
*/ */
use super::OneDReader; use super::OneDReader;
use crate::common::Result;
use crate::{BarcodeFormat, Exceptions}; use crate::{BarcodeFormat, Exceptions};
use rxing_one_d_proc_derive::{EANReader, OneDReader}; use rxing_one_d_proc_derive::{EANReader, OneDReader};
@@ -39,7 +40,7 @@ impl UPCEANReader for EAN8Reader {
row: &crate::common::BitArray, row: &crate::common::BitArray,
startRange: &[usize; 2], startRange: &[usize; 2],
resultString: &mut String, resultString: &mut String,
) -> Result<usize, Exceptions> { ) -> Result<usize> {
let mut counters = [0_u32; 4]; //decodeMiddleCounters; let mut counters = [0_u32; 4]; //decodeMiddleCounters;
// counters[0] = 0; // counters[0] = 0;
// counters[1] = 0; // counters[1] = 0;

View File

@@ -17,6 +17,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::{ use crate::{
common::Result,
oned::{EAN8Reader, UPCEANReader}, oned::{EAN8Reader, UPCEANReader},
BarcodeFormat, BarcodeFormat,
}; };
@@ -42,7 +43,7 @@ impl OneDimensionalCodeWriter for EAN8Writer {
/** /**
* @return a byte array of horizontal pixels (false = white, true = black) * @return a byte array of horizontal pixels (false = white, true = black)
*/ */
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let length = contents.chars().count(); let length = contents.chars().count();
let reader = EAN8Reader::default(); let reader = EAN8Reader::default();
let mut contents = contents.to_owned(); let mut contents = contents.to_owned();

View File

@@ -16,7 +16,10 @@
use rxing_one_d_proc_derive::OneDReader; 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}; use super::{one_d_reader, OneDReader};
@@ -106,7 +109,7 @@ impl OneDReader for ITFReader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
// Find out where the Middle section (payload) starts & ends // Find out where the Middle section (payload) starts & ends
let mut row = row.clone(); let mut row = row.clone();
let startRange = self.decodeStart(&row)?; let startRange = self.decodeStart(&row)?;
@@ -174,7 +177,7 @@ impl ITFReader {
payloadStart: usize, payloadStart: usize,
payloadEnd: usize, payloadEnd: usize,
resultString: &mut String, resultString: &mut String,
) -> Result<(), Exceptions> { ) -> Result<()> {
let mut payloadStart = payloadStart; let mut payloadStart = payloadStart;
// Digits are interleaved in pairs - 5 black lines for one digit, and the // Digits are interleaved in pairs - 5 black lines for one digit, and the
// 5 interleaved white lines for the second digit. // 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 * @return Array, containing index of start of 'start block' and end of
* 'start block' * '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 endStart = Self::skipWhiteSpace(row)?;
let startPattern = self.findGuardPattern(row, endStart, &START_PATTERN)?; 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. * @param startPattern index into row of the start or end pattern.
* @throws NotFoundException if the quiet zone cannot be found * @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 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 // 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. * @return index of the first black line.
* @throws NotFoundException Throws exception if no black lines are found in the row * @throws NotFoundException Throws exception if no black lines are found in the row
*/ */
fn skipWhiteSpace(row: &BitArray) -> Result<usize, Exceptions> { fn skipWhiteSpace(row: &BitArray) -> Result<usize> {
let width = row.getSize(); let width = row.getSize();
let endStart = row.getNextSet(0); let endStart = row.getNextSet(0);
if endStart == width { if endStart == width {
@@ -292,11 +295,11 @@ impl ITFReader {
* @return Array, containing index of start of 'end block' and end of 'end * @return Array, containing index of start of 'end block' and end of 'end
* block' * 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 // For convenience, reverse the row and then
// search from 'the start' for the end block // search from 'the start' for the end block
row.reverse(); row.reverse();
let interim_function = || -> Result<[usize; 2], Exceptions> { let interim_function = || -> Result<[usize; 2]> {
let endStart = Self::skipWhiteSpace(row)?; let endStart = Self::skipWhiteSpace(row)?;
let mut endPattern = let mut endPattern =
if let Ok(ptrn) = self.findGuardPattern(row, endStart, &END_PATTERN_REVERSED[0]) { if let Ok(ptrn) = self.findGuardPattern(row, endStart, &END_PATTERN_REVERSED[0]) {
@@ -339,7 +342,7 @@ impl ITFReader {
row: &BitArray, row: &BitArray,
rowOffset: usize, rowOffset: usize,
pattern: &[u32], pattern: &[u32],
) -> Result<[usize; 2], Exceptions> { ) -> Result<[usize; 2]> {
let patternLength = pattern.len(); let patternLength = pattern.len();
let mut counters = vec![0u32; patternLength]; //new int[patternLength]; let mut counters = vec![0u32; patternLength]; //new int[patternLength];
let width = row.getSize(); let width = row.getSize();
@@ -385,7 +388,7 @@ impl ITFReader {
* @return The decoded digit * @return The decoded digit
* @throws NotFoundException if digit cannot be decoded * @throws NotFoundException if digit cannot be decoded
*/ */
fn decodeDigit(&self, counters: &[u32]) -> Result<u32, Exceptions> { fn decodeDigit(&self, counters: &[u32]) -> Result<u32> {
let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept let mut bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
let mut bestMatch = -1_isize; let mut bestMatch = -1_isize;
let max = PATTERNS.len(); let max = PATTERNS.len();

View File

@@ -16,6 +16,7 @@
use rxing_one_d_proc_derive::OneDWriter; use rxing_one_d_proc_derive::OneDWriter;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use super::OneDimensionalCodeWriter; use super::OneDimensionalCodeWriter;
@@ -29,7 +30,7 @@ use super::OneDimensionalCodeWriter;
pub struct ITFWriter; pub struct ITFWriter;
impl OneDimensionalCodeWriter for ITFWriter { impl OneDimensionalCodeWriter for ITFWriter {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, contents: &str) -> Result<Vec<bool>> {
let length = contents.chars().count(); let length = contents.chars().count();
if length % 2 != 0 { if length % 2 != 0 {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(

View File

@@ -23,6 +23,7 @@ use super::Code93Reader;
use super::ITFReader; use super::ITFReader;
use super::MultiFormatUPCEANReader; use super::MultiFormatUPCEANReader;
use super::OneDReader; use super::OneDReader;
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use crate::DecodeHintValue; use crate::DecodeHintValue;
use crate::Exceptions; use crate::Exceptions;
@@ -39,7 +40,7 @@ impl OneDReader for MultiFormatOneDReader {
rowNumber: u32, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
for reader in self.0.iter_mut() { for reader in self.0.iter_mut() {
if let Ok(res) = reader.decodeRow(rowNumber, row, hints) { if let Ok(res) = reader.decodeRow(rowNumber, row, hints) {
return Ok(res); return Ok(res);
@@ -113,10 +114,7 @@ use crate::Reader;
use std::collections::HashMap; use std::collections::HashMap;
impl Reader for MultiFormatOneDReader { impl Reader for MultiFormatOneDReader {
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, Exceptions> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -125,7 +123,7 @@ impl Reader for MultiFormatOneDReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &DecodingHintDictionary, hints: &DecodingHintDictionary,
) -> Result<crate::RXingResult, Exceptions> { ) -> Result<crate::RXingResult> {
let first_try = self.doDecode(image, hints); let first_try = self.doDecode(image, hints);
if first_try.is_ok() { if first_try.is_ok() {
return first_try; return first_try;

View File

@@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::Result;
use crate::BarcodeFormat; use crate::BarcodeFormat;
use crate::DecodeHintValue; use crate::DecodeHintValue;
use crate::Exceptions; use crate::Exceptions;
@@ -74,7 +75,7 @@ impl MultiFormatUPCEANReader {
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
startGuardPattern: &[usize; 2], startGuardPattern: &[usize; 2],
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
let result = reader.decodeRowWithGuardRange(rowNumber, row, startGuardPattern, hints)?; let result = reader.decodeRowWithGuardRange(rowNumber, row, startGuardPattern, hints)?;
// Special case: a 12-digit code encoded in UPC-A is identical to a "0" // 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, // 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, rowNumber: u32,
row: &crate::common::BitArray, row: &crate::common::BitArray,
hints: &crate::DecodingHintDictionary, hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> { ) -> Result<crate::RXingResult> {
// Compute this location once and reuse it on multiple implementations // Compute this location once and reuse it on multiple implementations
let startGuardPattern = STAND_IN.findStartGuardPattern(row)?; let startGuardPattern = STAND_IN.findStartGuardPattern(row)?;
for reader in &self.0 { for reader in &self.0 {
@@ -145,10 +146,7 @@ use crate::RXingResultMetadataValue;
use std::collections::HashMap; use std::collections::HashMap;
impl Reader for MultiFormatUPCEANReader { impl Reader for MultiFormatUPCEANReader {
fn decode( fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, Exceptions> {
self.decode_with_hints(image, &HashMap::new()) self.decode_with_hints(image, &HashMap::new())
} }
@@ -157,7 +155,7 @@ impl Reader for MultiFormatUPCEANReader {
&mut self, &mut self,
image: &mut crate::BinaryBitmap, image: &mut crate::BinaryBitmap,
hints: &DecodingHintDictionary, hints: &DecodingHintDictionary,
) -> Result<crate::RXingResult, Exceptions> { ) -> Result<crate::RXingResult> {
let first_try = self.doDecode(image, hints); let first_try = self.doDecode(image, hints);
if first_try.is_ok() { if first_try.is_ok() {
return first_try; return first_try;

View File

@@ -17,7 +17,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::BitMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, common::{BitMatrix, Result},
BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@@ -40,7 +41,7 @@ pub trait OneDimensionalCodeWriter: Writer {
* @param contents barcode contents to encode * @param contents barcode contents to encode
* @return a {@code boolean[]} of horizontal pixels (false = white, true = black) * @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/ */
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions>; fn encode_oned(&self, contents: &str) -> Result<Vec<bool>>;
/** /**
* Can be overwritten if the encode requires to read the hints map. Otherwise it defaults to {@code encode}. * 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, &self,
contents: &str, contents: &str,
_hints: &crate::EncodingHintDictionary, _hints: &crate::EncodingHintDictionary,
) -> Result<Vec<bool>, Exceptions> { ) -> Result<Vec<bool>> {
self.encode_oned(contents) self.encode_oned(contents)
} }
@@ -68,7 +69,7 @@ pub trait OneDimensionalCodeWriter: Writer {
width: i32, width: i32,
height: i32, height: i32,
sidesMargin: u32, sidesMargin: u32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix> {
let inputWidth = code.len(); let inputWidth = code.len();
// Add quiet zone on both sides. // Add quiet zone on both sides.
let fullWidth = inputWidth + sidesMargin as usize; let fullWidth = inputWidth + sidesMargin as usize;
@@ -98,7 +99,7 @@ pub trait OneDimensionalCodeWriter: Writer {
* @param contents string to check for numeric characters * @param contents string to check for numeric characters
* @throws IllegalArgumentException if input contains characters other than digits 0-9. * @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) { if !NUMERIC.is_match(contents) {
Err(Exceptions::IllegalArgumentException(Some( Err(Exceptions::IllegalArgumentException(Some(
"Input should only contain digits 0-9".to_owned(), "Input should only contain digits 0-9".to_owned(),
@@ -150,7 +151,7 @@ impl Writer for L {
format: &crate::BarcodeFormat, format: &crate::BarcodeFormat,
width: i32, width: i32,
height: i32, height: i32,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
self.encode_with_hints(contents, format, width, height, &HashMap::new()) self.encode_with_hints(contents, format, width, height, &HashMap::new())
} }
@@ -161,7 +162,7 @@ impl Writer for L {
width: i32, width: i32,
height: i32, height: i32,
hints: &crate::EncodingHintDictionary, hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix> {
if contents.is_empty() { if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some( return Err(Exceptions::IllegalArgumentException(Some(
"Found empty contents".to_owned(), "Found empty contents".to_owned(),
@@ -195,7 +196,7 @@ impl Writer for L {
} }
impl OneDimensionalCodeWriter for L { impl OneDimensionalCodeWriter for L {
fn encode_oned(&self, _contents: &str) -> Result<Vec<bool>, Exceptions> { fn encode_oned(&self, _contents: &str) -> Result<Vec<bool>> {
todo!() todo!()
} }
} }

View File

@@ -15,9 +15,9 @@
*/ */
use crate::{ use crate::{
common::BitArray, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, common::{BitArray, Result},
Exceptions, RXingResult, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, BinaryBitmap, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions, RXingResult,
Reader, ResultPoint, RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader, ResultPoint,
}; };
/** /**
@@ -46,7 +46,7 @@ pub trait OneDReader: Reader {
&mut self, &mut self,
image: &mut BinaryBitmap, image: &mut BinaryBitmap,
hints: &DecodingHintDictionary, hints: &DecodingHintDictionary,
) -> Result<RXingResult, Exceptions> { ) -> Result<RXingResult> {
let mut hints = hints.clone(); let mut hints = hints.clone();
let width = image.getWidth(); let width = image.getWidth();
let height = image.getHeight(); let height = image.getHeight();
@@ -151,7 +151,7 @@ pub trait OneDReader: Reader {
rowNumber: u32, rowNumber: u32,
row: &BitArray, row: &BitArray,
hints: &DecodingHintDictionary, hints: &DecodingHintDictionary,
) -> Result<RXingResult, Exceptions>; ) -> Result<RXingResult>;
} }
/** /**
@@ -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 * @throws NotFoundException if counters cannot be filled entirely from row before running out
* of pixels * 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(); let numCounters = counters.len();
counters.fill(0); counters.fill(0);
@@ -246,11 +246,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu
Ok(()) Ok(())
} }
pub fn recordPatternInReverse( pub fn recordPatternInReverse(row: &BitArray, start: usize, counters: &mut [u32]) -> Result<()> {
row: &BitArray,
start: usize,
counters: &mut [u32],
) -> Result<(), Exceptions> {
let mut start = start; let mut start = start;
// This could be more efficient I guess // This could be more efficient I guess
let mut numTransitionsLeft = counters.len() as isize; let mut numTransitionsLeft = counters.len() as isize;

View File

@@ -15,6 +15,7 @@
*/ */
use crate::{ use crate::{
common::Result,
oned::{one_d_reader, OneDReader}, oned::{one_d_reader, OneDReader},
Exceptions, Exceptions,
}; };
@@ -30,7 +31,7 @@ pub trait AbstractRSSReaderTrait: OneDReader {
const MIN_FINDER_PATTERN_RATIO: f32 = 9.5 / 12.0; const MIN_FINDER_PATTERN_RATIO: f32 = 9.5 / 12.0;
const MAX_FINDER_PATTERN_RATIO: f32 = 12.5 / 14.0; const MAX_FINDER_PATTERN_RATIO: f32 = 12.5 / 14.0;
fn parseFinderValue(counters: &[u32], finderPatterns: &[[u32; 4]]) -> Result<u32, Exceptions> { fn parseFinderValue(counters: &[u32], finderPatterns: &[[u32; 4]]) -> Result<u32> {
for (value, pattern) in finderPatterns.iter().enumerate() { for (value, pattern) in finderPatterns.iter().enumerate() {
if one_d_reader::patternMatchVariance(counters, pattern, Self::MAX_INDIVIDUAL_VARIANCE) if one_d_reader::patternMatchVariance(counters, pattern, Self::MAX_INDIVIDUAL_VARIANCE)
< Self::MAX_AVG_VARIANCE < Self::MAX_AVG_VARIANCE

View File

@@ -30,7 +30,10 @@
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use crate::{common::BitArray, Exceptions}; use crate::{
common::{BitArray, Result},
Exceptions,
};
static ONE: Lazy<Regex> = Lazy::new(|| Regex::new("1").unwrap()); static ONE: Lazy<Regex> = Lazy::new(|| Regex::new("1").unwrap());
static ZERO: Lazy<Regex> = Lazy::new(|| Regex::new("0").unwrap()); static ZERO: Lazy<Regex> = Lazy::new(|| Regex::new("0").unwrap());
@@ -39,7 +42,7 @@ static SPACE: Lazy<Regex> = Lazy::new(|| Regex::new(" ").unwrap());
/* /*
* Constructs a BitArray from a String like the one returned from BitArray.toString() * Constructs a BitArray from a String like the one returned from BitArray.toString()
*/ */
pub fn buildBitArrayFromString(data: &str) -> Result<BitArray, Exceptions> { pub fn buildBitArrayFromString(data: &str) -> Result<BitArray> {
let dotsAndXs = ZERO let dotsAndXs = ZERO
.replace_all(&ONE.replace_all(data, "X"), ".") .replace_all(&ONE.replace_all(data, "X"), ".")
.to_string(); .to_string();
@@ -75,7 +78,7 @@ pub fn buildBitArrayFromString(data: &str) -> Result<BitArray, Exceptions> {
Ok(binary) Ok(binary)
} }
pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray, Exceptions> { pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray> {
let mut sb = String::new(); let mut sb = String::new();
// let dotsAndXs = ZERO.matcher(ONE.matcher(data).replaceAll("X")).replaceAll("."); // let dotsAndXs = ZERO.matcher(ONE.matcher(data).replaceAll("X")).replaceAll(".");

View File

@@ -24,7 +24,10 @@
* http://www.piramidepse.com/ * http://www.piramidepse.com/
*/ */
use crate::{common::BitArray, Exceptions}; use crate::{
common::{BitArray, Result},
Exceptions,
};
use super::{ use super::{
AI013103decoder, AI01320xDecoder, AI01392xDecoder, AI01393xDecoder, AI013x0x1xDecoder, AI013103decoder, AI01320xDecoder, AI01392xDecoder, AI01393xDecoder, AI013x0x1xDecoder,
@@ -53,14 +56,14 @@ pub trait AbstractExpandedDecoder {
// return generalDecoder; // return generalDecoder;
// } // }
fn parseInformation(&mut self) -> Result<String, Exceptions>; fn parseInformation(&mut self) -> Result<String>;
fn getGeneralDecoder(&self) -> &GeneralAppIdDecoder; fn getGeneralDecoder(&self) -> &GeneralAppIdDecoder;
// fn new(information:&BitArray) -> Self where Self:Sized; // fn new(information:&BitArray) -> Self where Self:Sized;
} }
pub fn createDecoder<'a>( pub fn createDecoder<'a>(
information: &'a BitArray, information: &'a BitArray,
) -> Result<Box<dyn AbstractExpandedDecoder + 'a>, Exceptions> { ) -> Result<Box<dyn AbstractExpandedDecoder + 'a>> {
if information.get(1) { if information.get(1) {
return Ok(Box::new(AI01AndOtherAIs::new(information))); return Ok(Box::new(AI01AndOtherAIs::new(information)));
} }

View File

@@ -24,7 +24,7 @@
* http://www.piramidepse.com/ * http://www.piramidepse.com/
*/ */
use crate::common::BitArray; use crate::common::{BitArray, Result};
use super::{AI013x0xDecoder, AI01decoder, AI01weightDecoder, AbstractExpandedDecoder}; use super::{AI013x0xDecoder, AI01decoder, AI01weightDecoder, AbstractExpandedDecoder};
@@ -43,7 +43,7 @@ impl AI01weightDecoder for AI013103decoder<'_> {
} }
} }
impl AbstractExpandedDecoder for AI013103decoder<'_> { impl AbstractExpandedDecoder for AI013103decoder<'_> {
fn parseInformation(&mut self) -> Result<String, crate::Exceptions> { fn parseInformation(&mut self) -> Result<String> {
self.0.parseInformation() self.0.parseInformation()
} }

Some files were not shown because too many files have changed in this diff Show More