Merge pull request #9 from Asha20/pr/refactor

Refactor to use common result type
This commit is contained in:
Henry A Schimke
2023-02-16 06:57:04 +09:00
committed by GitHub
160 changed files with 837 additions and 906 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,7 +16,7 @@
use std::fmt;
use crate::{common::BitArray, Exceptions};
use crate::common::{BitArray, Result};
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BinaryShiftToken {
@@ -32,7 +32,7 @@ impl BinaryShiftToken {
}
}
pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<(), Exceptions> {
pub fn appendTo(&self, bit_array: &mut BitArray, text: &[u8]) -> Result<()> {
let bsbc = self.binary_shift_byte_count as usize;
for i in 0..bsbc {
// for (int i = 0; i < bsbc; i++) {

View File

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

View File

@@ -16,7 +16,7 @@
use std::fmt;
use crate::{common::BitArray, Exceptions};
use crate::common::{BitArray, Result};
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct SimpleToken {
@@ -33,7 +33,7 @@ impl SimpleToken {
}
}
pub fn appendTo(&self, bit_array: &mut BitArray, _text: &[u8]) -> Result<(), Exceptions> {
pub fn appendTo(&self, bit_array: &mut BitArray, _text: &[u8]) -> Result<()> {
bit_array.appendBits(self.value as u32, self.bit_count as usize)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -17,7 +17,8 @@
use regex::Regex;
use crate::{
client::result::VINParsedRXingResult, exceptions::Exceptions, BarcodeFormat, RXingResult,
client::result::VINParsedRXingResult, common::Result, exceptions::Exceptions, BarcodeFormat,
RXingResult,
};
use super::ParsedClientResult;
@@ -67,7 +68,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
const IOQ: &str = "[IOQ]";
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;
for i in 0..vin.len() {
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)
}
fn vin_char_value(c: char) -> Result<u32, Exceptions> {
fn vin_char_value(c: char) -> Result<u32> {
match c {
'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1),
'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1),
@@ -97,7 +98,7 @@ fn vin_char_value(c: char) -> Result<u32, Exceptions> {
}
}
fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
fn vin_position_weight(position: usize) -> Result<usize> {
match position {
1..=7 => Ok(9 - position),
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 {
0..=9 => Ok((b'0' + remainder) as char),
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 {
'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),

View File

@@ -20,6 +20,7 @@
use std::{cmp, fmt};
use crate::common::Result;
use crate::Exceptions;
static LOAD_FACTOR: f32 = 0.75f32;
@@ -165,7 +166,7 @@ impl BitArray {
* @param start start of range, inclusive.
* @param end end of range, exclusive
*/
pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> {
pub fn setRange(&mut self, start: usize, end: usize) -> Result<()> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None));
@@ -208,7 +209,7 @@ impl BitArray {
* @return true iff all bits are set or not set in range, according to value argument
* @throws IllegalArgumentException if end is less than start or the range is not contained in the array
*/
pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool, Exceptions> {
pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None));
@@ -251,7 +252,7 @@ impl BitArray {
* @param value {@code int} containing bits to append
* @param numBits bits from value to append
*/
pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> {
pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<()> {
if num_bits > 32 {
return Err(Exceptions::IllegalArgumentException(Some(
"num bits must be between 0 and 32".to_owned(),
@@ -284,7 +285,7 @@ impl BitArray {
}
}
pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> {
pub fn xor(&mut self, other: &BitArray) -> Result<()> {
if self.size != other.size {
return Err(Exceptions::IllegalArgumentException(Some(
"Sizes don't match".to_owned(),

View File

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

View File

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

View File

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

View File

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

View File

@@ -17,7 +17,10 @@
//package com.google.zxing.common.detector;
use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint};
use crate::{
common::{BitMatrix, Result},
Exceptions, RXingResultPoint, ResultPoint,
};
/**
* <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
* @throws NotFoundException if no Data Matrix Code can be found
*/
pub fn detect(&self) -> Result<[RXingResultPoint; 4], Exceptions> {
pub fn detect(&self) -> Result<[RXingResultPoint; 4]> {
let height = self.image.getHeight() as i32;
let width = self.image.getWidth() as i32;
let halfHeight = height / 2;
@@ -155,7 +158,7 @@ impl<'a> MonochromeRectangleDetector<'_> {
top: i32,
bottom: i32,
maxWhiteRun: i32,
) -> Result<RXingResultPoint, Exceptions> {
) -> Result<RXingResultPoint> {
let mut lastRange_z: Option<[i32; 2]> = None;
let mut y: i32 = centerY;
let mut x: i32 = centerX;

View File

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

View File

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

View File

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

View File

@@ -24,6 +24,7 @@ use std::{borrow::Cow, rc::Rc};
use once_cell::unsync::OnceCell;
use crate::common::Result;
use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{BitArray, BitMatrix};
@@ -54,7 +55,7 @@ impl Binarizer for GlobalHistogramBinarizer {
}
// Applies simple sharpening to the row data to improve performance of the 1D Readers.
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions> {
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
let row = self.black_row_cache[y].get_or_try_init(|| {
let source = self.getLuminanceSource();
let width = source.getWidth();
@@ -101,7 +102,7 @@ impl Binarizer for GlobalHistogramBinarizer {
}
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> {
fn getBlackMatrix(&self) -> Result<&BitMatrix> {
let matrix = self
.black_matrix
.get_or_try_init(|| Self::build_black_matrix(&self.source))?;
@@ -138,7 +139,7 @@ impl GlobalHistogramBinarizer {
}
}
fn build_black_matrix(source: &Box<dyn LuminanceSource>) -> Result<BitMatrix, Exceptions> {
fn build_black_matrix(source: &Box<dyn LuminanceSource>) -> Result<BitMatrix> {
// let source = source.getLuminanceSource();
let width = source.getWidth();
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.
let numBuckets = buckets.len();
let mut maxBucketCount = 0;

View File

@@ -18,6 +18,7 @@
// import com.google.zxing.NotFoundException;
use crate::common::Result;
use crate::Exceptions;
use super::{BitMatrix, PerspectiveTransform};
@@ -108,7 +109,7 @@ pub trait GridSampler {
p3FromY: f32,
p4FromX: f32,
p4FromY: f32,
) -> Result<BitMatrix, Exceptions>;
) -> Result<BitMatrix>;
fn sample_grid(
&self,
@@ -116,7 +117,7 @@ pub trait GridSampler {
dimensionX: u32,
dimensionY: u32,
transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions>;
) -> Result<BitMatrix>;
/**
* <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
* @throws NotFoundException if an endpoint is lies outside the image boundaries
*/
fn checkAndNudgePoints(&self, image: &BitMatrix, points: &mut [f32]) -> Result<(), Exceptions> {
fn checkAndNudgePoints(&self, image: &BitMatrix, points: &mut [f32]) -> Result<()> {
let width = image.getWidth();
let height = image.getHeight();
// Check and nudge points from start until we see some that are OK:

View File

@@ -24,7 +24,8 @@ use std::{borrow::Cow, rc::Rc};
use once_cell::unsync::OnceCell;
use crate::{Binarizer, Exceptions, LuminanceSource};
use crate::common::Result;
use crate::{Binarizer, LuminanceSource};
use super::{BitArray, BitMatrix, GlobalHistogramBinarizer};
@@ -57,7 +58,7 @@ impl Binarizer for HybridBinarizer {
self.ghb.getLuminanceSource()
}
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>, Exceptions> {
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
self.ghb.getBlackRow(y)
}
@@ -66,7 +67,7 @@ impl Binarizer for HybridBinarizer {
* constructor instead, but there are some advantages to doing it lazily, such as making
* profiling easier, and not doing heavy lifting when callers don't expect it.
*/
fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> {
fn getBlackMatrix(&self) -> Result<&BitMatrix> {
let matrix = self
.black_matrix
.get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?;
@@ -102,7 +103,7 @@ impl HybridBinarizer {
}
}
fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result<BitMatrix, Exceptions> {
fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result<BitMatrix> {
// let matrix;
let source = ghb.getLuminanceSource();
let width = source.getWidth();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -17,6 +17,7 @@
use core::fmt;
use once_cell::sync::Lazy;
use crate::common::Result;
use crate::Exceptions;
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
* @throws FormatException if dimensions do correspond to a valid Data Matrix size
*/
pub fn getVersionForDimensions(
numRows: u32,
numColumns: u32,
) -> Result<&'static Version, Exceptions> {
pub fn getVersionForDimensions(numRows: u32, numColumns: u32) -> Result<&'static Version> {
if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 {
return Err(Exceptions::FormatException(None));
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,6 +16,7 @@
use std::rc::Rc;
use crate::common::Result;
use crate::{Dimension, Exceptions};
use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint};
@@ -40,13 +41,13 @@ impl<'a> EncoderContext<'_> {
pub fn with_symbol_info_lookup(
msg: &str,
symbol_lookup: Rc<SymbolInfoLookup<'a>>,
) -> Result<EncoderContext<'a>, Exceptions> {
) -> Result<EncoderContext<'a>> {
let mut new_self = EncoderContext::new(msg)?;
new_self.symbol_lookup = symbol_lookup.clone();
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!
// 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());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult};
use crate::{common::Result, BinaryBitmap, DecodingHintDictionary, RXingResult};
/**
* Implementation of this interface attempt to read several barcodes from one image.
@@ -23,12 +23,11 @@ use crate::{BinaryBitmap, DecodingHintDictionary, Exceptions, RXingResult};
* @author Sean Owen
*/
pub trait MultipleBarcodeReader {
fn decode_multiple(&mut self, image: &mut BinaryBitmap)
-> Result<Vec<RXingResult>, Exceptions>;
fn decode_multiple(&mut self, image: &mut BinaryBitmap) -> Result<Vec<RXingResult>>;
fn decode_multiple_with_hints(
&mut self,
image: &mut BinaryBitmap,
hints: &DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions>;
) -> Result<Vec<RXingResult>>;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -30,7 +30,10 @@
use once_cell::sync::Lazy;
use regex::Regex;
use crate::{common::BitArray, Exceptions};
use crate::{
common::{BitArray, Result},
Exceptions,
};
static ONE: Lazy<Regex> = Lazy::new(|| Regex::new("1").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()
*/
pub fn buildBitArrayFromString(data: &str) -> Result<BitArray, Exceptions> {
pub fn buildBitArrayFromString(data: &str) -> Result<BitArray> {
let dotsAndXs = ZERO
.replace_all(&ONE.replace_all(data, "X"), ".")
.to_string();
@@ -75,7 +78,7 @@ pub fn buildBitArrayFromString(data: &str) -> Result<BitArray, Exceptions> {
Ok(binary)
}
pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray, Exceptions> {
pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray> {
let mut sb = String::new();
// let dotsAndXs = ZERO.matcher(ONE.matcher(data).replaceAll("X")).replaceAll(".");

View File

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

View File

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

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