refactor to use exception helper factories

This commit is contained in:
Vukašin Stepanović
2023-02-15 10:46:13 +00:00
parent 3e27279dc8
commit 722ce78fd0
132 changed files with 966 additions and 1132 deletions

View File

@@ -168,7 +168,7 @@ impl BitArray {
pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None));
return Err(Exceptions::illegalArgumentEmpty());
}
if end == start {
return Ok(());
@@ -211,7 +211,7 @@ impl BitArray {
pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool, Exceptions> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException(None));
return Err(Exceptions::illegalArgumentEmpty());
}
if end == start {
return Ok(true); // empty range matches
@@ -253,9 +253,9 @@ impl BitArray {
*/
pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> {
if num_bits > 32 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"num bits must be between 0 and 32".to_owned(),
)));
));
}
if num_bits == 0 {
@@ -286,9 +286,7 @@ impl BitArray {
pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> {
if self.size != other.size {
return Err(Exceptions::IllegalArgumentException(Some(
"Sizes don't match".to_owned(),
)));
return Err(Exceptions::illegalArgument("Sizes don't match".to_owned()));
}
for i in 0..self.bits.len() {
//for (int i = 0; i < bits.length; i++) {

View File

@@ -65,9 +65,9 @@ impl BitMatrix {
*/
pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> {
if width < 1 || height < 1 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"Both dimensions must be greater than 0".to_owned(),
)));
));
}
Ok(Self {
width,
@@ -137,12 +137,12 @@ impl BitMatrix {
if string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
== '\n'
|| string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
== '\r'
{
if bitsPos > rowStartPos {
@@ -151,9 +151,9 @@ impl BitMatrix {
first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"row lengths do not match".to_owned(),
)));
));
}
rowStartPos = bitsPos;
nRows += 1;
@@ -168,10 +168,10 @@ impl BitMatrix {
bits[bitsPos] = false;
bitsPos += 1;
} else {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgument(format!(
"illegal character encountered: {}",
string_representation[pos..].to_owned()
))));
)));
}
}
@@ -182,9 +182,9 @@ impl BitMatrix {
// first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"row lengths do not match".to_owned(),
)));
));
}
nRows += 1;
}
@@ -311,9 +311,9 @@ impl BitMatrix {
pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> {
if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size
{
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"input matrix dimensions do not match".to_owned(),
)));
));
}
// let mut rowArray = BitArray::with_size(self.width as usize);
for y in 0..self.height {
@@ -363,16 +363,16 @@ impl BitMatrix {
// ));
// }
if height < 1 || width < 1 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"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(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"the region must fit inside the matrix".to_owned(),
)));
));
}
for y in top..bottom {
//for (int y = top; y < bottom; y++) {
@@ -444,9 +444,9 @@ impl BitMatrix {
self.rotate180();
Ok(())
}
_ => Err(Exceptions::IllegalArgumentException(Some(
_ => Err(Exceptions::illegalArgument(
"degrees must be a multiple of 0, 90, 180, or 270".to_owned(),
))),
)),
}
}

View File

@@ -70,9 +70,7 @@ impl BitSource {
*/
pub fn readBits(&mut self, numBits: usize) -> Result<u32, Exceptions> {
if !(1..=32).contains(&numBits) || numBits > self.available() {
return Err(Exceptions::IllegalArgumentException(Some(
numBits.to_string(),
)));
return Err(Exceptions::illegalArgument(numBits.to_string()));
}
let mut result: u32 = 0;

View File

@@ -244,9 +244,7 @@ impl CharacterSetECI {
28 => Ok(CharacterSetECI::Big5),
29 => Ok(CharacterSetECI::GB18030),
30 => Ok(CharacterSetECI::EUC_KR),
_ => Err(Exceptions::NotFoundException(Some(
"Bad ECI Value".to_owned(),
))),
_ => Err(Exceptions::notFound("Bad ECI Value".to_owned())),
}
}

View File

@@ -67,7 +67,7 @@ impl GridSampler for DefaultGridSampler {
transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions> {
if dimensionX == 0 || dimensionY == 0 {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
let mut bits = BitMatrix::new(dimensionX, dimensionY)?;
let mut points = vec![0.0; 2 * dimensionX as usize];
@@ -92,15 +92,15 @@ impl GridSampler for DefaultGridSampler {
// for (int x = 0; x < max; x += 2) {
// if points[x] as u32 >= image.getWidth() || points[x + 1] as u32 >= image.getHeight()
// {
// return Err(Exceptions::NotFoundException(Some(
// return Err(Exceptions::notFound(
// "index out of bounds, see documentation in file for explanation".to_owned(),
// )));
// ));
// }
if image
.try_get(points[x] as u32, points[x + 1] as u32)
.ok_or(Exceptions::NotFoundException(Some(
.ok_or(Exceptions::notFound(
"index out of bounds, see documentation in file for explanation".to_owned(),
)))?
))?
{
// Black(-ish) pixel
bits.set(x as u32 / 2, y);

View File

@@ -200,13 +200,13 @@ impl<'a> MonochromeRectangleDetector<'_> {
}
}
} else {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
lastRange_z = range;
y += deltaY;
x += deltaX
}
Err(Exceptions::NotFoundException(None))
Err(Exceptions::notFoundEmpty())
}
/**

View File

@@ -77,7 +77,7 @@ impl<'a> WhiteRectangleDetector<'_> {
|| downInit >= image.getHeight() as i32
|| rightInit >= image.getWidth() as i32
{
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
Ok(WhiteRectangleDetector {
@@ -223,7 +223,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if z.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
let mut t: Option<RXingResultPoint> = None;
@@ -241,7 +241,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if t.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
let mut x: Option<RXingResultPoint> = None;
@@ -259,7 +259,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if x.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
let mut y: Option<RXingResultPoint> = None;
@@ -277,12 +277,12 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if y.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap()))
} else {
Err(Exceptions::NotFoundException(None))
Err(Exceptions::notFoundEmpty())
}
}

View File

@@ -233,9 +233,9 @@ impl GlobalHistogramBinarizer {
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
if secondPeak - firstPeak <= numBuckets / 16 {
return Err(Exceptions::NotFoundException(Some(
return Err(Exceptions::notFound(
"secondPeak - firstPeak <= numBuckets / 16 ".to_owned(),
)));
));
}
// Find a valley between them that is low and closer to the white peak.

View File

@@ -145,7 +145,7 @@ pub trait GridSampler {
let x = points[offset] as i32;
let y = points[offset + 1] as i32;
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
nudged = false;
if x == -1 {
@@ -172,7 +172,7 @@ pub trait GridSampler {
let x = points[offset as usize] as i32;
let y = points[offset as usize + 1] as i32;
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
nudged = false;
if x == -1 {

View File

@@ -67,14 +67,12 @@ impl ECIInput for MinimalECIInput {
*/
fn charAt(&self, index: usize) -> Result<char, Exceptions> {
if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(),
)));
return Err(Exceptions::indexOutOfBounds(index.to_string()));
}
if self.isECI(index as u32)? {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgument(format!(
"value at {index} is not a character but an ECI"
))));
)));
}
if self.isFNC1(index)? {
Ok(self.fnc1 as u8 as char)
@@ -105,15 +103,15 @@ impl ECIInput for MinimalECIInput {
*/
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> {
if start > end || end > self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None));
return Err(Exceptions::indexOutOfBoundsEmpty());
}
let mut result = String::new();
for i in start..end {
// for (int i = start; i < end; i++) {
if self.isECI(i as u32)? {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgument(format!(
"value at {i} is not a character but an ECI"
))));
)));
}
result.push_str(&self.charAt(i)?.to_string());
}
@@ -133,7 +131,7 @@ impl ECIInput for MinimalECIInput {
*/
fn isECI(&self, index: u32) -> Result<bool, Exceptions> {
if index >= self.length() as u32 {
return Err(Exceptions::IndexOutOfBoundsException(None));
return Err(Exceptions::indexOutOfBoundsEmpty());
}
Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX)
}
@@ -158,12 +156,12 @@ impl ECIInput for MinimalECIInput {
*/
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> {
if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None));
return Err(Exceptions::indexOutOfBoundsEmpty());
}
if !self.isECI(index as u32)? {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgument(format!(
"value at {index} is not an ECI but a character"
))));
)));
}
Ok((self.bytes[index] as u32 - 256) as i32)
}
@@ -250,7 +248,7 @@ impl MinimalECIInput {
*/
pub fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> {
if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(None));
return Err(Exceptions::indexOutOfBoundsEmpty());
}
Ok(self.bytes[index] == 1000)
}

View File

@@ -19,7 +19,7 @@ impl OtsuLevelBinarizer {
fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result<BitMatrix, Exceptions> {
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))
return Err(Exceptions::illegalArgumentEmpty())
};
buff
};

View File

@@ -133,7 +133,7 @@ impl GenericGF {
*/
pub fn log(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 {
return Err(Exceptions::IllegalArgumentException(None));
return Err(Exceptions::illegalArgumentEmpty());
}
// let pos: usize = a.try_into().unwrap();
Ok(self.logTable[a as usize])
@@ -144,7 +144,7 @@ impl GenericGF {
*/
pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 {
return Err(Exceptions::ArithmeticException(None));
return Err(Exceptions::arithmeticEmpty());
}
let log_t_loc: usize = a as usize;
let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize;

View File

@@ -49,9 +49,9 @@ impl GenericGFPoly {
*/
pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result<Self, Exceptions> {
if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(String::from(
return Err(Exceptions::illegalArgument(String::from(
"coefficients cannot be empty",
))));
)));
}
Ok(Self {
field,
@@ -140,9 +140,9 @@ impl GenericGFPoly {
pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"GenericGFPolys do not have same GenericGF field".to_owned(),
)));
));
}
if self.isZero() {
return Ok(other.clone());
@@ -177,9 +177,9 @@ impl GenericGFPoly {
pub fn multiply(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field {
//if (!field.equals(other.field)) {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"GenericGFPolys do not have same GenericGF field".to_owned(),
)));
));
}
if self.isZero() || other.isZero() {
return Ok(self.getZero());
@@ -252,14 +252,12 @@ impl GenericGFPoly {
other: &GenericGFPoly,
) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"GenericGFPolys do not have same GenericGF field".to_owned(),
)));
));
}
if other.isZero() {
return Err(Exceptions::IllegalArgumentException(Some(
"Divide by 0".to_owned(),
)));
return Err(Exceptions::illegalArgument("Divide by 0".to_owned()));
}
let mut quotient = self.getZero();
@@ -268,11 +266,7 @@ impl GenericGFPoly {
let denominator_leading_term = other.getCoefficient(other.getDegree());
let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) {
Ok(val) => val,
Err(_issue) => {
return Err(Exceptions::IllegalArgumentException(Some(
"arithmetic issue".to_owned(),
)))
}
Err(_issue) => return Err(Exceptions::illegalArgument("arithmetic issue".to_owned())),
};
while remainder.getDegree() >= other.getDegree() && !remainder.isZero() {

View File

@@ -77,7 +77,7 @@ impl ReedSolomonDecoder {
return Ok(0);
}
let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else {
return Err(Exceptions::ReedSolomonException(None));
return Err(Exceptions::reedSolomonEmpty());
};
let sigmaOmega = self.runEuclideanAlgorithm(
&GenericGF::buildMonomial(self.field, twoS as usize, 1),
@@ -92,15 +92,11 @@ impl ReedSolomonDecoder {
//for (int i = 0; i < errorLocations.length; i++) {
let log_value = self.field.log(errorLocations[i] as i32)?;
if log_value > received.len() as i32 - 1 {
return Err(Exceptions::ReedSolomonException(Some(
"Bad error location".to_owned(),
)));
return Err(Exceptions::reedSolomon("Bad error location".to_owned()));
}
let position: isize = received.len() as isize - 1 - log_value as isize;
if position < 0 {
return Err(Exceptions::ReedSolomonException(Some(
"Bad error location".to_owned(),
)));
return Err(Exceptions::reedSolomon("Bad error location".to_owned()));
}
received[position as usize] =
GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]);
@@ -138,9 +134,7 @@ impl ReedSolomonDecoder {
// Divide rLastLast by rLast, with quotient in q and remainder in r
if rLast.isZero() {
// Oops, Euclidean algorithm already terminated?
return Err(Exceptions::ReedSolomonException(Some(
"r_{i-1} was zero".to_owned(),
)));
return Err(Exceptions::reedSolomon("r_{i-1} was zero".to_owned()));
}
r = rLastLast;
let mut q = r.getZero();
@@ -158,26 +152,20 @@ impl ReedSolomonDecoder {
t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?;
if r.getDegree() >= rLast.getDegree() {
return Err(Exceptions::ReedSolomonException(Some(format!(
return Err(Exceptions::reedSolomon(format!(
"Division algorithm failed to reduce polynomial? r: {r}, rLast: {rLast}"
))));
)));
}
}
let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 {
return Err(Exceptions::ReedSolomonException(Some(
"sigmaTilde(0) was zero".to_owned(),
)));
return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero".to_owned()));
}
let inverse = match self.field.inverse(sigmaTildeAtZero) {
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(),
)))
}
Err(_err) => return Err(Exceptions::reedSolomon("ArithmetricException".to_owned())),
};
let sigma = t.multiply_with_scalar(inverse);
let omega = r.multiply_with_scalar(inverse);
@@ -205,9 +193,9 @@ impl ReedSolomonDecoder {
}
}
if e != numErrors {
return Err(Exceptions::ReedSolomonException(Some(
return Err(Exceptions::reedSolomon(
"Error locator degree does not match number of roots".to_owned(),
)));
));
}
Ok(result)
}

View File

@@ -73,15 +73,15 @@ impl ReedSolomonEncoder {
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> {
if ec_bytes == 0 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"No error correction bytes".to_owned(),
)));
));
}
let data_bytes = to_encode.len() - ec_bytes;
if data_bytes == 0 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"No data bytes provided".to_owned(),
)));
));
}
let fld = self.field;
let generator = self.buildGenerator(ec_bytes);
@@ -91,7 +91,7 @@ impl ReedSolomonEncoder {
let mut info = GenericGFPoly::new(fld, &info_coefficients)?;
info = info.multiply_by_monomial(ec_bytes, 1)?;
let remainder = &info
.divide(generator.ok_or(Exceptions::ReedSolomonException(None))?)?
.divide(generator.ok_or(Exceptions::reedSolomonEmpty())?)?
.1;
let coefficients = remainder.getCoefficients();
let num_zero_coefficients = ec_bytes - coefficients.len();