From 5ce1a89abe01d141fb66b36f32f20dcf5271a83c Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 28 Aug 2022 18:31:21 -0500 Subject: [PATCH] enum exceptions --- .../common/BitArrayTestCase.java | 0 .../common/BitMatrixTestCase.java | 0 .../common/BitSourceBuilder.java | 0 .../common/StringUtilsTestCase.java | 0 .../zxing => src}/common/TestResult.java | 0 src/common/detector/mod.rs | 28 +-- src/common/mod.rs | 68 +++--- .../reedsolomon/GenericGFPolyTestCase.rs | 4 +- src/common/reedsolomon/ReedSolomonTestCase.rs | 2 +- src/common/reedsolomon/mod.rs | 127 ++++------- src/exceptions.rs | 205 ++---------------- src/lib.rs | 66 +++--- 12 files changed, 137 insertions(+), 363 deletions(-) rename {java_test/java/com/google/zxing => src}/common/BitArrayTestCase.java (100%) rename {java_test/java/com/google/zxing => src}/common/BitMatrixTestCase.java (100%) rename {java_test/java/com/google/zxing => src}/common/BitSourceBuilder.java (100%) mode change 100755 => 100644 rename {java_test/java/com/google/zxing => src}/common/StringUtilsTestCase.java (100%) rename {java_test/java/com/google/zxing => src}/common/TestResult.java (100%) diff --git a/java_test/java/com/google/zxing/common/BitArrayTestCase.java b/src/common/BitArrayTestCase.java similarity index 100% rename from java_test/java/com/google/zxing/common/BitArrayTestCase.java rename to src/common/BitArrayTestCase.java diff --git a/java_test/java/com/google/zxing/common/BitMatrixTestCase.java b/src/common/BitMatrixTestCase.java similarity index 100% rename from java_test/java/com/google/zxing/common/BitMatrixTestCase.java rename to src/common/BitMatrixTestCase.java diff --git a/java_test/java/com/google/zxing/common/BitSourceBuilder.java b/src/common/BitSourceBuilder.java old mode 100755 new mode 100644 similarity index 100% rename from java_test/java/com/google/zxing/common/BitSourceBuilder.java rename to src/common/BitSourceBuilder.java diff --git a/java_test/java/com/google/zxing/common/StringUtilsTestCase.java b/src/common/StringUtilsTestCase.java similarity index 100% rename from java_test/java/com/google/zxing/common/StringUtilsTestCase.java rename to src/common/StringUtilsTestCase.java diff --git a/java_test/java/com/google/zxing/common/TestResult.java b/src/common/TestResult.java similarity index 100% rename from java_test/java/com/google/zxing/common/TestResult.java rename to src/common/TestResult.java diff --git a/src/common/detector/mod.rs b/src/common/detector/mod.rs index 01efcdf..0b4a4fc 100644 --- a/src/common/detector/mod.rs +++ b/src/common/detector/mod.rs @@ -1,6 +1,6 @@ pub mod MathUtils; use crate::common::BitMatrix; -use crate::{NotFoundException, RXingResultPoint}; +use crate::{Exceptions, RXingResultPoint}; /* * Copyright 2009 ZXing authors @@ -49,7 +49,7 @@ impl MonochromeRectangleDetector { * third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ - pub fn detect(&self) -> Result, NotFoundException> { + pub fn detect(&self) -> Result, Exceptions> { let height = self.image.getHeight() as i32; let width = self.image.getWidth() as i32; let halfHeight= height / 2; @@ -155,7 +155,7 @@ impl MonochromeRectangleDetector { top: i32, bottom: i32, maxWhiteRun: i32, - ) -> Result { + ) -> Result { let mut lastRange_z: Option> = None; let mut y: i32 = centerY; let mut x: i32 = centerX; @@ -212,13 +212,13 @@ impl MonochromeRectangleDetector { } } }}else { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } lastRange_z = range; y += deltaY; x += deltaX } - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } /** @@ -354,7 +354,7 @@ pub struct WhiteRectangleDetector { } impl WhiteRectangleDetector { - pub fn new_from_image(image: &BitMatrix) -> Result { + pub fn new_from_image(image: &BitMatrix) -> Result { Self::new( image, INIT_SIZE, @@ -375,7 +375,7 @@ impl WhiteRectangleDetector { initSize: i32, x: i32, y: i32, - ) -> Result { + ) -> Result { let halfsize = initSize / 2; @@ -389,7 +389,7 @@ impl WhiteRectangleDetector { || downInit >= image.getHeight() as i32 || rightInit >= image.getWidth() as i32 { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } Ok(Self{ @@ -417,7 +417,7 @@ impl WhiteRectangleDetector { * leftmost and the third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ - pub fn detect(&self) -> Result, NotFoundException> { + pub fn detect(&self) -> Result, Exceptions> { let mut left: i32 = self.leftInit; let mut right: i32 = self.rightInit; let mut up: i32 = self.upInit; @@ -532,7 +532,7 @@ impl WhiteRectangleDetector { } if z.is_none() { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } let mut t: Option = None; @@ -550,7 +550,7 @@ impl WhiteRectangleDetector { } if t.is_none() { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } let mut x: Option = None; @@ -568,7 +568,7 @@ impl WhiteRectangleDetector { } if x.is_none() { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } let mut y: Option = None; @@ -586,12 +586,12 @@ impl WhiteRectangleDetector { } if y.is_none() { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } return Ok(self.centerEdges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())); } else { - return Err(NotFoundException {}); + return Err(Exceptions::NotFoundException("".to_owned())); } } diff --git a/src/common/mod.rs b/src/common/mod.rs index b682cfa..3859af3 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -6,7 +6,7 @@ use std::cmp; use std::collections::HashMap; use std::fmt; -use crate::exceptions::IllegalArgumentException; +use crate::Exceptions; use crate::DecodeHintType; use crate::RXingResultPoint; use encoding::Encoding; @@ -440,11 +440,11 @@ impl BitArray { * @param start start of range, inclusive. * @param end end of range, exclusive */ - pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), IllegalArgumentException> { + pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { let mut end = end; if end < start || start < 0 || end > self.size { - return Err(IllegalArgumentException::new( - "end < start || start < 0 || end > self.size", + return Err(Exceptions::IllegalArgumentException( + "end < start || start < 0 || end > self.size".to_owned(), )); } if end == start { @@ -489,11 +489,11 @@ impl BitArray { start: usize, end: usize, value: bool, - ) -> Result { + ) -> Result { let mut end = end; if end < start || start < 0 || end > self.size { - return Err(IllegalArgumentException::new( - "end < start || start < 0 || end > self.size", + return Err(Exceptions::IllegalArgumentException( + "end < start || start < 0 || end > self.size".to_owned(), )); } if end == start { @@ -538,10 +538,10 @@ impl BitArray { &mut self, value: u32, numBits: usize, - ) -> Result<(), IllegalArgumentException> { + ) -> Result<(), Exceptions> { if numBits < 0 || numBits > 32 { - return Err(IllegalArgumentException::new( - "Num bits must be between 0 and 32", + return Err(Exceptions::IllegalArgumentException( + "Num bits must be between 0 and 32".to_owned(), )); } let mut nextSize = self.size; @@ -566,9 +566,9 @@ impl BitArray { } } - pub fn xor(&mut self, other: &BitArray) -> Result<(), IllegalArgumentException> { + pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { if self.size != other.size { - return Err(IllegalArgumentException::new("Sizes don't match")); + return Err(Exceptions::IllegalArgumentException("Sizes don't match".to_owned())); } for i in 0..self.bits.len() { //for (int i = 0; i < bits.length; i++) { @@ -785,10 +785,10 @@ impl BitMatrix { * @param width bit matrix width * @param height bit matrix height */ - pub fn new(width: u32, height: u32) -> Result { + pub fn new(width: u32, height: u32) -> Result { if width < 1 || height < 1 { - return Err(IllegalArgumentException::new( - "Both dimensions must be greater than 0", + return Err(Exceptions::IllegalArgumentException( + "Both dimensions must be greater than 0".to_owned(), )); } Ok(Self { @@ -839,7 +839,7 @@ impl BitMatrix { stringRepresentation: &str, setString: &str, unsetString: &str, - ) -> Result { + ) -> Result { // cannot pass nulls in rust // if (stringRepresentation == null) { // throw new IllegalArgumentException(); @@ -862,7 +862,7 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(IllegalArgumentException::new("row lengths do not match")); + return Err(Exceptions::IllegalArgumentException("row lengths do not match".to_owned())); } rowStartPos = bitsPos; nRows += 1; @@ -877,7 +877,7 @@ impl BitMatrix { bits[bitsPos] = false; bitsPos += 1; } else { - return Err(IllegalArgumentException::new(&format!( + return Err(Exceptions::IllegalArgumentException(format!( "illegal character encountered: {}", stringRepresentation[pos..].to_owned() ))); @@ -891,7 +891,7 @@ impl BitMatrix { first_run = false; rowLength = bitsPos - rowStartPos; } else if bitsPos - rowStartPos != rowLength { - return Err(IllegalArgumentException::new("row lengths do not match")); + return Err(Exceptions::IllegalArgumentException("row lengths do not match".to_owned())); } nRows += 1; } @@ -965,10 +965,10 @@ impl BitMatrix { * * @param mask XOR mask */ - pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), IllegalArgumentException> { + pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { if self.width != mask.width || self.height != mask.height || self.rowSize != mask.rowSize { - return Err(IllegalArgumentException::new( - "input matrix dimensions do not match", + return Err(Exceptions::IllegalArgumentException( + "input matrix dimensions do not match".to_owned(), )); } let rowArray = BitArray::with_size(self.width as usize); @@ -1010,22 +1010,22 @@ impl BitMatrix { top: u32, width: u32, height: u32, - ) -> Result<(), IllegalArgumentException> { + ) -> Result<(), Exceptions> { if top < 0 || left < 0 { - return Err(IllegalArgumentException::new( - "Left and top must be nonnegative", + return Err(Exceptions::IllegalArgumentException( + "Left and top must be nonnegative".to_owned(), )); } if height < 1 || width < 1 { - return Err(IllegalArgumentException::new( - "Height and width must be at least 1", + return Err(Exceptions::IllegalArgumentException( + "Height and width must be at least 1".to_owned(), )); } let right = left + width; let bottom = top + height; if bottom > self.height || right > self.width { - return Err(IllegalArgumentException::new( - "The region must fit inside the matrix", + return Err(Exceptions::IllegalArgumentException( + "The region must fit inside the matrix".to_owned(), )); } for y in top..bottom { @@ -1081,7 +1081,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<(), IllegalArgumentException> { + pub fn rotate(&mut self, degrees: u32) -> Result<(), Exceptions> { match degrees % 360 { 0 => Ok(()), 90 => { @@ -1097,8 +1097,8 @@ impl BitMatrix { self.rotate180(); Ok(()) } - _ => Err(IllegalArgumentException::new( - "degrees must be a multiple of 0, 90, 180, or 270", + _ => Err(Exceptions::IllegalArgumentException( + "degrees must be a multiple of 0, 90, 180, or 270".to_owned(), )), } } @@ -1516,9 +1516,9 @@ impl BitSource { * bits of the int * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available */ - pub fn readBits(&mut self, numBits: usize) -> Result { + pub fn readBits(&mut self, numBits: usize) -> Result { if numBits < 1 || numBits > 32 || numBits > self.available() { - return Err(IllegalArgumentException::new(&numBits.to_string())); + return Err(Exceptions::IllegalArgumentException(numBits.to_string())); } let mut result = 0; diff --git a/src/common/reedsolomon/GenericGFPolyTestCase.rs b/src/common/reedsolomon/GenericGFPolyTestCase.rs index 173c01e..fd319ce 100644 --- a/src/common/reedsolomon/GenericGFPolyTestCase.rs +++ b/src/common/reedsolomon/GenericGFPolyTestCase.rs @@ -30,7 +30,7 @@ use super::{GenericGF, GenericGFPoly}; #[test] fn testPolynomialString() { let FIELD = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); - let fz = super::GenericGFPoly::new(FIELD.clone(), &vec![0;0]).unwrap(); + let fz = super::GenericGFPoly::new(FIELD.clone(), &vec![0; 0]).unwrap(); assert_eq!("0", fz.getZero().to_string()); assert_eq!("-1", FIELD.buildMonomial(0, -1).to_string()); @@ -43,7 +43,7 @@ fn testPolynomialString() { #[test] fn testZero() { let FIELD = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); - let fz = super::GenericGFPoly::new(FIELD.clone(), &vec![0;0]).unwrap(); + let fz = super::GenericGFPoly::new(FIELD.clone(), &vec![0; 0]).unwrap(); assert_eq!(fz.getZero(), FIELD.buildMonomial(1, 0)); assert_eq!( diff --git a/src/common/reedsolomon/ReedSolomonTestCase.rs b/src/common/reedsolomon/ReedSolomonTestCase.rs index 251ee26..a42d813 100644 --- a/src/common/reedsolomon/ReedSolomonTestCase.rs +++ b/src/common/reedsolomon/ReedSolomonTestCase.rs @@ -466,7 +466,7 @@ fn testDecoder(field: &GenericGF, dataWords: &Vec, ecWords: &Vec) { // fail only if maxErrors exceeded assert!( i > maxErrors, - "Decode in {} ({},{}) failed at {} errors: {}", + "Decode in {} ({},{}) failed at {} errors: {:#?}", field, dataWords.len(), ecWords.len(), diff --git a/src/common/reedsolomon/mod.rs b/src/common/reedsolomon/mod.rs index 17e279e..a1b3e11 100644 --- a/src/common/reedsolomon/mod.rs +++ b/src/common/reedsolomon/mod.rs @@ -1,6 +1,6 @@ use std::fmt; -use crate::exceptions::*; +use crate::Exceptions; use std::hash::Hash; #[cfg(test)] @@ -8,49 +8,6 @@ mod GenericGFPolyTestCase; #[cfg(test)] mod ReedSolomonTestCase; -/* - * Copyrigh&t 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "&License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing.common.reedsolomon; - -/** - *

Thrown when an exception occurs during Reed-Solomon decoding, such as when - * there are too many errors to correct.

- * - * @author Sean Owen - */ -#[derive(Debug)] -pub struct ReedSolomonException { - message: String, -} - -impl ReedSolomonException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } -} - -impl fmt::Display for ReedSolomonException { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.message) - } -} - /* * Copyright 2007 ZXing authors * @@ -222,9 +179,9 @@ impl GenericGF { /** * @return base 2 log of a in GF(size) */ - pub fn log(&self, a: i32) -> Result { + pub fn log(&self, a: i32) -> Result { if a == 0 { - return Err(IllegalArgumentException::new("")); + return Err(Exceptions::IllegalArgumentException("".to_owned())); } let pos: usize = a.try_into().unwrap(); return Ok(self.logTable[pos]); @@ -233,9 +190,9 @@ impl GenericGF { /** * @return multiplicative inverse of a */ - pub fn inverse(&self, a: i32) -> Result { + pub fn inverse(&self, a: i32) -> Result { if a == 0 { - return Err(ArithmeticException::new("")); + return Err(Exceptions::ArithmeticException("".to_owned())); } let log_t_loc: usize = a.try_into().unwrap(); let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) @@ -327,9 +284,9 @@ impl GenericGFPoly { pub fn new( field: GenericGF, coefficients: &Vec, - ) -> Result { + ) -> Result { if coefficients.len() == 0 { - return Err(IllegalArgumentException::new("")); + return Err(Exceptions::IllegalArgumentException("".to_owned())); } Ok(Self { field: field, @@ -422,10 +379,10 @@ impl GenericGFPoly { pub fn addOrSubtract( &self, other: &GenericGFPoly, - ) -> Result { + ) -> Result { if self.field != other.field { - return Err(IllegalArgumentException::new( - "GenericGFPolys do not have same GenericGF field", + return Err(Exceptions::IllegalArgumentException( + "GenericGFPolys do not have same GenericGF field".to_owned(), )); } if self.isZero() { @@ -463,11 +420,11 @@ impl GenericGFPoly { pub fn multiply( &self, other: &GenericGFPoly, - ) -> Result { + ) -> Result { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(IllegalArgumentException::new( - "GenericGFPolys do not have same GenericGF field", + return Err(Exceptions::IllegalArgumentException( + "GenericGFPolys do not have same GenericGF field".to_owned(), )); } if self.isZero() || other.isZero() { @@ -529,9 +486,9 @@ impl GenericGFPoly { &self, degree: usize, coefficient: i32, - ) -> Result { + ) -> Result { if degree < 0 { - return Err(IllegalArgumentException::new("")); + return Err(Exceptions::IllegalArgumentException("".to_owned())); } if coefficient == 0 { return Ok(self.getZero()); @@ -548,15 +505,15 @@ impl GenericGFPoly { pub fn divide( &self, other: &GenericGFPoly, - ) -> Result, IllegalArgumentException> { + ) -> Result, Exceptions> { if self.field != other.field { //if (!field.equals(other.field)) { - return Err(IllegalArgumentException::new( - "GenericGFPolys do not have same GenericGF field", + return Err(Exceptions::IllegalArgumentException( + "GenericGFPolys do not have same GenericGF field".to_owned(), )); } if other.isZero() { - return Err(IllegalArgumentException::new("Divide by 0")); + return Err(Exceptions::IllegalArgumentException("Divide by 0".to_owned())); } let mut quotient = self.getZero(); @@ -565,7 +522,7 @@ impl GenericGFPoly { let denominatorLeadingTerm = other.getCoefficient(other.getDegree()); let inverseDenominatorLeadingTerm = match self.field.inverse(denominatorLeadingTerm) { Ok(val) => val, - Err(issue) => return Err(IllegalArgumentException::new("arithmetic issue")), + Err(issue) => return Err(Exceptions::IllegalArgumentException("arithmetic issue".to_owned())), }; while remainder.getDegree() >= other.getDegree() && !remainder.isZero() { @@ -690,7 +647,7 @@ impl ReedSolomonDecoder { * @param twoS number of error-correction codewords available * @throws ReedSolomonException if decoding fails for any reason */ - pub fn decode(&self, received: &mut Vec, twoS: i32) -> Result<(), ReedSolomonException> { + pub fn decode(&self, received: &mut Vec, twoS: i32) -> Result<(), Exceptions> { let poly = GenericGFPoly::new(self.field.clone(), received).unwrap(); let mut syndromeCoefficients = Vec::with_capacity(twoS.try_into().unwrap()); let mut noError = true; @@ -713,7 +670,7 @@ impl ReedSolomonDecoder { } let syndrome = match GenericGFPoly::new(self.field.clone(), &syndromeCoefficients) { Ok(res) => res, - Err(fail) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(fail) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }; let sigmaOmega = self.runEuclideanAlgorithm( &self.field.buildMonomial(twoS.try_into().unwrap(), 1), @@ -730,10 +687,10 @@ impl ReedSolomonDecoder { - 1 - match self.field.log(errorLocations[i].try_into().unwrap()) { Ok(size) => size as usize, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }; if position < 0 { - return Err(ReedSolomonException::new("Bad error location")); + return Err(Exceptions::ReedSolomonException("Bad error location".to_owned())); } received[position] = GenericGF::addOrSubtract(received[position], errorMagnitudes[i]); } @@ -745,7 +702,7 @@ impl ReedSolomonDecoder { a: &GenericGFPoly, b: &GenericGFPoly, R: usize, - ) -> Result, ReedSolomonException> { + ) -> Result, Exceptions> { // Assume a's degree is >= b's let mut a = a.clone(); let mut b = b.clone(); @@ -772,14 +729,14 @@ impl ReedSolomonDecoder { // Divide rLastLast by rLast, with quotient in q and remainder in r if rLast.isZero() { // Oops, Euclidean algorithm already terminated? - return Err(ReedSolomonException::new("r_{i-1} was zero")); + return Err(Exceptions::ReedSolomonException("r_{i-1} was zero".to_owned())); } r = rLastLast; let mut q = r.getZero(); let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); let dltInverse = match self.field.inverse(denominatorLeadingTerm) { Ok(inv) => inv, - Err(err) => return Err(ReedSolomonException::new("ArithmetricException")), + Err(err) => return Err(Exceptions::ReedSolomonException("ArithmetricException".to_owned())), }; while r.getDegree() >= rLast.getDegree() && !r.isZero() { let degreeDiff = r.getDegree() - rLast.getDegree(); @@ -788,29 +745,29 @@ impl ReedSolomonDecoder { .multiply(r.getCoefficient(r.getDegree()), dltInverse); q = match q.addOrSubtract(&self.field.buildMonomial(degreeDiff, scale)) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }; r = match r.addOrSubtract(&match rLast.multiplyByMonomial(degreeDiff, scale) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }; } t = match (match q.multiply(&tLast) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }) .addOrSubtract(&tLastLast) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), + Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())), }; if r.getDegree() >= rLast.getDegree() { - return Err(ReedSolomonException::new(&format!( + return Err(Exceptions::ReedSolomonException(format!( "Division algorithm failed to reduce polynomial? r: {}, rLast: {}", r, rLast ))); @@ -819,12 +776,12 @@ impl ReedSolomonDecoder { let sigmaTildeAtZero = t.getCoefficient(0); if sigmaTildeAtZero == 0 { - return Err(ReedSolomonException::new("sigmaTilde(0) was zero")); + return Err(Exceptions::ReedSolomonException("sigmaTilde(0) was zero".to_owned())); } let inverse = match self.field.inverse(sigmaTildeAtZero) { Ok(res) => res, - Err(err) => return Err(ReedSolomonException::new("ArithmetricException")), + Err(err) => return Err(Exceptions::ReedSolomonException("ArithmetricException".to_owned())), }; let sigma = t.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse); @@ -834,7 +791,7 @@ impl ReedSolomonDecoder { fn findErrorLocations( &self, errorLocator: &GenericGFPoly, - ) -> Result, ReedSolomonException> { + ) -> Result, Exceptions> { // This is a direct application of Chien's search let numErrors = errorLocator.getDegree(); if numErrors == 1 { @@ -852,14 +809,14 @@ impl ReedSolomonDecoder { if errorLocator.evaluateAt(i) == 0 { result[e] = match self.field.inverse(i.try_into().unwrap()) { Ok(res) => res.try_into().unwrap(), - Err(err) => return Err(ReedSolomonException::new("ArithmetricException")), + Err(err) => return Err(Exceptions::ReedSolomonException("ArithmetricException".to_owned())), }; e += 1; } } if e != numErrors { - return Err(ReedSolomonException::new( - "Error locator degree does not match number of roots", + return Err(Exceptions::ReedSolomonException( + "Error locator degree does not match number of roots".to_owned(), )); } return Ok(result); @@ -985,13 +942,13 @@ impl ReedSolomonEncoder { &mut self, toEncode: &mut Vec, ecBytes: usize, - ) -> Result<(), IllegalArgumentException> { + ) -> Result<(), Exceptions> { if ecBytes == 0 { - return Err(IllegalArgumentException::new("No error correction bytes")); + return Err(Exceptions::IllegalArgumentException("No error correction bytes".to_owned())); } let dataBytes = toEncode.len() - ecBytes; if dataBytes <= 0 { - return Err(IllegalArgumentException::new("No data bytes provided")); + return Err(Exceptions::IllegalArgumentException("No data bytes provided".to_owned())); } let fld = self.field.clone(); let generator = self.buildGenerator(ecBytes); diff --git a/src/exceptions.rs b/src/exceptions.rs index 55d4acf..f194ecb 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -1,195 +1,16 @@ -#[derive(Debug)] -pub struct IllegalArgumentException { - message: String, -} -impl IllegalArgumentException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } -} -#[derive(Debug)] -pub struct UnsupportedOperationException { - message: String, -} -impl UnsupportedOperationException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } -} +use std::fmt; #[derive(Debug)] -pub struct IllegalStateException { - message: String, -} -impl IllegalStateException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } -} - -#[derive(Debug)] -pub struct ArithmeticException { - message: String, -} -impl ArithmeticException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } -} - - - -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing; - -/** - * Thrown when a barcode was not found in the image. It might have been - * partially detected but could not be confirmed. - * - * @author Sean Owen - */ -#[derive(Debug)] -pub struct NotFoundException; - -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing; - -/** - * Thrown when a barcode was successfully detected, but some aspect of - * the content did not conform to the barcode's format rules. This could have - * been due to a mis-detection. - * - * @author Sean Owen - */ -#[derive(Debug)] -pub struct FormatException; - -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing; - -/** - * Thrown when a barcode was successfully detected and decoded, but - * was not returned because its checksum feature failed. - * - * @author Sean Owen - */ -#[derive(Debug)] -pub struct ChecksumException; - -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing; - -/** - * The general exception class throw when something goes wrong during decoding of a barcode. - * This includes, but is not limited to, failing checksums / error correction algorithms, being - * unable to locate finder timing patterns, and so on. - * - * @author Sean Owen - */ -#[derive(Debug)] -pub struct ReaderException; - -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//package com.google.zxing; - -/** - * A base class which covers the range of exceptions which may occur when encoding a barcode using - * the Writer framework. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -#[derive(Debug)] -pub struct WriterException { - message: String, -} - -impl WriterException { - pub fn new(message: &str) -> Self { - Self { - message: message.to_owned(), - } - } +pub enum Exceptions { + IllegalArgumentException(String), + UnsupportedOperationException(String), + IllegalStateException(String), + ArithmeticException(String), + NotFoundException(String), + FormatException(String), + ChecksumException(String), + ReaderException(String), + WriterException(String), + ReedSolomonException(String), + ReaderDecodeException() } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index de37a5b..ce26982 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -423,7 +423,7 @@ pub trait Writer { format: &BarcodeFormat, width: i32, height: i32, - ) -> Result; + ) -> Result; /** * @param contents The contents to encode in the barcode @@ -440,7 +440,7 @@ pub trait Writer { width: i32, height: i32, hints: HashMap, - ) -> Result; + ) -> Result; } /* @@ -461,11 +461,7 @@ pub trait Writer { //package com.google.zxing; -pub enum ReaderDecodeException { - NotFoundException(NotFoundException), - ChecksumException(ChecksumException), - FormatException(FormatException), -} + /** * Implementations of this interface can decode an image of a barcode in some format into @@ -489,7 +485,7 @@ pub trait Reader { * @throws ChecksumException if a potential barcode is found but does not pass its checksum * @throws FormatException if a potential barcode is found but format is invalid */ - fn decode(image: BinaryBitmap) -> Result; + fn decode(image: BinaryBitmap) -> Result; /** * Locates and decodes a barcode in some format within an image. This method also accepts @@ -508,7 +504,7 @@ pub trait Reader { fn decode_with_hints( image: BinaryBitmap, hints: HashMap, - ) -> Result; + ) -> Result; /** * Resets any internal state the implementation has after a decode, to prepare it @@ -964,9 +960,9 @@ pub struct Dimension { } impl Dimension { - pub fn new(width: usize, height: usize) -> Result { + pub fn new(width: usize, height: usize) -> Result { if width < 0 || height < 0 { - return Err(IllegalArgumentException::new("")); + return Err(Exceptions::IllegalArgumentException("".to_owned())); } Ok(Self { width, height }) } @@ -1032,7 +1028,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, row: BitArray) -> Result; + fn getBlackRow(&self, y: usize, row: BitArray) -> Result; /** * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive @@ -1043,7 +1039,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; + fn getBlackMatrix(&self) -> Result; /** * Creates a new object with the same type as this Binarizer implementation, but with pristine @@ -1122,7 +1118,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, row: BitArray) -> Result { + pub fn getBlackRow(&self, y: usize, row: BitArray) -> Result { return self.binarizer.getBlackRow(y, row); } @@ -1135,7 +1131,7 @@ impl BinaryBitmap { * @return The 2D array of bits for the image (true means black). * @throws NotFoundException if image can't be binarized to make a matrix */ - pub fn getBlackMatrix(&self) -> Result<&BitMatrix, NotFoundException> { + pub fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> { // The matrix is created on demand the first time it is requested, then cached. There are two // reasons for this: // 1. This work will never be done if the caller only installs 1D Reader objects, or if a @@ -1338,9 +1334,9 @@ pub trait LuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, UnsupportedOperationException> { - return Err(UnsupportedOperationException::new( - "This luminance source does not support cropping.", + ) -> Result, Exceptions> { + return Err(Exceptions::UnsupportedOperationException( + "This luminance source does not support cropping.".to_owned(), )); } @@ -1367,9 +1363,9 @@ pub trait LuminanceSource { */ fn rotateCounterClockwise( &self, - ) -> Result, UnsupportedOperationException> { - return Err(UnsupportedOperationException::new( - "This luminance source does not support rotation by 90 degrees.", + ) -> Result, Exceptions> { + return Err(Exceptions::UnsupportedOperationException( + "This luminance source does not support rotation by 90 degrees.".to_owned(), )); } @@ -1381,9 +1377,9 @@ pub trait LuminanceSource { */ fn rotateCounterClockwise45( &self, - ) -> Result, UnsupportedOperationException> { - return Err(UnsupportedOperationException::new( - "This luminance source does not support rotation by 45 degrees.", + ) -> Result, Exceptions> { + return Err(Exceptions::UnsupportedOperationException( + "This luminance source does not support rotation by 45 degrees.".to_owned(), )); } @@ -1586,10 +1582,10 @@ impl PlanarYUVLuminanceSource { height: usize, reverseHorizontal: bool, inverted: bool, - ) -> Result { + ) -> Result { if left + width > dataWidth || top + height > dataHeight { - return Err(IllegalArgumentException::new( - "Crop rectangle does not fit within image data.", + return Err(Exceptions::IllegalArgumentException( + "Crop rectangle does not fit within image data.".to_owned(), )); } @@ -1753,7 +1749,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, UnsupportedOperationException> { + ) -> Result, Exceptions> { match PlanarYUVLuminanceSource::new_with_all( self.yuvData.clone(), self.dataWidth, @@ -1766,7 +1762,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource { self.invert, ) { Ok(new) => Ok(Box::new(new)), - Err(err) => Err(UnsupportedOperationException::new("")), + Err(err) => Err(Exceptions::UnsupportedOperationException("".to_owned())), } } @@ -1894,7 +1890,7 @@ impl LuminanceSource for RGBLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result, UnsupportedOperationException> { + ) -> Result, Exceptions> { match RGBLuminanceSource::new_complex( &self.luminances, self.dataWidth, @@ -1905,7 +1901,7 @@ impl LuminanceSource for RGBLuminanceSource { height, ) { Ok(crop) => Ok(Box::new(crop)), - Err(error) => Err(UnsupportedOperationException::new("")), + Err(error) => Err(Exceptions::UnsupportedOperationException("".to_owned())), } } @@ -1958,10 +1954,10 @@ impl RGBLuminanceSource { top: usize, width: usize, height: usize, - ) -> Result { - if (left + width > dataWidth || top + height > dataHeight) { - return Err(IllegalArgumentException::new( - "Crop rectangle does not fit within image data.", + ) -> Result { + if left + width > dataWidth || top + height > dataHeight { + return Err(Exceptions::IllegalArgumentException( + "Crop rectangle does not fit within image data.".to_owned(), )); } Ok(Self {