enum exceptions

This commit is contained in:
Henry
2022-08-28 18:31:21 -05:00
parent d375f112a1
commit 5ce1a89abe
12 changed files with 137 additions and 363 deletions

View File

@@ -1,6 +1,6 @@
pub mod MathUtils; pub mod MathUtils;
use crate::common::BitMatrix; use crate::common::BitMatrix;
use crate::{NotFoundException, RXingResultPoint}; use crate::{Exceptions, RXingResultPoint};
/* /*
* Copyright 2009 ZXing authors * Copyright 2009 ZXing authors
@@ -49,7 +49,7 @@ impl MonochromeRectangleDetector {
* third, the rightmost * third, the rightmost
* @throws NotFoundException if no Data Matrix Code can be found * @throws NotFoundException if no Data Matrix Code can be found
*/ */
pub fn detect(&self) -> Result<Vec<RXingResultPoint>, NotFoundException> { pub fn detect(&self) -> Result<Vec<RXingResultPoint>, Exceptions> {
let height = self.image.getHeight() as i32; let height = self.image.getHeight() as i32;
let width = self.image.getWidth() as i32; let width = self.image.getWidth() as i32;
let halfHeight= height / 2; let halfHeight= height / 2;
@@ -155,7 +155,7 @@ impl MonochromeRectangleDetector {
top: i32, top: i32,
bottom: i32, bottom: i32,
maxWhiteRun: i32, maxWhiteRun: i32,
) -> Result<RXingResultPoint, NotFoundException> { ) -> Result<RXingResultPoint, Exceptions> {
let mut lastRange_z: Option<Vec<i32>> = None; let mut lastRange_z: Option<Vec<i32>> = None;
let mut y: i32 = centerY; let mut y: i32 = centerY;
let mut x: i32 = centerX; let mut x: i32 = centerX;
@@ -212,13 +212,13 @@ impl MonochromeRectangleDetector {
} }
} }
}}else { }}else {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
lastRange_z = range; lastRange_z = range;
y += deltaY; y += deltaY;
x += deltaX x += deltaX
} }
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
/** /**
@@ -354,7 +354,7 @@ pub struct WhiteRectangleDetector {
} }
impl WhiteRectangleDetector { impl WhiteRectangleDetector {
pub fn new_from_image(image: &BitMatrix) -> Result<Self, NotFoundException> { pub fn new_from_image(image: &BitMatrix) -> Result<Self, Exceptions> {
Self::new( Self::new(
image, image,
INIT_SIZE, INIT_SIZE,
@@ -375,7 +375,7 @@ impl WhiteRectangleDetector {
initSize: i32, initSize: i32,
x: i32, x: i32,
y: i32, y: i32,
) -> Result<Self, NotFoundException> { ) -> Result<Self, Exceptions> {
let halfsize = initSize / 2; let halfsize = initSize / 2;
@@ -389,7 +389,7 @@ impl WhiteRectangleDetector {
|| downInit >= image.getHeight() as i32 || downInit >= image.getHeight() as i32
|| rightInit >= image.getWidth() as i32 || rightInit >= image.getWidth() as i32
{ {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
Ok(Self{ Ok(Self{
@@ -417,7 +417,7 @@ impl WhiteRectangleDetector {
* leftmost and the third, the rightmost * leftmost and the third, the rightmost
* @throws NotFoundException if no Data Matrix Code can be found * @throws NotFoundException if no Data Matrix Code can be found
*/ */
pub fn detect(&self) -> Result<Vec<RXingResultPoint>, NotFoundException> { pub fn detect(&self) -> Result<Vec<RXingResultPoint>, Exceptions> {
let mut left: i32 = self.leftInit; let mut left: i32 = self.leftInit;
let mut right: i32 = self.rightInit; let mut right: i32 = self.rightInit;
let mut up: i32 = self.upInit; let mut up: i32 = self.upInit;
@@ -532,7 +532,7 @@ impl WhiteRectangleDetector {
} }
if z.is_none() { if z.is_none() {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
let mut t: Option<RXingResultPoint> = None; let mut t: Option<RXingResultPoint> = None;
@@ -550,7 +550,7 @@ impl WhiteRectangleDetector {
} }
if t.is_none() { if t.is_none() {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
let mut x: Option<RXingResultPoint> = None; let mut x: Option<RXingResultPoint> = None;
@@ -568,7 +568,7 @@ impl WhiteRectangleDetector {
} }
if x.is_none() { if x.is_none() {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
let mut y: Option<RXingResultPoint> = None; let mut y: Option<RXingResultPoint> = None;
@@ -586,12 +586,12 @@ impl WhiteRectangleDetector {
} }
if y.is_none() { 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())); return Ok(self.centerEdges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap()));
} else { } else {
return Err(NotFoundException {}); return Err(Exceptions::NotFoundException("".to_owned()));
} }
} }

View File

@@ -6,7 +6,7 @@ use std::cmp;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use crate::exceptions::IllegalArgumentException; use crate::Exceptions;
use crate::DecodeHintType; use crate::DecodeHintType;
use crate::RXingResultPoint; use crate::RXingResultPoint;
use encoding::Encoding; use encoding::Encoding;
@@ -440,11 +440,11 @@ impl BitArray {
* @param start start of range, inclusive. * @param start start of range, inclusive.
* @param end end of range, exclusive * @param end end of range, exclusive
*/ */
pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), IllegalArgumentException> { pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> {
let mut end = end; let mut end = end;
if end < start || start < 0 || end > self.size { if end < start || start < 0 || end > self.size {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"end < start || start < 0 || end > self.size", "end < start || start < 0 || end > self.size".to_owned(),
)); ));
} }
if end == start { if end == start {
@@ -489,11 +489,11 @@ impl BitArray {
start: usize, start: usize,
end: usize, end: usize,
value: bool, value: bool,
) -> Result<bool, IllegalArgumentException> { ) -> Result<bool, Exceptions> {
let mut end = end; let mut end = end;
if end < start || start < 0 || end > self.size { if end < start || start < 0 || end > self.size {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"end < start || start < 0 || end > self.size", "end < start || start < 0 || end > self.size".to_owned(),
)); ));
} }
if end == start { if end == start {
@@ -538,10 +538,10 @@ impl BitArray {
&mut self, &mut self,
value: u32, value: u32,
numBits: usize, numBits: usize,
) -> Result<(), IllegalArgumentException> { ) -> Result<(), Exceptions> {
if numBits < 0 || numBits > 32 { if numBits < 0 || numBits > 32 {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Num bits must be between 0 and 32", "Num bits must be between 0 and 32".to_owned(),
)); ));
} }
let mut nextSize = self.size; 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 { 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 i in 0..self.bits.len() {
//for (int i = 0; i < bits.length; i++) { //for (int i = 0; i < bits.length; i++) {
@@ -785,10 +785,10 @@ impl BitMatrix {
* @param width bit matrix width * @param width bit matrix width
* @param height bit matrix height * @param height bit matrix height
*/ */
pub fn new(width: u32, height: u32) -> Result<Self, IllegalArgumentException> { pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> {
if width < 1 || height < 1 { if width < 1 || height < 1 {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Both dimensions must be greater than 0", "Both dimensions must be greater than 0".to_owned(),
)); ));
} }
Ok(Self { Ok(Self {
@@ -839,7 +839,7 @@ impl BitMatrix {
stringRepresentation: &str, stringRepresentation: &str,
setString: &str, setString: &str,
unsetString: &str, unsetString: &str,
) -> Result<Self, IllegalArgumentException> { ) -> Result<Self, Exceptions> {
// cannot pass nulls in rust // cannot pass nulls in rust
// if (stringRepresentation == null) { // if (stringRepresentation == null) {
// throw new IllegalArgumentException(); // throw new IllegalArgumentException();
@@ -862,7 +862,7 @@ impl BitMatrix {
first_run = false; first_run = false;
rowLength = bitsPos - rowStartPos; rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength { } 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; rowStartPos = bitsPos;
nRows += 1; nRows += 1;
@@ -877,7 +877,7 @@ impl BitMatrix {
bits[bitsPos] = false; bits[bitsPos] = false;
bitsPos += 1; bitsPos += 1;
} else { } else {
return Err(IllegalArgumentException::new(&format!( return Err(Exceptions::IllegalArgumentException(format!(
"illegal character encountered: {}", "illegal character encountered: {}",
stringRepresentation[pos..].to_owned() stringRepresentation[pos..].to_owned()
))); )));
@@ -891,7 +891,7 @@ impl BitMatrix {
first_run = false; first_run = false;
rowLength = bitsPos - rowStartPos; rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength { } 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; nRows += 1;
} }
@@ -965,10 +965,10 @@ impl BitMatrix {
* *
* @param mask XOR mask * @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 { if self.width != mask.width || self.height != mask.height || self.rowSize != mask.rowSize {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"input matrix dimensions do not match", "input matrix dimensions do not match".to_owned(),
)); ));
} }
let rowArray = BitArray::with_size(self.width as usize); let rowArray = BitArray::with_size(self.width as usize);
@@ -1010,22 +1010,22 @@ impl BitMatrix {
top: u32, top: u32,
width: u32, width: u32,
height: u32, height: u32,
) -> Result<(), IllegalArgumentException> { ) -> Result<(), Exceptions> {
if top < 0 || left < 0 { if top < 0 || left < 0 {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Left and top must be nonnegative", "Left and top must be nonnegative".to_owned(),
)); ));
} }
if height < 1 || width < 1 { if height < 1 || width < 1 {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Height and width must be at least 1", "Height and width must be at least 1".to_owned(),
)); ));
} }
let right = left + width; let right = left + width;
let bottom = top + height; let bottom = top + height;
if bottom > self.height || right > self.width { if bottom > self.height || right > self.width {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"The region must fit inside the matrix", "The region must fit inside the matrix".to_owned(),
)); ));
} }
for y in top..bottom { 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) * @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 { match degrees % 360 {
0 => Ok(()), 0 => Ok(()),
90 => { 90 => {
@@ -1097,8 +1097,8 @@ impl BitMatrix {
self.rotate180(); self.rotate180();
Ok(()) Ok(())
} }
_ => Err(IllegalArgumentException::new( _ => Err(Exceptions::IllegalArgumentException(
"degrees must be a multiple of 0, 90, 180, or 270", "degrees must be a multiple of 0, 90, 180, or 270".to_owned(),
)), )),
} }
} }
@@ -1516,9 +1516,9 @@ impl BitSource {
* bits of the int * bits of the int
* @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
*/ */
pub fn readBits(&mut self, numBits: usize) -> Result<u32, IllegalArgumentException> { pub fn readBits(&mut self, numBits: usize) -> Result<u32, Exceptions> {
if numBits < 1 || numBits > 32 || numBits > self.available() { 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; let mut result = 0;

View File

@@ -30,7 +30,7 @@ use super::{GenericGF, GenericGFPoly};
#[test] #[test]
fn testPolynomialString() { fn testPolynomialString() {
let FIELD = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); 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!("0", fz.getZero().to_string());
assert_eq!("-1", FIELD.buildMonomial(0, -1).to_string()); assert_eq!("-1", FIELD.buildMonomial(0, -1).to_string());
@@ -43,7 +43,7 @@ fn testPolynomialString() {
#[test] #[test]
fn testZero() { fn testZero() {
let FIELD = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); 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!(fz.getZero(), FIELD.buildMonomial(1, 0));
assert_eq!( assert_eq!(

View File

@@ -466,7 +466,7 @@ fn testDecoder(field: &GenericGF, dataWords: &Vec<i32>, ecWords: &Vec<i32>) {
// fail only if maxErrors exceeded // fail only if maxErrors exceeded
assert!( assert!(
i > maxErrors, i > maxErrors,
"Decode in {} ({},{}) failed at {} errors: {}", "Decode in {} ({},{}) failed at {} errors: {:#?}",
field, field,
dataWords.len(), dataWords.len(),
ecWords.len(), ecWords.len(),

View File

@@ -1,6 +1,6 @@
use std::fmt; use std::fmt;
use crate::exceptions::*; use crate::Exceptions;
use std::hash::Hash; use std::hash::Hash;
#[cfg(test)] #[cfg(test)]
@@ -8,49 +8,6 @@ mod GenericGFPolyTestCase;
#[cfg(test)] #[cfg(test)]
mod ReedSolomonTestCase; 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;
/**
* <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when
* there are too many errors to correct.</p>
*
* @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 * Copyright 2007 ZXing authors
* *
@@ -222,9 +179,9 @@ impl GenericGF {
/** /**
* @return base 2 log of a in GF(size) * @return base 2 log of a in GF(size)
*/ */
pub fn log(&self, a: i32) -> Result<i32, IllegalArgumentException> { pub fn log(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 { if a == 0 {
return Err(IllegalArgumentException::new("")); return Err(Exceptions::IllegalArgumentException("".to_owned()));
} }
let pos: usize = a.try_into().unwrap(); let pos: usize = a.try_into().unwrap();
return Ok(self.logTable[pos]); return Ok(self.logTable[pos]);
@@ -233,9 +190,9 @@ impl GenericGF {
/** /**
* @return multiplicative inverse of a * @return multiplicative inverse of a
*/ */
pub fn inverse(&self, a: i32) -> Result<i32, ArithmeticException> { pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 { if a == 0 {
return Err(ArithmeticException::new("")); return Err(Exceptions::ArithmeticException("".to_owned()));
} }
let log_t_loc: usize = a.try_into().unwrap(); let log_t_loc: usize = a.try_into().unwrap();
let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1)
@@ -327,9 +284,9 @@ impl GenericGFPoly {
pub fn new( pub fn new(
field: GenericGF, field: GenericGF,
coefficients: &Vec<i32>, coefficients: &Vec<i32>,
) -> Result<Self, IllegalArgumentException> { ) -> Result<Self, Exceptions> {
if coefficients.len() == 0 { if coefficients.len() == 0 {
return Err(IllegalArgumentException::new("")); return Err(Exceptions::IllegalArgumentException("".to_owned()));
} }
Ok(Self { Ok(Self {
field: field, field: field,
@@ -422,10 +379,10 @@ impl GenericGFPoly {
pub fn addOrSubtract( pub fn addOrSubtract(
&self, &self,
other: &GenericGFPoly, other: &GenericGFPoly,
) -> Result<GenericGFPoly, IllegalArgumentException> { ) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field { if self.field != other.field {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"GenericGFPolys do not have same GenericGF field", "GenericGFPolys do not have same GenericGF field".to_owned(),
)); ));
} }
if self.isZero() { if self.isZero() {
@@ -463,11 +420,11 @@ impl GenericGFPoly {
pub fn multiply( pub fn multiply(
&self, &self,
other: &GenericGFPoly, other: &GenericGFPoly,
) -> Result<GenericGFPoly, IllegalArgumentException> { ) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field { if self.field != other.field {
//if (!field.equals(other.field)) { //if (!field.equals(other.field)) {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"GenericGFPolys do not have same GenericGF field", "GenericGFPolys do not have same GenericGF field".to_owned(),
)); ));
} }
if self.isZero() || other.isZero() { if self.isZero() || other.isZero() {
@@ -529,9 +486,9 @@ impl GenericGFPoly {
&self, &self,
degree: usize, degree: usize,
coefficient: i32, coefficient: i32,
) -> Result<GenericGFPoly, IllegalArgumentException> { ) -> Result<GenericGFPoly, Exceptions> {
if degree < 0 { if degree < 0 {
return Err(IllegalArgumentException::new("")); return Err(Exceptions::IllegalArgumentException("".to_owned()));
} }
if coefficient == 0 { if coefficient == 0 {
return Ok(self.getZero()); return Ok(self.getZero());
@@ -548,15 +505,15 @@ impl GenericGFPoly {
pub fn divide( pub fn divide(
&self, &self,
other: &GenericGFPoly, other: &GenericGFPoly,
) -> Result<Vec<GenericGFPoly>, IllegalArgumentException> { ) -> Result<Vec<GenericGFPoly>, Exceptions> {
if self.field != other.field { if self.field != other.field {
//if (!field.equals(other.field)) { //if (!field.equals(other.field)) {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"GenericGFPolys do not have same GenericGF field", "GenericGFPolys do not have same GenericGF field".to_owned(),
)); ));
} }
if other.isZero() { if other.isZero() {
return Err(IllegalArgumentException::new("Divide by 0")); return Err(Exceptions::IllegalArgumentException("Divide by 0".to_owned()));
} }
let mut quotient = self.getZero(); let mut quotient = self.getZero();
@@ -565,7 +522,7 @@ impl GenericGFPoly {
let denominatorLeadingTerm = other.getCoefficient(other.getDegree()); let denominatorLeadingTerm = other.getCoefficient(other.getDegree());
let inverseDenominatorLeadingTerm = match self.field.inverse(denominatorLeadingTerm) { let inverseDenominatorLeadingTerm = match self.field.inverse(denominatorLeadingTerm) {
Ok(val) => val, 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() { while remainder.getDegree() >= other.getDegree() && !remainder.isZero() {
@@ -690,7 +647,7 @@ impl ReedSolomonDecoder {
* @param twoS number of error-correction codewords available * @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason * @throws ReedSolomonException if decoding fails for any reason
*/ */
pub fn decode(&self, received: &mut Vec<i32>, twoS: i32) -> Result<(), ReedSolomonException> { pub fn decode(&self, received: &mut Vec<i32>, twoS: i32) -> Result<(), Exceptions> {
let poly = GenericGFPoly::new(self.field.clone(), received).unwrap(); let poly = GenericGFPoly::new(self.field.clone(), received).unwrap();
let mut syndromeCoefficients = Vec::with_capacity(twoS.try_into().unwrap()); let mut syndromeCoefficients = Vec::with_capacity(twoS.try_into().unwrap());
let mut noError = true; let mut noError = true;
@@ -713,7 +670,7 @@ impl ReedSolomonDecoder {
} }
let syndrome = match GenericGFPoly::new(self.field.clone(), &syndromeCoefficients) { let syndrome = match GenericGFPoly::new(self.field.clone(), &syndromeCoefficients) {
Ok(res) => res, Ok(res) => res,
Err(fail) => return Err(ReedSolomonException::new("IllegalArgumentException")), Err(fail) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())),
}; };
let sigmaOmega = self.runEuclideanAlgorithm( let sigmaOmega = self.runEuclideanAlgorithm(
&self.field.buildMonomial(twoS.try_into().unwrap(), 1), &self.field.buildMonomial(twoS.try_into().unwrap(), 1),
@@ -730,10 +687,10 @@ impl ReedSolomonDecoder {
- 1 - 1
- match self.field.log(errorLocations[i].try_into().unwrap()) { - match self.field.log(errorLocations[i].try_into().unwrap()) {
Ok(size) => size as usize, Ok(size) => size as usize,
Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())),
}; };
if position < 0 { 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]); received[position] = GenericGF::addOrSubtract(received[position], errorMagnitudes[i]);
} }
@@ -745,7 +702,7 @@ impl ReedSolomonDecoder {
a: &GenericGFPoly, a: &GenericGFPoly,
b: &GenericGFPoly, b: &GenericGFPoly,
R: usize, R: usize,
) -> Result<Vec<GenericGFPoly>, ReedSolomonException> { ) -> Result<Vec<GenericGFPoly>, Exceptions> {
// Assume a's degree is >= b's // Assume a's degree is >= b's
let mut a = a.clone(); let mut a = a.clone();
let mut b = b.clone(); let mut b = b.clone();
@@ -772,14 +729,14 @@ impl ReedSolomonDecoder {
// Divide rLastLast by rLast, with quotient in q and remainder in r // Divide rLastLast by rLast, with quotient in q and remainder in r
if rLast.isZero() { if rLast.isZero() {
// Oops, Euclidean algorithm already terminated? // 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; r = rLastLast;
let mut q = r.getZero(); let mut q = r.getZero();
let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
let dltInverse = match self.field.inverse(denominatorLeadingTerm) { let dltInverse = match self.field.inverse(denominatorLeadingTerm) {
Ok(inv) => inv, 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() { while r.getDegree() >= rLast.getDegree() && !r.isZero() {
let degreeDiff = r.getDegree() - rLast.getDegree(); let degreeDiff = r.getDegree() - rLast.getDegree();
@@ -788,29 +745,29 @@ impl ReedSolomonDecoder {
.multiply(r.getCoefficient(r.getDegree()), dltInverse); .multiply(r.getCoefficient(r.getDegree()), dltInverse);
q = match q.addOrSubtract(&self.field.buildMonomial(degreeDiff, scale)) { q = match q.addOrSubtract(&self.field.buildMonomial(degreeDiff, scale)) {
Ok(res) => res, 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) { r = match r.addOrSubtract(&match rLast.multiplyByMonomial(degreeDiff, scale) {
Ok(res) => res, Ok(res) => res,
Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())),
}) { }) {
Ok(res) => res, 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) { t = match (match q.multiply(&tLast) {
Ok(res) => res, Ok(res) => res,
Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())),
}) })
.addOrSubtract(&tLastLast) .addOrSubtract(&tLastLast)
{ {
Ok(res) => res, Ok(res) => res,
Err(err) => return Err(ReedSolomonException::new("IllegalArgumentException")), Err(err) => return Err(Exceptions::ReedSolomonException("IllegalArgumentException".to_owned())),
}; };
if r.getDegree() >= rLast.getDegree() { if r.getDegree() >= rLast.getDegree() {
return Err(ReedSolomonException::new(&format!( return Err(Exceptions::ReedSolomonException(format!(
"Division algorithm failed to reduce polynomial? r: {}, rLast: {}", "Division algorithm failed to reduce polynomial? r: {}, rLast: {}",
r, rLast r, rLast
))); )));
@@ -819,12 +776,12 @@ impl ReedSolomonDecoder {
let sigmaTildeAtZero = t.getCoefficient(0); let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 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) { let inverse = match self.field.inverse(sigmaTildeAtZero) {
Ok(res) => res, 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 sigma = t.multiply_with_scalar(inverse);
let omega = r.multiply_with_scalar(inverse); let omega = r.multiply_with_scalar(inverse);
@@ -834,7 +791,7 @@ impl ReedSolomonDecoder {
fn findErrorLocations( fn findErrorLocations(
&self, &self,
errorLocator: &GenericGFPoly, errorLocator: &GenericGFPoly,
) -> Result<Vec<usize>, ReedSolomonException> { ) -> Result<Vec<usize>, Exceptions> {
// This is a direct application of Chien's search // This is a direct application of Chien's search
let numErrors = errorLocator.getDegree(); let numErrors = errorLocator.getDegree();
if numErrors == 1 { if numErrors == 1 {
@@ -852,14 +809,14 @@ impl ReedSolomonDecoder {
if errorLocator.evaluateAt(i) == 0 { if errorLocator.evaluateAt(i) == 0 {
result[e] = match self.field.inverse(i.try_into().unwrap()) { result[e] = match self.field.inverse(i.try_into().unwrap()) {
Ok(res) => res.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; e += 1;
} }
} }
if e != numErrors { if e != numErrors {
return Err(ReedSolomonException::new( return Err(Exceptions::ReedSolomonException(
"Error locator degree does not match number of roots", "Error locator degree does not match number of roots".to_owned(),
)); ));
} }
return Ok(result); return Ok(result);
@@ -985,13 +942,13 @@ impl ReedSolomonEncoder {
&mut self, &mut self,
toEncode: &mut Vec<i32>, toEncode: &mut Vec<i32>,
ecBytes: usize, ecBytes: usize,
) -> Result<(), IllegalArgumentException> { ) -> Result<(), Exceptions> {
if ecBytes == 0 { 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; let dataBytes = toEncode.len() - ecBytes;
if dataBytes <= 0 { 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 fld = self.field.clone();
let generator = self.buildGenerator(ecBytes); let generator = self.buildGenerator(ecBytes);

View File

@@ -1,195 +1,16 @@
#[derive(Debug)] use std::fmt;
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(),
}
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct IllegalStateException { pub enum Exceptions {
message: String, IllegalArgumentException(String),
} UnsupportedOperationException(String),
impl IllegalStateException { IllegalStateException(String),
pub fn new(message: &str) -> Self { ArithmeticException(String),
Self { NotFoundException(String),
message: message.to_owned(), FormatException(String),
} ChecksumException(String),
} ReaderException(String),
} WriterException(String),
ReedSolomonException(String),
#[derive(Debug)] ReaderDecodeException()
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(),
}
}
} }

View File

@@ -423,7 +423,7 @@ pub trait Writer {
format: &BarcodeFormat, format: &BarcodeFormat,
width: i32, width: i32,
height: i32, height: i32,
) -> Result<BitMatrix, WriterException>; ) -> Result<BitMatrix, Exceptions>;
/** /**
* @param contents The contents to encode in the barcode * @param contents The contents to encode in the barcode
@@ -440,7 +440,7 @@ pub trait Writer {
width: i32, width: i32,
height: i32, height: i32,
hints: HashMap<EncodeHintType, T>, hints: HashMap<EncodeHintType, T>,
) -> Result<BitMatrix, WriterException>; ) -> Result<BitMatrix, Exceptions>;
} }
/* /*
@@ -461,11 +461,7 @@ pub trait Writer {
//package com.google.zxing; //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 * 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 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 * @throws FormatException if a potential barcode is found but format is invalid
*/ */
fn decode(image: BinaryBitmap) -> Result<RXingResult, ReaderDecodeException>; fn decode(image: BinaryBitmap) -> Result<RXingResult, Exceptions>;
/** /**
* Locates and decodes a barcode in some format within an image. This method also accepts * 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<T>( fn decode_with_hints<T>(
image: BinaryBitmap, image: BinaryBitmap,
hints: HashMap<DecodeHintType, T>, hints: HashMap<DecodeHintType, T>,
) -> Result<RXingResult, ReaderDecodeException>; ) -> Result<RXingResult, Exceptions>;
/** /**
* Resets any internal state the implementation has after a decode, to prepare it * Resets any internal state the implementation has after a decode, to prepare it
@@ -964,9 +960,9 @@ pub struct Dimension {
} }
impl Dimension { impl Dimension {
pub fn new(width: usize, height: usize) -> Result<Self, IllegalArgumentException> { pub fn new(width: usize, height: usize) -> Result<Self, Exceptions> {
if width < 0 || height < 0 { if width < 0 || height < 0 {
return Err(IllegalArgumentException::new("")); return Err(Exceptions::IllegalArgumentException("".to_owned()));
} }
Ok(Self { width, height }) Ok(Self { width, height })
} }
@@ -1032,7 +1028,7 @@ pub trait Binarizer {
* @return The array of bits for this row (true means black). * @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized * @throws NotFoundException if row can't be binarized
*/ */
fn getBlackRow(&self, y: usize, row: BitArray) -> Result<BitArray, NotFoundException>; fn getBlackRow(&self, y: usize, row: BitArray) -> Result<BitArray, Exceptions>;
/** /**
* Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive
@@ -1043,7 +1039,7 @@ pub trait Binarizer {
* @return The 2D array of bits for the image (true means black). * @return The 2D array of bits for the image (true means black).
* @throws NotFoundException if image can't be binarized to make a matrix * @throws NotFoundException if image can't be binarized to make a matrix
*/ */
fn getBlackMatrix(&self) -> Result<BitMatrix, NotFoundException>; fn getBlackMatrix(&self) -> Result<BitMatrix, Exceptions>;
/** /**
* Creates a new object with the same type as this Binarizer implementation, but with pristine * Creates a new object with the same type as this Binarizer implementation, but with pristine
@@ -1122,7 +1118,7 @@ impl BinaryBitmap {
* @return The array of bits for this row (true means black). * @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized * @throws NotFoundException if row can't be binarized
*/ */
pub fn getBlackRow(&self, y: usize, row: BitArray) -> Result<BitArray, NotFoundException> { pub fn getBlackRow(&self, y: usize, row: BitArray) -> Result<BitArray, Exceptions> {
return self.binarizer.getBlackRow(y, row); return self.binarizer.getBlackRow(y, row);
} }
@@ -1135,7 +1131,7 @@ impl BinaryBitmap {
* @return The 2D array of bits for the image (true means black). * @return The 2D array of bits for the image (true means black).
* @throws NotFoundException if image can't be binarized to make a matrix * @throws NotFoundException if image can't be binarized to make a matrix
*/ */
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 // The matrix is created on demand the first time it is requested, then cached. There are two
// reasons for this: // reasons for this:
// 1. This work will never be done if the caller only installs 1D Reader objects, or if a // 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, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Box<dyn LuminanceSource>, UnsupportedOperationException> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(UnsupportedOperationException::new( return Err(Exceptions::UnsupportedOperationException(
"This luminance source does not support cropping.", "This luminance source does not support cropping.".to_owned(),
)); ));
} }
@@ -1367,9 +1363,9 @@ pub trait LuminanceSource {
*/ */
fn rotateCounterClockwise( fn rotateCounterClockwise(
&self, &self,
) -> Result<Box<dyn LuminanceSource>, UnsupportedOperationException> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(UnsupportedOperationException::new( return Err(Exceptions::UnsupportedOperationException(
"This luminance source does not support rotation by 90 degrees.", "This luminance source does not support rotation by 90 degrees.".to_owned(),
)); ));
} }
@@ -1381,9 +1377,9 @@ pub trait LuminanceSource {
*/ */
fn rotateCounterClockwise45( fn rotateCounterClockwise45(
&self, &self,
) -> Result<Box<dyn LuminanceSource>, UnsupportedOperationException> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(UnsupportedOperationException::new( return Err(Exceptions::UnsupportedOperationException(
"This luminance source does not support rotation by 45 degrees.", "This luminance source does not support rotation by 45 degrees.".to_owned(),
)); ));
} }
@@ -1586,10 +1582,10 @@ impl PlanarYUVLuminanceSource {
height: usize, height: usize,
reverseHorizontal: bool, reverseHorizontal: bool,
inverted: bool, inverted: bool,
) -> Result<Self, IllegalArgumentException> { ) -> Result<Self, Exceptions> {
if left + width > dataWidth || top + height > dataHeight { if left + width > dataWidth || top + height > dataHeight {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Crop rectangle does not fit within image data.", "Crop rectangle does not fit within image data.".to_owned(),
)); ));
} }
@@ -1753,7 +1749,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource {
top: usize, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Box<dyn LuminanceSource>, UnsupportedOperationException> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
match PlanarYUVLuminanceSource::new_with_all( match PlanarYUVLuminanceSource::new_with_all(
self.yuvData.clone(), self.yuvData.clone(),
self.dataWidth, self.dataWidth,
@@ -1766,7 +1762,7 @@ impl LuminanceSource for PlanarYUVLuminanceSource {
self.invert, self.invert,
) { ) {
Ok(new) => Ok(Box::new(new)), 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, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Box<dyn LuminanceSource>, UnsupportedOperationException> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
match RGBLuminanceSource::new_complex( match RGBLuminanceSource::new_complex(
&self.luminances, &self.luminances,
self.dataWidth, self.dataWidth,
@@ -1905,7 +1901,7 @@ impl LuminanceSource for RGBLuminanceSource {
height, height,
) { ) {
Ok(crop) => Ok(Box::new(crop)), 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, top: usize,
width: usize, width: usize,
height: usize, height: usize,
) -> Result<Self, IllegalArgumentException> { ) -> Result<Self, Exceptions> {
if (left + width > dataWidth || top + height > dataHeight) { if left + width > dataWidth || top + height > dataHeight {
return Err(IllegalArgumentException::new( return Err(Exceptions::IllegalArgumentException(
"Crop rectangle does not fit within image data.", "Crop rectangle does not fit within image data.".to_owned(),
)); ));
} }
Ok(Self { Ok(Self {