Cleanup of many components of the code.

Many unwraps, expects, and panics removed or handled.

More rustification of the codebase.

Squashed commit of the following:

commit 80c6483cf8c819496a7b781f9e3a149d1f18d5fe
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 20:36:57 2023 -0600

    add other parsed result option

commit 412d92ae585e7bf194697f5282dbc045e448bace
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 19:06:34 2023 -0600

    fix some panics

commit 9108d3e931aadec00fc0bf346ebc52d24e5d8146
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 18:56:30 2023 -0600

    clippy --fix

commit 8cd89d314323f54f342f15fc73297b62d418ac79
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 18:55:45 2023 -0600

    some more cleanup in aztec

commit fb7f9242e273b85a4bb212f22a185a0dcbfafc36
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 18:19:54 2023 -0600

    cleanup root

commit 4fb7c0639830869149332b29be789e891eade3e7
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 16:50:15 2023 -0600

    format

commit 3ac271af657b25fbe5ee39cbdf8859e5aa38ea41
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 16:43:14 2023 -0600

    clippy --fix

commit 0c5b4c1477159db93a9da9645039f51cd1a7c574
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 16:04:31 2023 -0600

    qrcode cleanup complete

commit 70c1d107cc672e45d46567c650c46fece7e7da9c
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 13:28:25 2023 -0600

    clippy --fix

commit e13263d0f1f2a13dbb59b6e60d8b871a32babc92
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 13:27:44 2023 -0600

    qrcode detector cleanup

commit f7f2855099e469fe1091868c6099196705d0ae83
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 11:48:13 2023 -0600

    qrcode decoder

commit bdbaaba597b3479639c2ed3726465a69e3004471
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 11:13:18 2023 -0600

    clippy --fix

commit fd6dbcaeb1f45dc91ae98f0e7c58aad48d67df78
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 11:12:28 2023 -0600

    pdf417 cleanup complete

commit 7bbd47604c2639a5eb61bdb5533e71be3bce95a1
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 10:39:28 2023 -0600

    clippy --fix

commit 8f4962b7bb5f133524fe4d3d4948e5672a88c545
Author: Henry Schimke <henry@azule.info>
Date:   Fri Feb 10 10:39:00 2023 -0600

    cleanup on pdf417 hie

commit 254c8243953776d3c8704dd81529aadd05d5a94e
Author: Henry <henry@azule.info>
Date:   Fri Feb 10 02:51:21 2023 +0000

    partway through pdf417 hle

commit d4a5b00fde8c0282b0c6e4175a21c1e111b11533
Author: Henry <henry@azule.info>
Date:   Wed Feb 8 21:35:25 2023 +0000

    clippy --fix

commit 2bd4a8e218aa963a88997b50bc5a198f9a88205e
Author: Henry <henry@azule.info>
Date:   Wed Feb 8 21:31:55 2023 +0000

    pdf417 decode and detect cleanup

commit 05130ac54a72c2303045d64507bf6185aa74e531
Author: Henry Schimke <henry@azule.info>
Date:   Tue Feb 7 08:06:25 2023 -0600

    at decodeTextCompaction in decoded_bit_straem_parser

commit 924c023a7d2339dfffa6ef0c4a805fb192576796
Author: Henry Schimke <henry@azule.info>
Date:   Mon Feb 6 18:22:02 2023 -0600

    clippy --fix

commit 5cfb81a885c22b4b5ec937a79be31d0815def211
Author: Henry Schimke <henry@azule.info>
Date:   Mon Feb 6 18:20:22 2023 -0600

    oned cleanup

commit 0649b64854baf56a8e3314728d4f6cf4063db8b2
Author: Henry Schimke <henry@azule.info>
Date:   Mon Feb 6 11:47:28 2023 -0600

    rss cleanup

commit 2d3127898fc11f7e65d590e983cda799b798b646
Author: Henry Schimke <henry@azule.info>
Date:   Mon Feb 6 10:19:56 2023 -0600

    multi cleanup

commit 7e8b43a159083a2096123e6204d4d1d359c59981
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 21:41:59 2023 -0600

    cargo fmt

commit df8285e8da07b4bffd48ca6e596de3f010eb8d9e
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 21:41:29 2023 -0600

    maxicode cleanup

commit a51f923a14016eb416ca202b2194258808dde3e7
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 21:27:57 2023 -0600

    cargo fmt

commit 332d7eef4a25318611025a3fcb0b70c604d917be
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 21:27:48 2023 -0600

    cleanup datamatrix

commit eb2311c476a9c9993f271ab6cf9fd359aedca26f
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 21:27:26 2023 -0600

    cargo clippy --fix

commit 2abaa4c51d287f619d4c7a438f85ba2a30f159cf
Author: Henry <henry@azule.info>
Date:   Sun Feb 5 19:13:02 2023 -0600

    finish cleanup in parsers

commit 716aa2fbf728716cff36657a5fd80e7bca5276b7
Author: Henry Schimke <henry@azule.info>
Date:   Sun Feb 5 17:44:56 2023 -0600

    cleanup continues

commit 7d843788a49fa9cc82c4616d226c0f882e73612b
Author: Henry Schimke <henry@azule.info>
Date:   Sun Feb 5 15:15:09 2023 -0600

    common cleanup

commit fd251866c68f22d450dd428c93d7a3620bf1be27
Author: Henry Schimke <henry@azule.info>
Date:   Sun Feb 5 10:24:54 2023 -0600

    cleanup reedsolomon

commit 132e27ed1468f5c1ce998516ff5a00687217c3e6
Author: Henry Schimke <henry@azule.info>
Date:   Sun Feb 5 09:52:04 2023 -0600

    make MathUtils more generic

commit d8352b7fff4cb4f9ecc8e8a969710d26ef410e8b
Author: Henry Schimke <henry@azule.info>
Date:   Sun Feb 5 09:29:33 2023 -0600

    cleanup some string handling in ResultParser

    There may still be some edge cases where multi-byte characters break the parser
This commit is contained in:
Henry
2023-02-10 20:41:25 -06:00
parent 5222bb25b7
commit 28723be2eb
180 changed files with 3248 additions and 4117 deletions

View File

@@ -39,7 +39,9 @@ fn test_random() {
// }
assert_eq!(
encoding::all::UTF_8.name(),
StringUtils::guessCharset(&bytes, &HashMap::new()).name()
StringUtils::guessCharset(&bytes, &HashMap::new())
.unwrap()
.name()
);
}
@@ -100,8 +102,8 @@ fn test_utf16_le() {
}
fn do_test(bytes: &[u8], charset: EncodingRef, encoding: &str) {
let guessedCharset = StringUtils::guessCharset(bytes, &HashMap::new());
let guessedEncoding = StringUtils::guessEncoding(bytes, &HashMap::new());
let guessedCharset = StringUtils::guessCharset(bytes, &HashMap::new()).unwrap();
let guessedEncoding = StringUtils::guessEncoding(bytes, &HashMap::new()).unwrap();
assert_eq!(charset.name(), guessedCharset.name());
assert_eq!(encoding, guessedEncoding);
}

View File

@@ -50,7 +50,7 @@ impl BitArray {
}
}
// For testing only
/// For testing only
#[cfg(test)]
pub fn with_initial_values(bits: Vec<u32>, size: usize) -> Self {
Self { bits, size }

View File

@@ -53,8 +53,8 @@ impl BitMatrix {
*
* @param dimension height and width
*/
pub fn with_single_dimension(dimension: u32) -> Self {
Self::new(dimension, dimension).unwrap()
pub fn with_single_dimension(dimension: u32) -> Result<Self, Exceptions> {
Self::new(dimension, dimension)
}
/**
@@ -134,8 +134,16 @@ impl BitMatrix {
let mut nRows = 0;
let mut pos = 0;
while pos < string_representation.chars().count() {
if string_representation.chars().nth(pos).unwrap() == '\n'
|| string_representation.chars().nth(pos).unwrap() == '\r'
if string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::IllegalStateException(None))?
== '\n'
|| string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::IllegalStateException(None))?
== '\r'
{
if bitsPos > rowStartPos {
//if rowLength == -1 {
@@ -181,15 +189,12 @@ impl BitMatrix {
nRows += 1;
}
let mut matrix = BitMatrix::new(rowLength.try_into().unwrap(), nRows)?;
let mut matrix = BitMatrix::new(rowLength as u32, nRows)?;
for (i, bit) in bits.iter().enumerate().take(bitsPos) {
// for i in 0..bitsPos {
//for (int i = 0; i < bitsPos; i++) {
if *bit {
matrix.set(
(i % rowLength).try_into().unwrap(),
(i / rowLength).try_into().unwrap(),
);
matrix.set((i % rowLength) as u32, (i / rowLength) as u32);
}
}
Ok(matrix)

View File

@@ -33,7 +33,7 @@ static BIT_MATRIX_POINTS: [u32; 6] = [1, 2, 2, 0, 3, 1];
#[test]
fn test_get_set() {
let mut matrix = BitMatrix::with_single_dimension(33);
let mut matrix = BitMatrix::with_single_dimension(33).expect("new");
assert_eq!(33, matrix.getHeight());
for y in 0..33 {
// for (int y = 0; y < 33; y++) {
@@ -55,7 +55,7 @@ fn test_get_set() {
#[test]
fn test_set_region() {
let mut matrix = BitMatrix::with_single_dimension(5);
let mut matrix = BitMatrix::with_single_dimension(5).expect("new");
matrix.setRegion(1, 1, 3, 3).expect("must set");
for y in 0..5 {
// for (int y = 0; y < 5; y++) {
@@ -71,7 +71,7 @@ fn test_set_region() {
#[test]
fn test_enclosing() {
let mut matrix = BitMatrix::with_single_dimension(5);
let mut matrix = BitMatrix::with_single_dimension(5).expect("new");
assert!(matrix.getEnclosingRectangle().is_none());
matrix.setRegion(1, 1, 1, 1).expect("must set");
assert_eq!(vec![1, 1, 1, 1], matrix.getEnclosingRectangle().unwrap());
@@ -83,7 +83,7 @@ fn test_enclosing() {
#[test]
fn test_on_bit() {
let mut matrix = BitMatrix::with_single_dimension(5);
let mut matrix = BitMatrix::with_single_dimension(5).expect("new");
assert!(matrix.getTopLeftOnBit().is_none());
assert!(matrix.getBottomRightOnBit().is_none());
matrix.setRegion(1, 1, 1, 1).expect("must set");

View File

@@ -90,13 +90,18 @@ impl GridSampler for DefaultGridSampler {
let mut x = 0;
while x < max {
// 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(
// if points[x] as u32 >= image.getWidth() || points[x + 1] as u32 >= image.getHeight()
// {
// return Err(Exceptions::NotFoundException(Some(
// "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(
"index out of bounds, see documentation in file for explanation".to_owned(),
)));
}
if image.get(points[x] as u32, points[x + 1] as u32) {
)))?
{
// Black(-ish) pixel
bits.set(x as u32 / 2, y);
}

View File

@@ -14,8 +14,10 @@
* limitations under the License.
*/
//package com.google.zxing.common.detector;
use std::{f32, i32};
use std::{
f32, i32,
ops::{Add, Sub},
};
/**
* General math-related and numeric utility functions.
@@ -32,32 +34,43 @@ use std::{f32, i32};
*/
#[inline(always)]
pub fn round(d: f32) -> i32 {
(d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32
// (d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32
d.round() as i32
}
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
#[inline(always)]
pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 {
let xDiff: f64 = (aX - bX).into();
let yDiff: f64 = (aY - bY).into();
(xDiff * xDiff + yDiff * yDiff).sqrt() as f32
}
// /**
// * @param aX point A x coordinate
// * @param aY point A y coordinate
// * @param bX point B x coordinate
// * @param bY point B y coordinate
// * @return Euclidean distance between points A and B
// */
// #[inline(always)]
// pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 {
// let xDiff: f64 = (aX - bX).into();
// let yDiff: f64 = (aY - bY).into();
// (xDiff * xDiff + yDiff * yDiff).sqrt() as f32
// }
// /**
// * @param aX point A x coordinate
// * @param aY point A y coordinate
// * @param bX point B x coordinate
// * @param bY point B y coordinate
// * @return Euclidean distance between points A and B
// */
// #[inline(always)]
// pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 {
// let xDiff: f64 = (aX - bX).into();
// let yDiff: f64 = (aY - bY).into();
// (xDiff * xDiff + yDiff * yDiff).sqrt() as f32
// }
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
#[inline(always)]
pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 {
pub fn distance<T>(aX: T, aY: T, bX: T, bY: T) -> f32
where
T: Sub<T, Output = T> + Into<f64>,
{
let xDiff: f64 = (aX - bX).into();
let yDiff: f64 = (aY - bY).into();
(xDiff * xDiff + yDiff * yDiff).sqrt() as f32
@@ -68,13 +81,11 @@ pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 {
* @return sum of values in array
*/
#[inline(always)]
pub fn sum(array: &[i32]) -> i32 {
pub fn sum<'a, T>(array: &'a [T]) -> T
where
T: Add + std::iter::Sum<&'a T>,
{
array.iter().sum()
// let mut count = 0;
// for a in array {
// count += a;
// }
// count
}
#[cfg(test)]
@@ -112,15 +123,12 @@ mod tests {
fn testDistance() {
assert_eq!(
(8.0f32).sqrt(),
MathUtils::distance_float(1.0f32, 2.0f32, 3.0f32, 4.0f32)
);
assert_eq!(
0.0f32,
MathUtils::distance_float(1.0f32, 2.0f32, 1.0f32, 2.0f32)
MathUtils::distance(1.0f32, 2.0f32, 3.0f32, 4.0f32)
);
assert_eq!(0.0f32, MathUtils::distance(1.0f32, 2.0f32, 1.0f32, 2.0f32));
assert_eq!((8.0f32).sqrt(), MathUtils::distance_int(1, 2, 3, 4));
assert_eq!(0.0f32, MathUtils::distance_int(1, 2, 1, 2));
assert_eq!((8.0f32).sqrt(), MathUtils::distance(1, 2, 3, 4));
assert_eq!(0.0f32, MathUtils::distance(1, 2, 1, 2));
}
#[test]
@@ -129,5 +137,7 @@ mod tests {
assert_eq!(1, MathUtils::sum(&[1]));
assert_eq!(4, MathUtils::sum(&[1, 3]));
assert_eq!(0, MathUtils::sum(&[-1, 1]));
assert_eq!(0.0, MathUtils::sum(&[-1.0, 1.0]));
assert_eq!(4.0, MathUtils::sum(&[1.0, 3.0]));
}
}

View File

@@ -293,7 +293,7 @@ impl<'a> WhiteRectangleDetector<'_> {
b_x: f32,
b_y: f32,
) -> Option<RXingResultPoint> {
let dist = MathUtils::round(MathUtils::distance_float(a_x, a_y, b_x, b_y));
let dist = MathUtils::round(MathUtils::distance(a_x, a_y, b_x, b_y));
let x_step: f32 = (b_x - a_x) / dist as f32;
let y_step: f32 = (b_y - a_y) / dist as f32;

View File

@@ -210,14 +210,20 @@ impl ECIEncoderSet {
self.encoders.is_empty()
}
pub fn getCharsetName(&self, index: usize) -> &'static str {
assert!(index < self.len());
return self.encoders[index].name();
pub fn getCharsetName(&self, index: usize) -> Option<&'static str> {
if index < self.len() {
Some(self.encoders[index].name())
} else {
None
}
}
pub fn getCharset(&self, index: usize) -> EncodingRef {
assert!(index < self.len());
self.encoders[index]
pub fn getCharset(&self, index: usize) -> Option<EncodingRef> {
if index < self.len() {
Some(self.encoders[index])
} else {
None
}
}
pub fn getECIValue(&self, encoderIndex: usize) -> u32 {
@@ -233,25 +239,35 @@ impl ECIEncoderSet {
self.priorityEncoderIndex
}
pub fn canEncode(&self, c: &str, encoderIndex: usize) -> bool {
assert!(encoderIndex < self.len());
let encoder = self.encoders[encoderIndex];
let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict);
pub fn canEncode(&self, c: &str, encoderIndex: usize) -> Option<bool> {
if encoderIndex < self.len() {
let encoder = self.encoders[encoderIndex];
let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict);
enc_data.is_ok()
Some(enc_data.is_ok())
} else {
None
}
}
pub fn encode_char(&self, c: &str, encoderIndex: usize) -> Vec<u8> {
assert!(encoderIndex < self.len());
let encoder = self.encoders[encoderIndex];
let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict);
assert!(enc_data.is_ok());
enc_data.unwrap()
pub fn encode_char(&self, c: &str, encoderIndex: usize) -> Option<Vec<u8>> {
if encoderIndex < self.len() {
let encoder = self.encoders[encoderIndex];
let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict);
enc_data.ok()
// assert!(enc_data.is_ok());
// enc_data.unwrap()
} else {
None
}
}
pub fn encode_string(&self, s: &str, encoderIndex: usize) -> Vec<u8> {
assert!(encoderIndex < self.len());
let encoder = self.encoders[encoderIndex];
encoder.encode(s, encoding::EncoderTrap::Replace).unwrap()
pub fn encode_string(&self, s: &str, encoderIndex: usize) -> Option<Vec<u8>> {
if encoderIndex < self.len() {
let encoder = self.encoders[encoderIndex];
encoder.encode(s, encoding::EncoderTrap::Strict).ok()
} else {
None
}
}
}

View File

@@ -106,5 +106,5 @@ pub trait ECIInput: Display {
* if the value at the {@code index} argument is not an ECI (@see #isECI)
*/
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions>;
fn haveNCharacters(&self, index: usize, n: usize) -> bool;
fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool, Exceptions>;
}

View File

@@ -51,7 +51,7 @@ impl ECIStringBuilder {
pub fn with_capacity(initial_capacity: usize) -> Self {
Self {
current_bytes: Vec::with_capacity(initial_capacity),
result: String::new(),
result: String::with_capacity(initial_capacity),
current_charset: Some(encoding::all::ISO_8859_1),
}
}
@@ -121,31 +121,25 @@ impl ECIStringBuilder {
Ok(())
}
/// Finishes encoding anything in the buffer using the current ECI and resets.
///
/// This function can panic
pub fn encodeCurrentBytesIfAny(&mut self) {
if let Some(encoder) = self.current_charset {
if encoder.name() == encoding::all::UTF_8.name() {
if !self.current_bytes.is_empty() {
// if result == null {
// result = currentBytes;
// currentBytes = new StringBuilder();
// } else {
self.result.push_str(
&String::from_utf8(std::mem::take(&mut self.current_bytes)).unwrap(),
);
self.current_bytes.clear();
// }
}
} else if !self.current_bytes.is_empty() {
let bytes = std::mem::take(&mut self.current_bytes);
self.current_bytes.clear();
// if (result == null) {
// result = new StringBuilder(new String(bytes, currentCharset));
// } else {
let encoded_value = encoder
.decode(&bytes, encoding::DecoderTrap::Strict)
.unwrap();
self.result.push_str(&encoded_value);
// }
}
} else {
for byte in &self.current_bytes {
@@ -172,7 +166,7 @@ impl ECIStringBuilder {
*/
pub fn len(&mut self) -> usize {
self.encodeCurrentBytesIfAny(); //return toString().length();
self.result.len()
self.result.chars().count()
}
/**

View File

@@ -102,11 +102,6 @@ impl Binarizer for GlobalHistogramBinarizer {
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> {
// if self.black_matrix.is_none() {
// self.black_matrix =
// Some(Self::build_black_matrix(&self.source).expect("matrix must generate"))
// }
// Ok(self.black_matrix.as_ref().unwrap())
let matrix = self
.black_matrix
.get_or_try_init(|| Self::build_black_matrix(&self.source))?;

View File

@@ -144,22 +144,22 @@ pub trait GridSampler {
// for (int offset = 0; offset < maxOffset && nudged; offset += 2) {
let x = points[offset] as i32;
let y = points[offset + 1] as i32;
if x < -1 || x > width.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() {
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::NotFoundException(None));
}
nudged = false;
if x == -1 {
points[offset] = 0.0f32;
points[offset] = 0.0;
nudged = true;
} else if x == width.try_into().unwrap() {
points[offset] = width as f32 - 1f32;
} else if x == width as i32 {
points[offset] = width as f32 - 1.0;
nudged = true;
}
if y == -1 {
points[offset + 1] = 0.0f32;
points[offset + 1] = 0.0;
nudged = true;
} else if y == height.try_into().unwrap() {
points[offset + 1] = height as f32 - 1f32;
} else if y == height as i32 {
points[offset + 1] = height as f32 - 1.0;
nudged = true;
}
offset += 2;
@@ -171,22 +171,22 @@ pub trait GridSampler {
// for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
let x = points[offset as usize] as i32;
let y = points[offset as usize + 1] as i32;
if x < -1 || x > width.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() {
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::NotFoundException(None));
}
nudged = false;
if x == -1 {
points[offset as usize] = 0.0f32;
points[offset as usize] = 0.0;
nudged = true;
} else if x == width.try_into().unwrap() {
points[offset as usize] = width as f32 - 1f32;
} else if x == width as i32 {
points[offset as usize] = width as f32 - 1.0;
nudged = true;
}
if y == -1 {
points[offset as usize + 1] = 0.0f32;
points[offset as usize + 1] = 0.0;
nudged = true;
} else if y == height.try_into().unwrap() {
points[offset as usize + 1] = height as f32 - 1f32;
} else if y == height as i32 {
points[offset as usize + 1] = height as f32 - 1.0;
nudged = true;
}
offset += -2;

View File

@@ -67,13 +67,6 @@ impl Binarizer for HybridBinarizer {
* profiling easier, and not doing heavy lifting when callers don't expect it.
*/
fn getBlackMatrix(&self) -> Result<&BitMatrix, Exceptions> {
// if self.black_matrix.is_none() {
// self.black_matrix = Some(
// Self::calculateBlackMatrix(&mut self.ghb)
// .expect("generate black matrix must complete"),
// )
// }
// Ok(self.black_matrix.as_ref().unwrap())
let matrix = self
.black_matrix
.get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?;
@@ -200,6 +193,7 @@ impl HybridBinarizer {
}
}
#[inline(always)]
fn cap(value: u32, max: u32) -> u32 {
if value < 2 {
2

View File

@@ -14,12 +14,6 @@
* limitations under the License.
*/
// package com.google.zxing.common;
// import java.nio.charset.Charset;
// import java.util.ArrayList;
// import java.util.List;
use std::{fmt, rc::Rc};
use encoding::EncodingRef;
@@ -174,17 +168,17 @@ impl ECIInput for MinimalECIInput {
Ok((self.bytes[index] as u32 - 256) as i32)
}
fn haveNCharacters(&self, index: usize, n: usize) -> bool {
fn haveNCharacters(&self, index: usize, n: usize) -> Result<bool, Exceptions> {
if index + n > self.bytes.len() {
return false;
return Ok(false);
}
for i in 0..n {
// for (int i = 0; i < n; i++) {
if self.isECI(index as u32 + i as u32).unwrap() {
return false;
if self.isECI(index as u32 + i as u32)? {
return Ok(false);
}
}
true
Ok(true)
}
}
impl MinimalECIInput {
@@ -209,10 +203,14 @@ impl MinimalECIInput {
let bytes = if encoderSet.len() == 1 {
//optimization for the case when all can be encoded without ECI in ISO-8859-1
let mut bytes_hld = vec![0; stringToEncode.len()];
for (i, byt) in bytes_hld.iter_mut().enumerate().take(stringToEncode.len()) {
for (byt, c) in bytes_hld
.iter_mut()
.zip(&stringToEncode)
.take(stringToEncode.len())
{
// for i in 0..stringToEncode.len() {
// for (int i = 0; i < bytes.length; i++) {
let c = stringToEncode.get(i).unwrap();
// let c = stringToEncode.get(i).unwrap();
*byt = if fnc1.is_some() && c == fnc1.as_ref().unwrap() {
1000
} else {
@@ -287,7 +285,9 @@ impl MinimalECIInput {
if encoderSet.getPriorityEncoderIndex().is_some()
&& ((fnc1.is_some()
&& ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap())
|| encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex().unwrap()))
|| encoderSet
.canEncode(ch, encoderSet.getPriorityEncoderIndex().unwrap())
.unwrap())
{
start = encoderSet.getPriorityEncoderIndex().unwrap();
end = start + 1;
@@ -298,7 +298,7 @@ impl MinimalECIInput {
// for (int i = start; i < end; i++) {
if (fnc1.is_some()
&& ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap())
|| encoderSet.canEncode(ch, i)
|| encoderSet.canEncode(ch, i).unwrap()
{
Self::addEdge(
edges,
@@ -309,6 +309,9 @@ impl MinimalECIInput {
}
}
/// Minimially encode a string with the given characterset.
///
/// Function can panic if the string cannot be encoded.
pub fn encodeMinimally(
stringToEncode: &str,
encoderSet: &ECIEncoderSet,
@@ -360,6 +363,7 @@ impl MinimalECIInput {
} else {
let bytes: Vec<u16> = encoderSet
.encode_char(&c.c, c.encoderIndex)
.unwrap()
.iter()
.map(|x| *x as u16)
.collect();
@@ -414,7 +418,7 @@ impl InputEdge {
let mut size = if c == Self::FNC1_UNICODE {
1
} else {
encoderSet.encode_char(c, encoderIndex).len()
encoderSet.encode_char(c, encoderIndex).unwrap().len()
};
//let fnc1Str = String::from_utf16(&[fnc1]).unwrap();

View File

@@ -404,7 +404,7 @@ fn test_encode_decode_random(field: GenericGFRef, dataSize: usize, ecSize: usize
ecSize > 0 && ecSize + dataSize <= field.getSize(),
"Invalid ECC size for {field}"
);
let mut encoder = ReedSolomonEncoder::new(field);
let mut encoder = ReedSolomonEncoder::new(field).expect("new");
let mut message = vec![0; dataSize + ecSize];
let mut dataWords: Vec<i32> = vec![0; dataSize];
let mut ecWords = vec![0; ecSize];
@@ -440,7 +440,7 @@ fn test_encode_decode(field: GenericGFRef, dataWords: &Vec<i32>, ecWords: &Vec<i
}
fn test_encoder(field: GenericGFRef, dataWords: &Vec<i32>, ecWords: &Vec<i32>) {
let mut encoder = ReedSolomonEncoder::new(field);
let mut encoder = ReedSolomonEncoder::new(field).expect("new");
let mut messageExpected = vec![0; dataWords.len() + ecWords.len()];
let mut message = vec![0; dataWords.len() + ecWords.len()];
messageExpected[0..dataWords.len()].clone_from_slice(&dataWords[0..dataWords.len()]);

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(
"coefficients.len()".to_owned(),
)));
return Err(Exceptions::IllegalArgumentException(Some(String::from(
"coefficients cannot be empty",
))));
}
Ok(Self {
field,

View File

@@ -61,7 +61,7 @@ impl ReedSolomonDecoder {
* @throws ReedSolomonException if decoding fails for any reason
*/
pub fn decode(&self, received: &mut Vec<i32>, twoS: i32) -> Result<usize, Exceptions> {
let poly = GenericGFPoly::new(self.field, received).unwrap();
let poly = GenericGFPoly::new(self.field, received)?;
let mut syndromeCoefficients = vec![0; twoS as usize];
let mut noError = true;
for i in 0..twoS {
@@ -87,7 +87,7 @@ impl ReedSolomonDecoder {
let sigma = &sigmaOmega[0];
let omega = &sigmaOmega[1];
let errorLocations = self.findErrorLocations(sigma)?;
let errorMagnitudes = self.findErrorMagnitudes(omega, &errorLocations);
let errorMagnitudes = self.findErrorMagnitudes(omega, &errorLocations)?;
for i in 0..errorLocations.len() {
//for (int i = 0; i < errorLocations.length; i++) {
let log_value = self.field.log(errorLocations[i] as i32)?;
@@ -145,62 +145,17 @@ impl ReedSolomonDecoder {
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(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(),
)))
}
};
let dltInverse = self.field.inverse(denominatorLeadingTerm)?;
while r.getDegree() >= rLast.getDegree() && !r.isZero() {
let degreeDiff = r.getDegree() - rLast.getDegree();
let scale = self
.field
.multiply(r.getCoefficient(r.getDegree()), dltInverse);
q = match q.addOrSubtract(&GenericGF::buildMonomial(self.field, degreeDiff, scale))
{
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(),
)))
}
};
r = match r.addOrSubtract(&match rLast.multiply_by_monomial(degreeDiff, scale) {
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(),
)))
}
}) {
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(),
)))
}
};
q = q.addOrSubtract(&GenericGF::buildMonomial(self.field, degreeDiff, scale))?;
r = r.addOrSubtract(&rLast.multiply_by_monomial(degreeDiff, scale)?)?;
}
t = match (match q.multiply(&tLast) {
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(),
)))
}
})
.addOrSubtract(&tLastLast)
{
Ok(res) => res,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(),
)))
}
};
t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?;
if r.getDegree() >= rLast.getDegree() {
return Err(Exceptions::ReedSolomonException(Some(format!(
@@ -245,14 +200,7 @@ impl ReedSolomonDecoder {
break;
}
if errorLocator.evaluateAt(i) == 0 {
result[e] = match self.field.inverse(i as i32) {
Ok(res) => res as usize,
Err(_err) => {
return Err(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(),
)))
}
};
result[e] = self.field.inverse(i as i32)? as usize;
e += 1;
}
}
@@ -268,13 +216,13 @@ impl ReedSolomonDecoder {
&self,
errorEvaluator: &GenericGFPoly,
errorLocations: &Vec<usize>,
) -> Vec<i32> {
) -> Result<Vec<i32>, Exceptions> {
// This is directly applying Forney's Formula
let s = errorLocations.len();
let mut result = vec![0; s];
for i in 0..s {
//for (int i = 0; i < s; i++) {
let xiInverse = self.field.inverse(errorLocations[i] as i32).unwrap();
let xiInverse = self.field.inverse(errorLocations[i] as i32)?;
let mut denominator = 1;
for (j, loc) in errorLocations.iter().enumerate().take(s) {
// for j in 0..s {
@@ -295,12 +243,12 @@ impl ReedSolomonDecoder {
}
result[i] = self.field.multiply(
errorEvaluator.evaluateAt(xiInverse as usize),
self.field.inverse(denominator).unwrap(),
self.field.inverse(denominator)?,
);
if self.field.getGeneratorBase() != 0 {
result[i] = self.field.multiply(result[i], xiInverse);
}
}
result
Ok(result)
}
}

View File

@@ -35,17 +35,17 @@ pub struct ReedSolomonEncoder {
}
impl ReedSolomonEncoder {
pub fn new(field: GenericGFRef) -> Self {
pub fn new(field: GenericGFRef) -> Result<Self, Exceptions> {
let n = field;
Self {
cachedGenerators: vec![GenericGFPoly::new(n, &[1]).unwrap()],
Ok(Self {
cachedGenerators: vec![GenericGFPoly::new(n, &[1])?],
field: n,
}
})
}
fn buildGenerator(&mut self, degree: usize) -> &GenericGFPoly {
fn buildGenerator(&mut self, degree: usize) -> Option<&GenericGFPoly> {
if degree >= self.cachedGenerators.len() {
let mut lastGenerator = self.cachedGenerators.last().unwrap();
let mut lastGenerator = self.cachedGenerators.last()?;
let cg_len = self.cachedGenerators.len();
let mut nextGenerator;
for d in cg_len..=degree {
@@ -59,16 +59,16 @@ impl ReedSolomonEncoder {
self.field.exp(d as i32 - 1 + self.field.getGeneratorBase()),
],
)
.unwrap(),
.ok()?,
)
.unwrap();
.ok()?;
self.cachedGenerators.push(nextGenerator);
lastGenerator = self.cachedGenerators.get(d).unwrap();
lastGenerator = self.cachedGenerators.get(d)?;
//lastGenerator = &nextGenerator;
}
}
let rv = self.cachedGenerators.get(degree).unwrap();
rv
let rv = self.cachedGenerators.get(degree)?;
Some(rv)
}
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> {
@@ -90,7 +90,9 @@ impl ReedSolomonEncoder {
//System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);
let mut info = GenericGFPoly::new(fld, &info_coefficients)?;
info = info.multiply_by_monomial(ec_bytes, 1)?;
let remainder = &info.divide(generator)?.1;
let remainder = &info
.divide(generator.ok_or(Exceptions::ReedSolomonException(None))?)?
.1;
let coefficients = remainder.getCoefficients();
let num_zero_coefficients = ec_bytes - coefficients.len();
for i in 0..num_zero_coefficients {

View File

@@ -14,12 +14,6 @@
* limitations under the License.
*/
// package com.google.zxing.common;
// import java.nio.charset.Charset;
// import java.nio.charset.StandardCharsets;
// import java.util.Map;
use encoding::{Encoding, EncodingRef};
use crate::{DecodeHintType, DecodeHintValue, DecodingHintDictionary};
@@ -71,20 +65,16 @@ impl StringUtils {
* "SJIS", "UTF8", "ISO8859_1", or the platform default encoding if none
* of these can possibly be correct
*/
pub fn guessEncoding(bytes: &[u8], hints: &DecodingHintDictionary) -> &'static str {
let c = StringUtils::guessCharset(bytes, hints);
if c.name()
== encoding::label::encoding_from_whatwg_label("SJIS")
.unwrap()
.name()
{
"SJIS"
pub fn guessEncoding(bytes: &[u8], hints: &DecodingHintDictionary) -> Option<&'static str> {
let c = StringUtils::guessCharset(bytes, hints)?;
if c.name() == encoding::label::encoding_from_whatwg_label("SJIS")?.name() {
Some("SJIS")
} else if c.name() == encoding::all::UTF_8.name() {
"UTF8"
Some("UTF8")
} else if c.name() == encoding::all::ISO_8859_1.name() {
"ISO8859_1"
Some("ISO8859_1")
} else {
c.name()
Some(c.name())
}
}
@@ -97,12 +87,12 @@ impl StringUtils {
* or the platform default encoding if
* none of these can possibly be correct
*/
pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> EncodingRef {
pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> Option<EncodingRef> {
if let Some(DecodeHintValue::CharacterSet(cs_name)) =
hints.get(&DecodeHintType::CHARACTER_SET)
{
// if let DecodeHintValue::CharacterSet(cs_name) = hint {
return encoding::label::encoding_from_whatwg_label(cs_name).unwrap();
return encoding::label::encoding_from_whatwg_label(cs_name);
// }
}
// if hints.contains_key(&DecodeHintType::CHARACTER_SET) {
@@ -114,9 +104,9 @@ impl StringUtils {
&& ((bytes[0] == 0xFE && bytes[1] == 0xFF) || (bytes[0] == 0xFF && bytes[1] == 0xFE))
{
if bytes[0] == 0xFE && bytes[1] == 0xFF {
return encoding::all::UTF_16BE;
return Some(encoding::all::UTF_16BE);
} else {
return encoding::all::UTF_16LE;
return Some(encoding::all::UTF_16LE);
}
}
@@ -234,7 +224,7 @@ impl StringUtils {
// Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done
if can_be_utf8 && (utf8bom || utf2_bytes_chars + utf3_bytes_chars + utf4_bytes_chars > 0) {
return encoding::all::UTF_8;
return Some(encoding::all::UTF_8);
}
// Easy -- if assuming Shift_JIS or >= 3 valid consecutive not-ascii characters (and no evidence it can't be), done
if can_be_shift_jis
@@ -242,7 +232,7 @@ impl StringUtils {
|| sjis_max_katakana_word_length >= 3
|| sjis_max_double_bytes_word_length >= 3)
{
return encoding::label::encoding_from_whatwg_label("SJIS").unwrap();
return encoding::label::encoding_from_whatwg_label("SJIS");
}
// Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is:
// - If we saw
@@ -253,23 +243,23 @@ impl StringUtils {
return if (sjis_max_katakana_word_length == 2 && sjis_katakana_chars == 2)
|| iso_high_other * 10 >= length
{
encoding::label::encoding_from_whatwg_label("SJIS").unwrap()
encoding::label::encoding_from_whatwg_label("SJIS")
} else {
encoding::all::ISO_8859_1
Some(encoding::all::ISO_8859_1)
};
}
// Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding
if can_be_iso88591 {
return encoding::all::ISO_8859_1;
return Some(encoding::all::ISO_8859_1);
}
if can_be_shift_jis {
return encoding::label::encoding_from_whatwg_label("SJIS").unwrap();
return Some(encoding::label::encoding_from_whatwg_label("SJIS").unwrap());
}
if can_be_utf8 {
return encoding::all::UTF_8;
return Some(encoding::all::UTF_8);
}
// Otherwise, we take a wild guess with platform encoding
encoding::all::UTF_8
Some(encoding::all::UTF_8)
}
}