Implement clippy suggestions

This commit is contained in:
Henry Schimke
2023-01-04 14:48:16 -06:00
parent c65eadf102
commit 48287631dd
196 changed files with 2465 additions and 2574 deletions

View File

@@ -26,8 +26,8 @@ image = {version = "0.24", optional = true}
imageproc = {version = "0.23.0", optional = true} imageproc = {version = "0.23.0", optional = true}
unicode-segmentation = "1.10.0" unicode-segmentation = "1.10.0"
codepage-437 = "0.1.0" codepage-437 = "0.1.0"
rxing-one-d-proc-derive = "0.2" #rxing-one-d-proc-derive = "0.2.1"
#rxing-one-d-proc-derive = {path ="../rxing-one-d-proc-derive"} rxing-one-d-proc-derive = {path ="../rxing-one-d-proc-derive"}
num = "0.4.0" num = "0.4.0"
[dev-dependencies] [dev-dependencies]

View File

@@ -32,7 +32,7 @@ const SRC_DATA: [u32; 9] = [
#[test] #[test]
fn testCrop() { fn testCrop() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref());
assert!(SOURCE.isCropSupported()); assert!(SOURCE.isCropSupported());
let cropped = SOURCE.crop(1, 1, 1, 1).unwrap(); let cropped = SOURCE.crop(1, 1, 1, 1).unwrap();
@@ -43,7 +43,7 @@ fn testCrop() {
#[test] #[test]
fn testMatrix() { fn testMatrix() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref());
assert_eq!( assert_eq!(
vec![0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F], vec![0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F],
@@ -60,7 +60,7 @@ fn testMatrix() {
#[test] #[test]
fn testGetRow() { fn testGetRow() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec()); let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, SRC_DATA.as_ref());
assert_eq!(vec![0x3F, 0x7F, 0x3F], SOURCE.getRow(2)); assert_eq!(vec![0x3F, 0x7F, 0x3F], SOURCE.getRow(2));
} }

View File

@@ -101,14 +101,30 @@ fn test_error_in_parameter_locator(data: &str) {
clone(&matrix) clone(&matrix)
}; };
copy.flip_coords( copy.flip_coords(
orientation_points.get(error1).unwrap().get_x().abs() as u32, orientation_points
orientation_points.get(error1).unwrap().get_y().abs() as u32, .get(error1)
.unwrap()
.get_x()
.unsigned_abs(),
orientation_points
.get(error1)
.unwrap()
.get_y()
.unsigned_abs(),
); );
if error2 > error1 { if error2 > error1 {
// if error2 == error1, we only test a single error // if error2 == error1, we only test a single error
copy.flip_coords( copy.flip_coords(
orientation_points.get(error2).unwrap().get_x().abs() as u32, orientation_points
orientation_points.get(error2).unwrap().get_y().abs() as u32, .get(error2)
.unwrap()
.get_x()
.unsigned_abs(),
orientation_points
.get(error2)
.unwrap()
.get_y()
.unsigned_abs(),
); );
} }
// dbg!(copy.to_string()); // dbg!(copy.to_string());
@@ -180,7 +196,7 @@ fn make_larger(input: &BitMatrix, factor: u32) -> BitMatrix {
} }
} }
} }
return output; output
} }
// Returns a list of the four rotations of the BitMatrix. // Returns a list of the four rotations of the BitMatrix.
@@ -209,7 +225,7 @@ fn rotate_right(input: &BitMatrix) -> BitMatrix {
} }
} }
} }
return result; result
} }
// Returns the transpose of a bit matrix, which is equivalent to rotating the // Returns the transpose of a bit matrix, which is equivalent to rotating the
@@ -226,7 +242,7 @@ fn transpose(input: &BitMatrix) -> BitMatrix {
} }
} }
} }
return result; result
} }
fn clone(input: &BitMatrix) -> BitMatrix { fn clone(input: &BitMatrix) -> BitMatrix {
@@ -268,7 +284,7 @@ fn get_orientation_points(code: &AztecCode) -> Vec<Point> {
} }
xSign += 2; xSign += 2;
} }
return result; result
} }
const TEST_BARCODE: &str = r" X X X X X X X X X X X X X X X X X X X X X X X X X const TEST_BARCODE: &str = r" X X X X X X X X X X X X X X X X X X X X X X X X X

View File

@@ -446,16 +446,12 @@ fn testHighLevelEncodeBinary() {
let expected_length = (8 * i) let expected_length = (8 * i)
+ if i <= 31 { + if i <= 31 {
10 10
} else { } else if i <= 62 {
if i <= 62 {
20 20
} else { } else if i <= 2078 {
if i <= 2078 {
21 21
} else { } else {
31 31
}
}
}; };
// ( (i <= 31) ? 10 : (i <= 62) ? 20 : (i <= 2078) ? 21 : 31); // ( (i <= 31) ? 10 : (i <= 62) ? 20 : (i <= 2078) ? 21 : 31);
// Verify that we are correct about the length. // Verify that we are correct about the length.

View File

@@ -53,8 +53,7 @@ impl Reader for AztecReader {
// let notFoundException = None; // let notFoundException = None;
// let formatException = None; // let formatException = None;
let mut detector = Detector::new(image.getBlackMatrix()); let mut detector = Detector::new(image.getBlackMatrix());
let points;
let decoderRXingResult: DecoderRXingResult;
// try { // try {
let detectorRXingResult = if let Ok(det) = detector.detect(false) { let detectorRXingResult = if let Ok(det) = detector.detect(false) {
@@ -62,13 +61,11 @@ impl Reader for AztecReader {
} else if let Ok(det) = detector.detect(true) { } else if let Ok(det) = detector.detect(true) {
det det
} else { } else {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(None));
"barcode not found".to_owned(),
));
}; };
points = detectorRXingResult.getPoints(); let points = detectorRXingResult.getPoints();
decoderRXingResult = decoder::decode(&detectorRXingResult)?; let decoderRXingResult: DecoderRXingResult = decoder::decode(&detectorRXingResult)?;
// } catch (NotFoundException e) { // } catch (NotFoundException e) {
// notFoundException = e; // notFoundException = e;
// } catch (FormatException e) { // } catch (FormatException e) {

View File

@@ -106,10 +106,10 @@ fn encode(
layers: i32, layers: i32,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix, Exceptions> {
if format != BarcodeFormat::AZTEC { if format != BarcodeFormat::AZTEC {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can only encode AZTEC, but got {:?}", "Can only encode AZTEC, but got {:?}",
format format
))); ))));
} }
let aztec = if let Some(cset) = charset { let aztec = if let Some(cset) = charset {
// dbg!(cset.name(), cset.whatwg_name()); // dbg!(cset.name(), cset.whatwg_name());

View File

@@ -35,12 +35,12 @@ use super::AztecDetectorResult::AztecDetectorRXingResult;
#[derive(PartialEq, Eq, Copy, Clone)] #[derive(PartialEq, Eq, Copy, Clone)]
enum Table { enum Table {
UPPER, Upper,
LOWER, Lower,
MIXED, Mixed,
DIGIT, Digit,
PUNCT, Punct,
BINARY, Binary,
} }
const UPPER_TABLE: [&str; 32] = [ const UPPER_TABLE: [&str; 32] = [
@@ -78,8 +78,8 @@ pub fn decode(
) -> Result<DecoderRXingResult, Exceptions> { ) -> Result<DecoderRXingResult, Exceptions> {
//let mut detectorRXingResult = detectorRXingResult.clone(); //let mut detectorRXingResult = detectorRXingResult.clone();
let matrix = detectorRXingResult.getBits(); let matrix = detectorRXingResult.getBits();
let rawbits = extract_bits(&detectorRXingResult, matrix); let rawbits = extract_bits(detectorRXingResult, matrix);
let corrected_bits = correct_bits(&detectorRXingResult, &rawbits)?; let corrected_bits = correct_bits(detectorRXingResult, &rawbits)?;
let raw_bytes = convertBoolArrayToByteArray(&corrected_bits.correct_bits); let raw_bytes = convertBoolArrayToByteArray(&corrected_bits.correct_bits);
let result = get_encoded_data(&corrected_bits.correct_bits); let result = get_encoded_data(&corrected_bits.correct_bits);
let mut decoder_rxing_result = DecoderRXingResult::new( let mut decoder_rxing_result = DecoderRXingResult::new(
@@ -105,8 +105,8 @@ pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String, Exceptions> {
*/ */
fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> { fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
let end_index = corrected_bits.len(); let end_index = corrected_bits.len();
let mut latch_table = Table::UPPER; // table most recently latched to let mut latch_table = Table::Upper; // table most recently latched to
let mut shift_table = Table::UPPER; // table to use for the next read let mut shift_table = Table::Upper; // table to use for the next read
// Final decoded string result // Final decoded string result
// (correctedBits-5) / 4 is an upper bound on the size (all-digit result) // (correctedBits-5) / 4 is an upper bound on the size (all-digit result)
@@ -121,7 +121,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
let mut index = 0; let mut index = 0;
'main: while index < end_index { 'main: while index < end_index {
if shift_table == Table::BINARY { if shift_table == Table::Binary {
if end_index - index < 5 { if end_index - index < 5 {
break; break;
} }
@@ -147,7 +147,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
// Go back to whatever mode we had been in // Go back to whatever mode we had been in
shift_table = latch_table; shift_table = latch_table;
} else { } else {
let size = if shift_table == Table::DIGIT { 4 } else { 5 }; let size = if shift_table == Table::Digit { 4 } else { 5 };
if end_index - index < size { if end_index - index < size {
break; break;
} }
@@ -171,9 +171,9 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
match n { match n {
0 => result.push(29 as char), // translate FNC1 as ASCII 29 0 => result.push(29 as char), // translate FNC1 as ASCII 29
7 => { 7 => {
return Err(Exceptions::FormatException( return Err(Exceptions::FormatException(Some(
"FLG(7) is reserved and illegal".to_owned(), "FLG(7) is reserved and illegal".to_owned(),
)) )))
} // FLG(7) is reserved and illegal } // FLG(7) is reserved and illegal
_ => { _ => {
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode // ECI is decimal integer encoded as 1-6 codes in DIGIT mode
@@ -185,19 +185,19 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
//while (n-- > 0) { //while (n-- > 0) {
let next_digit = read_code(corrected_bits, index, 4); let next_digit = read_code(corrected_bits, index, 4);
index += 4; index += 4;
if next_digit < 2 || next_digit > 11 { if !(2..=11).contains(&next_digit) {
return Err(Exceptions::FormatException( return Err(Exceptions::FormatException(Some(
"Not a decimal digit".to_owned(), "Not a decimal digit".to_owned(),
)); // Not a decimal digit ))); // Not a decimal digit
} }
eci = eci * 10 + (next_digit - 2); eci = eci * 10 + (next_digit - 2);
n -= 1; n -= 1;
} }
let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci); let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci);
if charset_eci.is_err() { if charset_eci.is_err() {
return Err(Exceptions::FormatException( return Err(Exceptions::FormatException(Some(
"Charset must exist".to_owned(), "Charset must exist".to_owned(),
)); )));
} }
encdr = CharacterSetECI::getCharset(&charset_eci?); encdr = CharacterSetECI::getCharset(&charset_eci?);
} }
@@ -232,7 +232,9 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) { if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) {
result.push_str(&str); result.push_str(&str);
} else { } else {
return Err(Exceptions::IllegalStateException("bad encoding".to_owned())); return Err(Exceptions::IllegalStateException(Some(
"bad encoding".to_owned(),
)));
} }
// result.push_str(decodedBytes.toString(encoding.name())); // result.push_str(decodedBytes.toString(encoding.name()));
//} catch (UnsupportedEncodingException uee) { //} catch (UnsupportedEncodingException uee) {
@@ -247,12 +249,12 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
*/ */
fn getTable(t: char) -> Table { fn getTable(t: char) -> Table {
match t { match t {
'L' => Table::LOWER, 'L' => Table::Lower,
'P' => Table::PUNCT, 'P' => Table::Punct,
'M' => Table::MIXED, 'M' => Table::Mixed,
'D' => Table::DIGIT, 'D' => Table::Digit,
'B' => Table::BINARY, 'B' => Table::Binary,
_ => Table::UPPER, _ => Table::Upper,
} }
// switch (t) { // switch (t) {
// case 'L': // case 'L':
@@ -279,12 +281,14 @@ fn getTable(t: char) -> Table {
*/ */
fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> { fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> {
match table { match table {
Table::UPPER => Ok(UPPER_TABLE[code as usize]), Table::Upper => Ok(UPPER_TABLE[code as usize]),
Table::LOWER => Ok(LOWER_TABLE[code as usize]), Table::Lower => Ok(LOWER_TABLE[code as usize]),
Table::MIXED => Ok(MIXED_TABLE[code as usize]), Table::Mixed => Ok(MIXED_TABLE[code as usize]),
Table::DIGIT => Ok(DIGIT_TABLE[code as usize]), Table::Digit => Ok(DIGIT_TABLE[code as usize]),
Table::PUNCT => Ok(PUNCT_TABLE[code as usize]), Table::Punct => Ok(PUNCT_TABLE[code as usize]),
_ => Err(Exceptions::IllegalStateException("Bad table".to_owned())), _ => Err(Exceptions::IllegalStateException(Some(
"Bad table".to_owned(),
))),
} }
// switch (table) { // switch (table) {
// case UPPER: // case UPPER:
@@ -345,17 +349,18 @@ fn correct_bits(
let num_data_codewords = ddata.getNbDatablocks(); let num_data_codewords = ddata.getNbDatablocks();
let num_codewords = rawbits.len() / codeword_size; let num_codewords = rawbits.len() / codeword_size;
if num_codewords < num_data_codewords as usize { if num_codewords < num_data_codewords as usize {
return Err(Exceptions::FormatException(format!( return Err(Exceptions::FormatException(Some(format!(
"numCodewords {}< numDataCodewords{}", "numCodewords {}< numDataCodewords{}",
num_codewords, num_data_codewords num_codewords, num_data_codewords
))); ))));
} }
let mut offset = rawbits.len() % codeword_size; let mut offset = rawbits.len() % codeword_size;
let mut data_words = vec![0i32; num_codewords]; let mut data_words = vec![0i32; num_codewords];
for i in 0..num_codewords { for word in data_words.iter_mut().take(num_codewords) {
// for i in 0..num_codewords {
// for (int i = 0; i < numCodewords; i++, offset += codewordSize) { // for (int i = 0; i < numCodewords; i++, offset += codewordSize) {
data_words[i] = read_code(rawbits, offset, codeword_size) as i32; *word = read_code(rawbits, offset, codeword_size) as i32;
offset += codeword_size; offset += codeword_size;
} }
@@ -373,15 +378,14 @@ fn correct_bits(
// First, count how many bits are going to be thrown out as stuffing // First, count how many bits are going to be thrown out as stuffing
let mask = (1 << codeword_size) - 1; let mask = (1 << codeword_size) - 1;
let mut stuffed_bits = 0; let mut stuffed_bits = 0;
for i in 0..num_data_codewords as usize { for data_word in data_words.iter().take(num_data_codewords as usize) {
// for i in 0..num_data_codewords as usize {
// for (int i = 0; i < numDataCodewords; i++) { // for (int i = 0; i < numDataCodewords; i++) {
let data_word = data_words[i]; // let data_word = data_words[i];
if data_word == 0 || data_word == mask { if data_word == &0 || data_word == &mask {
return Err(Exceptions::FormatException( return Err(Exceptions::FormatException(None));
"dataWord == 0 || dataWord == mask".to_owned(),
));
//throw FormatException.getFormatInstance(); //throw FormatException.getFormatInstance();
} else if data_word == 1 || data_word == mask - 1 { } else if data_word == &1 || data_word == &(mask - 1) {
stuffed_bits += 1; stuffed_bits += 1;
} }
} }
@@ -389,21 +393,22 @@ fn correct_bits(
let mut corrected_bits = let mut corrected_bits =
vec![false; (num_data_codewords * codeword_size as u32 - stuffed_bits) as usize]; vec![false; (num_data_codewords * codeword_size as u32 - stuffed_bits) as usize];
let mut index = 0; let mut index = 0;
for i in 0..num_data_codewords as usize { for data_word in data_words.iter().take(num_data_codewords as usize) {
// for i in 0..num_data_codewords as usize {
// for (int i = 0; i < numDataCodewords; i++) { // for (int i = 0; i < numDataCodewords; i++) {
let data_word = data_words[i]; // let data_word = data_words[i];
if data_word == 1 || data_word == mask - 1 { if *data_word == 1 || *data_word == mask - 1 {
// next codewordSize-1 bits are all zeros or all ones // next codewordSize-1 bits are all zeros or all ones
corrected_bits.splice( corrected_bits.splice(
index..index + codeword_size - 1, index..index + codeword_size - 1,
vec![data_word > 1; codeword_size - 1], vec![*data_word > 1; codeword_size - 1],
); );
// Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1); // Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
index += codeword_size - 1; index += codeword_size - 1;
} else { } else {
for bit in (0..codeword_size).rev() { for bit in (0..codeword_size).rev() {
// for (int bit = codewordSize - 1; bit >= 0; --bit) { // for (int bit = codewordSize - 1; bit >= 0; --bit) {
corrected_bits[index] = (data_word & (1 << bit)) != 0; corrected_bits[index] = (*data_word & (1 << bit)) != 0;
index += 1; index += 1;
} }
} }
@@ -428,9 +433,9 @@ fn extract_bits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<boo
let mut rawbits = vec![false; total_bits_in_layer(layers as usize, compact)]; let mut rawbits = vec![false; total_bits_in_layer(layers as usize, compact)];
if compact { if compact {
for i in 0..alignment_map.len() { for (i, am) in alignment_map.iter_mut().enumerate() {
// for (int i = 0; i < alignmentMap.length; i++) { // for (int i = 0; i < alignmentMap.length; i++) {
alignment_map[i] = i as u32; *am = i as u32;
} }
} else { } else {
let matrix_size = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15); let matrix_size = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15);
@@ -481,7 +486,7 @@ fn extract_bits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<boo
} }
row_offset += row_size * 8; row_offset += row_size * 8;
} }
return rawbits; rawbits
} }
/** /**
@@ -489,14 +494,15 @@ fn extract_bits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<boo
*/ */
fn read_code(rawbits: &[bool], start_index: usize, length: usize) -> u32 { fn read_code(rawbits: &[bool], start_index: usize, length: usize) -> u32 {
let mut res = 0; let mut res = 0;
for i in start_index..start_index + length { for bit in rawbits.iter().skip(start_index).take(length) {
// for i in start_index..start_index + length {
// for (int i = startIndex; i < startIndex + length; i++) { // for (int i = startIndex; i < startIndex + length; i++) {
res <<= 1; res <<= 1;
if rawbits[i] { if *bit {
res |= 0x01; res |= 0x01;
} }
} }
return res; res
} }
/** /**
@@ -507,7 +513,7 @@ fn read_byte(rawbits: &[bool], start_index: usize) -> u8 {
if n >= 8 { if n >= 8 {
return read_code(rawbits, start_index, 8) as u8; return read_code(rawbits, start_index, 8) as u8;
} }
return (read_code(rawbits, start_index, n) << (8 - n)) as u8; (read_code(rawbits, start_index, n) << (8 - n)) as u8
} }
/** /**
@@ -515,11 +521,12 @@ fn read_byte(rawbits: &[bool], start_index: usize) -> u8 {
*/ */
pub fn convertBoolArrayToByteArray(bool_arr: &[bool]) -> Vec<u8> { pub fn convertBoolArrayToByteArray(bool_arr: &[bool]) -> Vec<u8> {
let mut byte_arr = vec![0u8; (bool_arr.len() + 7) / 8]; let mut byte_arr = vec![0u8; (bool_arr.len() + 7) / 8];
for i in 0..byte_arr.len() { // for i in 0..byte_arr.len() {
for (i, byte) in byte_arr.iter_mut().enumerate() {
// for (int i = 0; i < byteArr.length; i++) { // for (int i = 0; i < byteArr.length; i++) {
byte_arr[i] = read_byte(bool_arr, 8 * i); *byte = read_byte(bool_arr, 8 * i);
} }
return byte_arr; byte_arr
} }
fn total_bits_in_layer(layers: usize, compact: bool) -> usize { fn total_bits_in_layer(layers: usize, compact: bool) -> usize {

View File

@@ -93,7 +93,7 @@ impl<'a> Detector<'_> {
// 4. Sample the grid // 4. Sample the grid
let bits = self.sample_grid( let bits = self.sample_grid(
&self.image, self.image,
&bulls_eye_corners[self.shift as usize % 4], &bulls_eye_corners[self.shift as usize % 4],
&bulls_eye_corners[(self.shift as usize + 1) % 4], &bulls_eye_corners[(self.shift as usize + 1) % 4],
&bulls_eye_corners[(self.shift as usize + 2) % 4], &bulls_eye_corners[(self.shift as usize + 2) % 4],
@@ -127,7 +127,9 @@ impl<'a> Detector<'_> {
|| !self.is_valid(&bulls_eye_corners[2]) || !self.is_valid(&bulls_eye_corners[2])
|| !self.is_valid(&bulls_eye_corners[3]) || !self.is_valid(&bulls_eye_corners[3])
{ {
return Err(Exceptions::NotFoundException("no valid points".to_owned())); return Err(Exceptions::NotFoundException(Some(
"no valid points".to_owned(),
)));
} }
let length = 2 * self.nb_center_layers; let length = 2 * self.nb_center_layers;
// Get the bits around the bull's eye // Get the bits around the bull's eye
@@ -208,7 +210,9 @@ impl<'a> Detector<'_> {
return Ok(shift); return Ok(shift);
} }
} }
Err(Exceptions::NotFoundException("rotation failure".to_owned())) Err(Exceptions::NotFoundException(Some(
"rotation failure".to_owned(),
)))
} }
/** /**
@@ -302,8 +306,7 @@ impl<'a> Detector<'_> {
// &pind.to_rxing_result_point(), // &pind.to_rxing_result_point(),
// &pina.to_rxing_result_point(), // &pina.to_rxing_result_point(),
// ) * (nbCenterLayers + 2) as f32); // ) * (nbCenterLayers + 2) as f32);
if q < 0.75 if !(0.75..=1.25).contains(&q)
|| q > 1.25
|| !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd) || !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd)
{ {
break; break;
@@ -321,7 +324,7 @@ impl<'a> Detector<'_> {
} }
if self.nb_center_layers != 5 && self.nb_center_layers != 7 { if self.nb_center_layers != 5 && self.nb_center_layers != 7 {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
self.compact = self.nb_center_layers == 5; self.compact = self.nb_center_layers == 5;
@@ -360,7 +363,7 @@ impl<'a> Detector<'_> {
let mut fnd = false; let mut fnd = false;
//Get a white rectangle that can be the border of the matrix in center bull's eye or //Get a white rectangle that can be the border of the matrix in center bull's eye or
if let Ok(wrd) = WhiteRectangleDetector::new_from_image(&self.image) { if let Ok(wrd) = WhiteRectangleDetector::new_from_image(self.image) {
if let Ok(cornerPoints) = wrd.detect() { if let Ok(cornerPoints) = wrd.detect() {
point_a = cornerPoints[0]; point_a = cornerPoints[0];
point_b = cornerPoints[1]; point_b = cornerPoints[1];
@@ -421,7 +424,7 @@ impl<'a> Detector<'_> {
// This will ensure that we end up with a white rectangle in center bull's eye // This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center. // in order to compute a more accurate center.
let mut fnd = false; let mut fnd = false;
if let Ok(wrd) = WhiteRectangleDetector::new(&self.image, 15, cx, cy) { if let Ok(wrd) = WhiteRectangleDetector::new(self.image, 15, cx, cy) {
if let Ok(cornerPoints) = wrd.detect() { if let Ok(cornerPoints) = wrd.detect() {
point_a = cornerPoints[0]; point_a = cornerPoints[0];
point_b = cornerPoints[1]; point_b = cornerPoints[1];
@@ -557,7 +560,7 @@ impl<'a> Detector<'_> {
result |= 1 << (size - i - 1); result |= 1 << (size - i - 1);
} }
} }
return result; result
} }
/** /**
@@ -607,7 +610,7 @@ impl<'a> Detector<'_> {
let c = self.get_color(&p3, &p4); let c = self.get_color(&p3, &p4);
return c == c_init; c == c_init
} }
/** /**

View File

@@ -171,25 +171,25 @@ pub fn encode_bytes_with_charset(
MAX_NB_BITS MAX_NB_BITS
}) })
{ {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal value {} for layers", "Illegal value {} for layers",
user_specified_layers user_specified_layers
))); ))));
} }
total_bits_in_layer_var = total_bits_in_layer(layers, compact); total_bits_in_layer_var = total_bits_in_layer(layers, compact);
word_size = WORD_SIZE[layers as usize]; word_size = WORD_SIZE[layers as usize];
let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size); let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size);
stuffed_bits = stuffBits(&bits, word_size as usize); stuffed_bits = stuffBits(&bits, word_size as usize);
if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers { if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Data to large for user specified layer".to_owned(), "Data to large for user specified layer".to_owned(),
)); )));
} }
if compact && stuffed_bits.getSize() as u32 > word_size * 64 { if compact && stuffed_bits.getSize() as u32 > word_size * 64 {
// Compact format only allows 64 data words, though C4 can hold more words than that // Compact format only allows 64 data words, though C4 can hold more words than that
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Data to large for user specified layer".to_owned(), "Data to large for user specified layer".to_owned(),
)); )));
} }
} else { } else {
word_size = 0; word_size = 0;
@@ -201,14 +201,14 @@ pub fn encode_bytes_with_charset(
loop { loop {
// for (int i = 0; ; i++) { // for (int i = 0; ; i++) {
if i > MAX_NB_BITS { if i > MAX_NB_BITS {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Data too large for an Aztec code".to_owned(), "Data too large for an Aztec code".to_owned(),
)); )));
} }
compact = i <= 3; compact = i <= 3;
layers = if compact { i + 1 } else { i }; layers = if compact { i + 1 } else { i };
total_bits_in_layer_var = total_bits_in_layer(layers, compact); total_bits_in_layer_var = total_bits_in_layer(layers, compact);
if total_size_bits > total_bits_in_layer_var as u32 { if total_size_bits > total_bits_in_layer_var {
i += 1; i += 1;
continue; continue;
} }
@@ -239,7 +239,7 @@ pub fn encode_bytes_with_charset(
// generate mode message // generate mode message
let messageSizeInWords = stuffed_bits.getSize() as u32 / word_size; let messageSizeInWords = stuffed_bits.getSize() as u32 / word_size;
let modeMessage = generateModeMessage(compact, layers as u32, messageSizeInWords); let modeMessage = generateModeMessage(compact, layers, messageSizeInWords);
// allocate symbol // allocate symbol
let baseMatrixSize = (if compact { 11 } else { 14 }) + layers * 4; // not including alignment lines let baseMatrixSize = (if compact { 11 } else { 14 }) + layers * 4; // not including alignment lines
@@ -248,10 +248,8 @@ pub fn encode_bytes_with_charset(
if compact { if compact {
// no alignment marks in compact mode, alignmentMap is a no-op // no alignment marks in compact mode, alignmentMap is a no-op
matrixSize = baseMatrixSize; matrixSize = baseMatrixSize;
for i in 0..alignmentMap.len() { // for i in 0..alignmentMap.len() {
// for (int i = 0; i < alignmentMap.length; i++) { alignmentMap[..].copy_from_slice(&(0..baseMatrixSize).collect::<Vec<u32>>()[..]);
alignmentMap[i] = i as u32;
}
} else { } else {
matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15); matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15);
let origCenter = (baseMatrixSize / 2) as usize; let origCenter = (baseMatrixSize / 2) as usize;
@@ -259,11 +257,11 @@ pub fn encode_bytes_with_charset(
for i in 0..origCenter { for i in 0..origCenter {
// for (int i = 0; i < origCenter; i++) { // for (int i = 0; i < origCenter; i++) {
let newOffset = (i + i / 15) as u32; let newOffset = (i + i / 15) as u32;
alignmentMap[origCenter - i - 1] = center as u32 - newOffset - 1; alignmentMap[origCenter - i - 1] = center - newOffset - 1;
alignmentMap[origCenter + i] = center as u32 + newOffset + 1; alignmentMap[origCenter + i] = center + newOffset + 1;
} }
} }
let mut matrix = BitMatrix::with_single_dimension(matrixSize as u32); let mut matrix = BitMatrix::with_single_dimension(matrixSize);
// dbg!(matrix.to_string()); // dbg!(matrix.to_string());
@@ -306,25 +304,25 @@ pub fn encode_bytes_with_charset(
// dbg!(matrix.to_string()); // dbg!(matrix.to_string());
// draw mode message // draw mode message
drawModeMessage(&mut matrix, compact, matrixSize as u32, modeMessage); drawModeMessage(&mut matrix, compact, matrixSize, modeMessage);
// dbg!(matrix.to_string()); // dbg!(matrix.to_string());
// draw alignment marks // draw alignment marks
if compact { if compact {
drawBullsEye(&mut matrix, matrixSize as u32 / 2, 5); drawBullsEye(&mut matrix, matrixSize / 2, 5);
} else { } else {
drawBullsEye(&mut matrix, matrixSize as u32 / 2, 7); drawBullsEye(&mut matrix, matrixSize / 2, 7);
let mut i = 0; let mut i = 0;
let mut j = 0; let mut j = 0;
while i < baseMatrixSize / 2 - 1 { while i < baseMatrixSize / 2 - 1 {
let mut k = (matrixSize / 2) & 1; let mut k = (matrixSize / 2) & 1;
while k < matrixSize { while k < matrixSize {
// for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) { // for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) {
matrix.set(matrixSize as u32 / 2 - j, k as u32); matrix.set(matrixSize / 2 - j, k);
matrix.set(matrixSize as u32 / 2 + j, k as u32); matrix.set(matrixSize / 2 + j, k);
matrix.set(k as u32, matrixSize as u32 / 2 - j); matrix.set(k, matrixSize / 2 - j);
matrix.set(k as u32, matrixSize as u32 / 2 + j); matrix.set(k, matrixSize / 2 + j);
k += 2; k += 2;
} }
@@ -344,13 +342,7 @@ pub fn encode_bytes_with_charset(
// dbg!(matrix.to_string()); // dbg!(matrix.to_string());
let aztec = AztecCode::new( let aztec = AztecCode::new(compact, matrixSize, layers, messageSizeInWords, matrix);
compact,
matrixSize as u32,
layers,
messageSizeInWords as u32,
matrix,
);
// aztec.setCompact(compact); // aztec.setCompact(compact);
// aztec.setSize(matrixSize); // aztec.setSize(matrixSize);
// aztec.setLayers(layers); // aztec.setLayers(layers);
@@ -399,7 +391,7 @@ pub fn generateModeMessage(compact: bool, layers: u32, messageSizeInWords: u32)
.expect("should append"); .expect("should append");
mode_message = generateCheckWords(&mode_message, 40, 4); mode_message = generateCheckWords(&mode_message, 40, 4);
} }
return mode_message; mode_message
} }
fn drawModeMessage(matrix: &mut BitMatrix, compact: bool, matrixSize: u32, modeMessage: BitArray) { fn drawModeMessage(matrix: &mut BitMatrix, compact: bool, matrixSize: u32, modeMessage: BitArray) {
@@ -459,7 +451,7 @@ fn generateCheckWords(bitArray: &BitArray, totalBits: usize, wordSize: usize) ->
.expect("must append"); .expect("must append");
} }
// dbg!(message_bits.to_string()); // dbg!(message_bits.to_string());
return message_bits; message_bits
} }
fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Vec<i32> { fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Vec<i32> {
@@ -472,7 +464,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve
for j in 0..wordSize { for j in 0..wordSize {
// for (int j = 0; j < wordSize; j++) { // for (int j = 0; j < wordSize; j++) {
value |= if stuffedBits.get(i * wordSize + j) { value |= if stuffedBits.get(i * wordSize + j) {
1 << wordSize - j - 1 1 << (wordSize - j - 1)
} else { } else {
0 0
}; };
@@ -481,7 +473,7 @@ fn bitsToWords(stuffedBits: &BitArray, wordSize: usize, totalWords: usize) -> Ve
i += 1; i += 1;
} }
return message; message
} }
fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> { fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> {
@@ -491,10 +483,10 @@ fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> {
8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)), 8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)),
10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)), 10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)),
12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)), 12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)),
_ => Err(Exceptions::IllegalArgumentException(format!( _ => Err(Exceptions::IllegalArgumentException(Some(format!(
"Unsupported word size {}", "Unsupported word size {}",
wordSize wordSize
))), )))),
} }
// switch (wordSize) { // switch (wordSize) {
// case 4: // case 4:
@@ -539,7 +531,7 @@ pub fn stuffBits(bits: &BitArray, word_size: usize) -> BitArray {
i += word_size as isize; i += word_size as isize;
} }
return out; out
} }
fn total_bits_in_layer(layers: u32, compact: bool) -> u32 { fn total_bits_in_layer(layers: u32, compact: bool) -> u32 {

View File

@@ -14,8 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
use std::cmp::Ordering;
use crate::{ use crate::{
common::{BitArray, CharacterSetECI}, common::{BitArray, CharacterSetECI},
exceptions::Exceptions, exceptions::Exceptions,
@@ -250,9 +248,9 @@ impl HighLevelEncoder {
initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?; initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?;
} }
} else { } else {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"No ECI code for character set".to_owned(), "No ECI code for character set".to_owned(),
)); )));
} }
// if self.charset != null { // if self.charset != null {
// CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset); // CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset);
@@ -266,13 +264,13 @@ impl HighLevelEncoder {
while index < self.text.len() { while index < self.text.len() {
// for index in 0..self.text.len() { // for index in 0..self.text.len() {
// for (int index = 0; index < text.length; index++) { // for (int index = 0; index < text.length; index++) {
let pair_code;
let next_char = if index + 1 < self.text.len() { let next_char = if index + 1 < self.text.len() {
self.text[index + 1] self.text[index + 1]
} else { } else {
0 0
}; };
pair_code = match self.text[index] { let pair_code = match self.text[index] {
b'\r' if next_char == b'\n' => 2, b'\r' if next_char == b'\n' => 2,
b'.' if next_char == b' ' => 3, b'.' if next_char == b' ' => 3,
b',' if next_char == b' ' => 4, b',' if next_char == b' ' => 4,
@@ -301,13 +299,19 @@ impl HighLevelEncoder {
.into_iter() .into_iter()
.min_by(|a, b| { .min_by(|a, b| {
let diff: i64 = a.getBitCount() as i64 - b.getBitCount() as i64; let diff: i64 = a.getBitCount() as i64 - b.getBitCount() as i64;
if diff < 0 { diff.cmp(&0)
Ordering::Less // match diff {
} else if diff == 0 { // ..0 => Ordering::Less,
Ordering::Equal // 0 => Ordering::Equal,
} else { // 0.. => Ordering::Greater,
Ordering::Greater // }
} // if diff < 0 {
// Ordering::Less
// } else if diff == 0 {
// Ordering::Equal
// } else {
// Ordering::Greater
// }
// a.getBitCount() - b.getBitCount() // a.getBitCount() - b.getBitCount()
}) })
.unwrap(); .unwrap();
@@ -344,7 +348,7 @@ impl HighLevelEncoder {
let mut state_no_binary = None; let mut state_no_binary = None;
for mode in 0..=Self::MODE_PUNCT { for mode in 0..=Self::MODE_PUNCT {
// for (int mode = 0; mode <= MODE_PUNCT; mode++) { // for (int mode = 0; mode <= MODE_PUNCT; mode++) {
let char_in_mode = Self::CHAR_MAP[mode as usize][ch as usize]; let char_in_mode = Self::CHAR_MAP[mode][ch as usize];
if char_in_mode > 0 { if char_in_mode > 0 {
if state_no_binary.is_none() { if state_no_binary.is_none() {
// Only create stateNoBinary the first time it's required. // Only create stateNoBinary the first time it's required.
@@ -446,7 +450,7 @@ impl HighLevelEncoder {
add = false; add = false;
break; break;
} }
if newState.isBetterThanOrEqualTo(&oldState) { if newState.isBetterThanOrEqualTo(oldState) {
result.remove(i); result.remove(i);
} }
} }
@@ -455,6 +459,6 @@ impl HighLevelEncoder {
result.push(newState); result.push(newState);
} }
} }
return result; result
} }
} }

View File

@@ -80,9 +80,9 @@ impl State {
token.add(0, 3); // 0: FNC1 token.add(0, 3); // 0: FNC1
} else */ } else */
if eci > 999999 { if eci > 999999 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"ECI code must be between 0 and 999999".to_owned(), "ECI code must be between 0 and 999999".to_owned(),
)); )));
// throw new IllegalArgumentException("ECI code must be between 0 and 999999"); // throw new IllegalArgumentException("ECI code must be between 0 and 999999");
} else { } else {
let eci_digits = encoding::all::ISO_8859_1 let eci_digits = encoding::all::ISO_8859_1
@@ -155,12 +155,10 @@ impl State {
let deltaBitCount = let deltaBitCount =
if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 { if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 {
18 18
} else { } else if self.binary_shift_byte_count == 62 {
if self.binary_shift_byte_count == 62 {
9 9
} else { } else {
8 8
}
}; };
let mut result = State::new( let mut result = State::new(
token, token,
@@ -240,7 +238,7 @@ impl State {
if binary_shift_byte_count > 0 { if binary_shift_byte_count > 0 {
return 10; // one B/S return 10; // one B/S
} }
return 0; 0
} }
} }

View File

@@ -115,3 +115,9 @@ impl IntoIterator for Token {
// fn appendTo(&self, bitArray: BitArray, text: &[u8]); // fn appendTo(&self, bitArray: BitArray, text: &[u8]);
// } // }
impl Default for Token {
fn default() -> Self {
Self::new()
}
}

View File

@@ -24,9 +24,10 @@ pub fn toBitArray(bits: &str) -> BitArray {
#[allow(dead_code)] #[allow(dead_code)]
pub fn toBooleanArray(bitArray: &BitArray) -> Vec<bool> { pub fn toBooleanArray(bitArray: &BitArray) -> Vec<bool> {
let mut result = vec![false; bitArray.getSize()]; let mut result = vec![false; bitArray.getSize()];
for i in 0..result.len() { // for i in 0..result.len() {
for (i, res) in result.iter_mut().enumerate() {
// for (int i = 0; i < result.length; i++) { // for (int i = 0; i < result.length; i++) {
result[i] = bitArray.get(i); *res = bitArray.get(i);
} }
result result
} }

View File

@@ -39,7 +39,7 @@ impl BinaryBitmap {
pub fn new(binarizer: Rc<RefCell<dyn Binarizer>>) -> Self { pub fn new(binarizer: Rc<RefCell<dyn Binarizer>>) -> Self {
Self { Self {
matrix: None, matrix: None,
binarizer: binarizer, binarizer,
} }
} }
@@ -123,7 +123,7 @@ impl BinaryBitmap {
.clone(), .clone(),
) )
} }
&self.matrix.as_ref().unwrap() self.matrix.as_ref().unwrap()
} }
/** /**
@@ -132,8 +132,8 @@ impl BinaryBitmap {
pub fn isCropSupported(&self) -> bool { pub fn isCropSupported(&self) -> bool {
let b = self.binarizer.borrow(); let b = self.binarizer.borrow();
let r = b.getLuminanceSource(); let r = b.getLuminanceSource();
let isCropOk = r.isCropSupported();
return isCropOk; r.isCropSupported()
} }
/** /**

View File

@@ -102,7 +102,7 @@ impl BufferedImageLuminanceSource {
for y in 0..image.height() { for y in 0..image.height() {
let pixel = img.get_pixel(x, y); let pixel = img.get_pixel(x, y);
let [red, green, blue, alpha] = pixel.0; let [red, green, blue, alpha] = pixel.0;
if (alpha & 0xFF) == 0 { if alpha == 0 {
// white, so we know its luminance is 255 // white, so we know its luminance is 255
raster.put_pixel(x, y, Luma([0xFF])) raster.put_pixel(x, y, Luma([0xFF]))
} else { } else {
@@ -147,10 +147,10 @@ impl BufferedImageLuminanceSource {
Self { Self {
image: Rc::new(DynamicImage::from(raster)), image: Rc::new(DynamicImage::from(raster)),
width: width, width,
height: height, height,
left: left, left,
top: top, top,
} }
// Self { // Self {
@@ -206,13 +206,12 @@ impl LuminanceSource for BufferedImageLuminanceSource {
let data = unmanaged let data = unmanaged
.chunks(self.image.width() as usize) .chunks(self.image.width() as usize)
.into_iter() // Get rows .into_iter() // Get rows
.map(|f| { .flat_map(|f| {
f.into_iter() f.iter()
.skip(row_skip as usize) .skip(row_skip as usize)
.take(total_row_take as usize) .take(total_row_take)
.copied() .copied()
}) // Take data from each row }) // flatten this all out
.flatten() // flatten this all out
.copied() // copy it over so that it's u8 .copied() // copy it over so that it's u8
.collect(); // collect into a vec .collect(); // collect into a vec
@@ -235,7 +234,7 @@ impl LuminanceSource for BufferedImageLuminanceSource {
} }
fn isCropSupported(&self) -> bool { fn isCropSupported(&self) -> bool {
return true; true
} }
fn crop( fn crop(
@@ -266,7 +265,7 @@ impl LuminanceSource for BufferedImageLuminanceSource {
} }
fn isRotateSupported(&self) -> bool { fn isRotateSupported(&self) -> bool {
return true; true
} }
fn rotateCounterClockwise( fn rotateCounterClockwise(

View File

@@ -118,20 +118,20 @@ impl AddressBookParsedRXingResult {
urls: Vec<String>, urls: Vec<String>,
geo: Vec<String>, geo: Vec<String>,
) -> Result<Self, Exceptions> { ) -> Result<Self, Exceptions> {
if phone_numbers.len() != phone_types.len() && phone_types.len() > 0 { if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Phone numbers and types lengths differ".to_owned(), "Phone numbers and types lengths differ".to_owned(),
)); )));
} }
if emails.len() != email_types.len() && email_types.len() > 0 { if emails.len() != email_types.len() && !email_types.is_empty() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Emails and types lengths differ".to_owned(), "Emails and types lengths differ".to_owned(),
)); )));
} }
if addresses.len() != address_types.len() && address_types.len() > 0 { if addresses.len() != address_types.len() && !address_types.is_empty() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Addresses and types lengths differ".to_owned(), "Addresses and types lengths differ".to_owned(),
)); )));
} }
Ok(Self { Ok(Self {
names, names,

View File

@@ -37,7 +37,7 @@ fn testAddressBookDocomo() {
doTest( doTest(
"MECARD:N:Sean Owen;;", "MECARD:N:Sean Owen;;",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -51,14 +51,14 @@ fn testAddressBookDocomo() {
doTest( doTest(
"MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;;", "MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;;",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&Vec::new(), &Vec::new(),
&vec!["srowen@example.org"], &["srowen@example.org"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
"", "",
&vec!["google.com"], &["google.com"],
"", "",
"ZXing Team", "ZXing Team",
); );
@@ -69,11 +69,11 @@ fn testAddressBookAU() {
doTest( doTest(
"MEMORY:foo\r\nNAME1:Sean\r\nTEL1:+12125551212\r\n", "MEMORY:foo\r\nNAME1:Sean\r\nTEL1:+12125551212\r\n",
"", "",
&vec!["Sean"], &["Sean"],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&vec!["+12125551212"], &["+12125551212"],
&Vec::new(), &Vec::new(),
"", "",
&Vec::new(), &Vec::new(),
@@ -87,9 +87,9 @@ fn testVCard() {
doTest( doTest(
"BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", "BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&vec!["123 Main St"], &["123 Main St"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -105,7 +105,7 @@ fn testVCardFullN() {
doTest( doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;T;Mr.;Esq.\r\nEND:VCARD", "BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;T;Mr.;Esq.\r\nEND:VCARD",
"", "",
&vec!["Mr. Sean T Owen Esq."], &["Mr. Sean T Owen Esq."],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -123,7 +123,7 @@ fn testVCardFullN2() {
doTest( doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;;;\r\nEND:VCARD", "BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;;;\r\nEND:VCARD",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -141,7 +141,7 @@ fn testVCardFullN3() {
doTest( doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:;Sean;;;\r\nEND:VCARD", "BEGIN:VCARD\r\nVERSION:2.1\r\nN:;Sean;;;\r\nEND:VCARD",
"", "",
&vec!["Sean"], &["Sean"],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -159,9 +159,9 @@ fn testVCardCaseInsensitive() {
doTest( doTest(
"begin:vcard\r\nadr;HOME:123 Main St\r\nVersion:2.1\r\nn:Owen;Sean\r\nEND:VCARD", "begin:vcard\r\nadr;HOME:123 Main St\r\nVersion:2.1\r\nn:Owen;Sean\r\nEND:VCARD",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&vec!["123 Main St"], &["123 Main St"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -175,7 +175,7 @@ fn testVCardCaseInsensitive() {
#[test] #[test]
fn testEscapedVCard() { fn testEscapedVCard() {
doTest("BEGIN:VCARD\r\nADR;HOME:123\\;\\\\ Main\\, St\\nHome\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", doTest("BEGIN:VCARD\r\nADR;HOME:123\\;\\\\ Main\\, St\\nHome\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD",
"", &vec!["Sean Owen"], "", &vec!["123;\\ Main, St\nHome"], "", &["Sean Owen"], "", &["123;\\ Main, St\nHome"],
&Vec::new(), &Vec::new(), &Vec::new(), "", &Vec::new(), "", ""); &Vec::new(), &Vec::new(), &Vec::new(), "", &Vec::new(), "", "");
} }
@@ -184,11 +184,11 @@ fn testBizcard() {
doTest( doTest(
"BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12125551212;E:srowen@example.org;", "BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12125551212;E:srowen@example.org;",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&vec!["123 Main St"], &["123 Main St"],
&vec!["srowen@example.org"], &["srowen@example.org"],
&vec!["+12125551212"], &["+12125551212"],
&Vec::new(), &Vec::new(),
"Google", "Google",
&Vec::new(), &Vec::new(),
@@ -200,9 +200,9 @@ fn testBizcard() {
#[test] #[test]
fn testSeveralAddresses() { fn testSeveralAddresses() {
doTest("MECARD:N:Foo Bar;ORG:Company;TEL:5555555555;EMAIL:foo.bar@xyz.com;ADR:City, 10001;ADR:City, 10001;NOTE:This is the memo.;;", doTest("MECARD:N:Foo Bar;ORG:Company;TEL:5555555555;EMAIL:foo.bar@xyz.com;ADR:City, 10001;ADR:City, 10001;NOTE:This is the memo.;;",
"", &vec!["Foo Bar"], "", &vec!["City, 10001", "City, 10001"], "", &["Foo Bar"], "", &["City, 10001", "City, 10001"],
&vec!["foo.bar@xyz.com"], &["foo.bar@xyz.com"],
&vec!["5555555555" ], &Vec::new(), "Company", &Vec::new(), "", "This is the memo."); &["5555555555"], &Vec::new(), "Company", &Vec::new(), "", "This is the memo.");
} }
#[test] #[test]
@@ -212,7 +212,7 @@ fn testQuotedPrintable() {
"", "",
&Vec::new(), &Vec::new(),
"", "",
&vec!["88 Lynbrook\r\nCO 69999"], &["88 Lynbrook\r\nCO 69999"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -292,8 +292,8 @@ fn testVCardValueURI() {
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&vec!["+1-555-555-1212"], &["+1-555-555-1212"],
&vec![""], &[""],
"", "",
&Vec::new(), &Vec::new(),
"", "",
@@ -303,7 +303,7 @@ fn testVCardValueURI() {
doTest( doTest(
"BEGIN:VCARD\r\nN;VALUE=text:Owen;Sean\r\nEND:VCARD", "BEGIN:VCARD\r\nN;VALUE=text:Owen;Sean\r\nEND:VCARD",
"", "",
&vec!["Sean Owen"], &["Sean Owen"],
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
@@ -325,8 +325,8 @@ fn testVCardTypes() {
"", "",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&vec!["10", "20", "30"], &["10", "20", "30"],
&vec!["WORK", "", "CELL"], &["WORK", "", "CELL"],
"", "",
&Vec::new(), &Vec::new(),
"", "",

View File

@@ -120,11 +120,9 @@ fn buildPhoneNumbers(number1: String, number2: String, number3: String) -> Vec<S
fn buildName(firstName: &str, lastName: &str) -> String { fn buildName(firstName: &str, lastName: &str) -> String {
if firstName.is_empty() { if firstName.is_empty() {
lastName.to_owned() lastName.to_owned()
} else { } else if lastName.is_empty() {
if lastName.is_empty() {
firstName.to_owned() firstName.to_owned()
} else { } else {
format!("{} {}", firstName, lastName) format!("{} {}", firstName, lastName)
} }
}
} }

View File

@@ -32,14 +32,12 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
} }
let title = ResultParser::match_single_do_co_mo_prefixed_field("TITLE:", rawText, true); let title = ResultParser::match_single_do_co_mo_prefixed_field("TITLE:", rawText, true);
let rawUri = ResultParser::match_do_co_mo_prefixed_field("URL:", rawText); let rawUri = ResultParser::match_do_co_mo_prefixed_field("URL:", rawText);
if rawUri.is_none() { rawUri.as_ref()?;
return None;
}
let uri = rawUri?[0].clone(); let uri = rawUri?[0].clone();
if URIResultParser::is_basically_valid_uri(&uri) { if URIResultParser::is_basically_valid_uri(&uri) {
Some(ParsedClientResult::URIResult(URIParsedRXingResult::new( Some(ParsedClientResult::URIResult(URIParsedRXingResult::new(
uri, uri,
title.unwrap_or("".to_owned()), title.unwrap_or_else(|| "".to_owned()),
))) )))
} else { } else {
None None

View File

@@ -120,8 +120,6 @@ impl CalendarParsedRXingResult {
} else { } else {
Self::parseDate(endString.clone())? Self::parseDate(endString.clone())?
}; };
let startAllDay;
let endAllDay;
// try { // try {
// this.start = parseDate(startString); // this.start = parseDate(startString);
@@ -140,8 +138,8 @@ impl CalendarParsedRXingResult {
// } // }
// } // }
startAllDay = startString.len() == 8; let startAllDay = startString.len() == 8;
endAllDay = !endString.is_empty() && endString.len() == 8; let endAllDay = !endString.is_empty() && endString.len() == 8;
Ok(Self { Ok(Self {
summary, summary,
@@ -168,7 +166,7 @@ impl CalendarParsedRXingResult {
fn parseDate(when: String) -> Result<i64, Exceptions> { fn parseDate(when: String) -> Result<i64, Exceptions> {
// let date_time_regex = Regex::new(DATE_TIME).unwrap(); // let date_time_regex = Regex::new(DATE_TIME).unwrap();
if !DATE_TIME.is_match(&when) { if !DATE_TIME.is_match(&when) {
return Err(Exceptions::ParseException(when)); return Err(Exceptions::ParseException(Some(when)));
} }
if when.len() == 8 { if when.len() == 8 {
// Show only year/month/day // Show only year/month/day
@@ -196,10 +194,10 @@ impl CalendarParsedRXingResult {
if when.len() == 16 && when.chars().nth(15).unwrap() == 'Z' { if when.len() == 16 && when.chars().nth(15).unwrap() == 'Z' {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") {
Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()), Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()),
Err(e) => Err(Exceptions::ParseException(format!( Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse string: {}", "couldn't parse string: {}",
e e
))), )))),
}; };
// let dtm = DateTime::parse_from_str(&when, "%Y%m%dT%H%M%S").unwrap().with_timezone(&Utc); // let dtm = DateTime::parse_from_str(&when, "%Y%m%dT%H%M%S").unwrap().with_timezone(&Utc);
// //let milliseconds = Self::parseDateTimeString(&when[0..15]); // //let milliseconds = Self::parseDateTimeString(&when[0..15]);
@@ -219,18 +217,18 @@ impl CalendarParsedRXingResult {
let tz_parsed: Tz = match tz_part.parse() { let tz_parsed: Tz = match tz_part.parse() {
Ok(time_zone) => time_zone, Ok(time_zone) => time_zone,
Err(e) => { Err(e) => {
return Err(Exceptions::ParseException(format!( return Err(Exceptions::ParseException(Some(format!(
"couldn't parse timezone '{}': {}", "couldn't parse timezone '{}': {}",
tz_part, e tz_part, e
))) ))))
} }
}; };
return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") { return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()), Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()),
Err(e) => Err(Exceptions::ParseException(format!( Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse string: {}", "couldn't parse string: {}",
e e
))), )))),
}; };
} }
@@ -238,10 +236,10 @@ impl CalendarParsedRXingResult {
if when.len() == 15 { if when.len() == 15 {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") { return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.timestamp()), Ok(dtm) => Ok(dtm.timestamp()),
Err(e) => Err(Exceptions::ParseException(format!( Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse local time: {}", "couldn't parse local time: {}",
e e
))), )))),
}; };
} }
Self::parseDateTimeString(&when) Self::parseDateTimeString(&when)
@@ -270,12 +268,13 @@ impl CalendarParsedRXingResult {
// let regex = Regex::new(RFC2445_DURATION).unwrap(); // let regex = Regex::new(RFC2445_DURATION).unwrap();
if let Some(m) = RFC2445_DURATION.captures(durationString) { if let Some(m) = RFC2445_DURATION.captures(durationString) {
let mut durationMS = 0i64; let mut durationMS = 0i64;
for i in 0..RFC2445_DURATION_FIELD_UNITS.len() { for (i, unit) in RFC2445_DURATION_FIELD_UNITS.iter().enumerate() {
// for i in 0..RFC2445_DURATION_FIELD_UNITS.len() {
// for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.length; i++) { // for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.length; i++) {
let fieldValue = m.get(i + 1); let fieldValue = m.get(i + 1);
if fieldValue.is_some() { if let Some(parseable) = fieldValue {
let z = fieldValue.unwrap().as_str().parse::<i64>().unwrap(); let z = parseable.as_str().parse::<i64>().unwrap();
durationMS += RFC2445_DURATION_FIELD_UNITS[i] * z; durationMS += unit * z;
} }
} }
durationMS durationMS
@@ -299,10 +298,10 @@ impl CalendarParsedRXingResult {
if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") { if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") {
Ok(dtm.timestamp()) Ok(dtm.timestamp())
} else { } else {
Err(Exceptions::ParseException(format!( Err(Exceptions::ParseException(Some(format!(
"Couldn't parse {}", "Couldn't parse {}",
dateTimeString dateTimeString
))) ))))
} }
// DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH); // DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
// return format.parse(dateTimeString).getTime(); // return format.parse(dateTimeString).getTime();

View File

@@ -150,7 +150,7 @@ fn testAttendees() {
doTest( doTest(
"BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20080504T123456Z\r\nATTENDEE:mailto:bob@example.org\r\nATTENDEE:mailto:alice@example.org\r\nEND:VEVENT\r\nEND:VCALENDAR", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20080504T123456Z\r\nATTENDEE:mailto:bob@example.org\r\nATTENDEE:mailto:alice@example.org\r\nEND:VEVENT\r\nEND:VCALENDAR",
"", "", "", "20080504T123456Z", "", "", "", "", "", "20080504T123456Z", "", "",
&vec!["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN); &["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN);
} }
#[test] #[test]

View File

@@ -42,7 +42,7 @@ fn testEmailAddress() {
fn testTos() { fn testTos() {
do_test( do_test(
"mailto:srowen@example.org,bob@example.org", "mailto:srowen@example.org,bob@example.org",
&vec!["srowen@example.org", "bob@example.org"], &["srowen@example.org", "bob@example.org"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
"", "",
@@ -50,7 +50,7 @@ fn testTos() {
); );
do_test( do_test(
"mailto:?to=srowen@example.org,bob@example.org", "mailto:?to=srowen@example.org,bob@example.org",
&vec!["srowen@example.org", "bob@example.org"], &["srowen@example.org", "bob@example.org"],
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
"", "",
@@ -63,7 +63,7 @@ fn testCCs() {
do_test( do_test(
"mailto:?cc=srowen@example.org", "mailto:?cc=srowen@example.org",
&Vec::new(), &Vec::new(),
&vec!["srowen@example.org"], &["srowen@example.org"],
&Vec::new(), &Vec::new(),
"", "",
"", "",
@@ -71,7 +71,7 @@ fn testCCs() {
do_test( do_test(
"mailto:?cc=srowen@example.org,bob@example.org", "mailto:?cc=srowen@example.org,bob@example.org",
&Vec::new(), &Vec::new(),
&vec!["srowen@example.org", "bob@example.org"], &["srowen@example.org", "bob@example.org"],
&Vec::new(), &Vec::new(),
"", "",
"", "",
@@ -84,7 +84,7 @@ fn testBCCs() {
"mailto:?bcc=srowen@example.org", "mailto:?bcc=srowen@example.org",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&vec!["srowen@example.org"], &["srowen@example.org"],
"", "",
"", "",
); );
@@ -92,7 +92,7 @@ fn testBCCs() {
"mailto:?bcc=srowen@example.org,bob@example.org", "mailto:?bcc=srowen@example.org,bob@example.org",
&Vec::new(), &Vec::new(),
&Vec::new(), &Vec::new(),
&vec!["srowen@example.org", "bob@example.org"], &["srowen@example.org", "bob@example.org"],
"", "",
"", "",
); );
@@ -102,9 +102,9 @@ fn testBCCs() {
fn testAll() { fn testAll() {
do_test( do_test(
"mailto:bob@example.org?cc=foo@example.org&bcc=srowen@example.org&subject=baz&body=buzz", "mailto:bob@example.org?cc=foo@example.org&bcc=srowen@example.org&subject=baz&body=buzz",
&vec!["bob@example.org"], &["bob@example.org"],
&vec!["foo@example.org"], &["foo@example.org"],
&vec!["srowen@example.org"], &["srowen@example.org"],
"baz", "baz",
"buzz", "buzz",
); );
@@ -151,7 +151,7 @@ fn testSMTP() {
} }
fn do_test_single(contents: &str, to: &str, subject: &str, body: &str) { fn do_test_single(contents: &str, to: &str, subject: &str, body: &str) {
do_test(contents, &vec![to], &Vec::new(), &Vec::new(), subject, body); do_test(contents, &[to], &Vec::new(), &Vec::new(), subject, body);
} }
fn do_test(contents: &str, tos: &[&str], ccs: &[&str], bccs: &[&str], subject: &str, body: &str) { fn do_test(contents: &str, tos: &[&str], ccs: &[&str], bccs: &[&str], subject: &str, body: &str) {

View File

@@ -120,22 +120,16 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
subject = nv.get("subject").unwrap_or(&"".to_owned()).clone(); subject = nv.get("subject").unwrap_or(&"".to_owned()).clone();
body = nv.get("body").unwrap_or(&"".to_owned()).clone(); body = nv.get("body").unwrap_or(&"".to_owned()).clone();
} }
return Some(ParsedClientResult::EmailResult( Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details( EmailAddressParsedRXingResult::with_details(tos, ccs, bccs, subject, body),
tos, ))
ccs,
bccs,
subject.to_owned(),
body.to_owned(),
),
));
} else { } else {
// let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap(); // let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) { if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) {
return None; return None;
} }
return Some(ParsedClientResult::EmailResult( Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::new(rawText), EmailAddressParsedRXingResult::new(rawText),
)); ))
} }
} }

View File

@@ -48,7 +48,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?; let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?;
for to in &tos { for to in &tos {
if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) { if !isBasicallyValidEmailAddress(to, &ATEXT_ALPHANUMERIC) {
return None; return None;
} }
} }

View File

@@ -251,7 +251,7 @@ fn findAIvalue(i: usize, rawText: &str) -> Option<String> {
if currentChar == ')' { if currentChar == ')' {
return Some(buf); return Some(buf);
} }
if currentChar < '0' || currentChar > '9' { if !('0'..='9').contains(&currentChar) {
return None; return None;
} }
buf.push(currentChar); buf.push(currentChar);
@@ -270,7 +270,7 @@ fn findValue(i: usize, rawText: &str) -> String {
if c == '(' { if c == '(' {
// We look for a new AI. If it doesn't exist (ERROR), we continue // We look for a new AI. If it doesn't exist (ERROR), we continue
// with the iteration // with the iteration
if let Some(_) = findAIvalue(index, rawTextAux) { if findAIvalue(index, rawTextAux).is_some() {
break; break;
} }
// if findAIvalue(index, rawTextAux) != null { // if findAIvalue(index, rawTextAux) != null {

View File

@@ -29,7 +29,7 @@ lazy_static! {
static ref GEO_URL: regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap(); static ref GEO_URL: regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap();
} }
const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?"; const GEO_URL_PATTERN: &str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?";
/** /**
* Parses a "geo:" URI result, which specifies a location on the surface of * Parses a "geo:" URI result, which specifies a location on the surface of
@@ -54,7 +54,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
let latitude = if let Some(la) = captures.get(1) { let latitude = if let Some(la) = captures.get(1) {
if let Ok(laf64) = la.as_str().parse::<f64>() { if let Ok(laf64) = la.as_str().parse::<f64>() {
if laf64 > 90.0 || laf64 < -90.0 { if !(-90.0..=90.0).contains(&laf64) {
return None; return None;
} }
laf64 laf64
@@ -67,7 +67,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
let longitude = if let Some(lo) = captures.get(2) { let longitude = if let Some(lo) = captures.get(2) {
if let Ok(lof64) = lo.as_str().parse::<f64>() { if let Ok(lof64) = lo.as_str().parse::<f64>() {
if lof64 > 180.0 || lof64 < -180.0 { if !(-180.0..=180.0).contains(&lof64) {
return None; return None;
} }
lof64 lof64
@@ -119,7 +119,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
String::from(query), String::from(query),
))) )))
} else { } else {
return None; None
} }
// Matcher matcher = GEO_URL_PATTERN.matcher(rawText); // Matcher matcher = GEO_URL_PATTERN.matcher(rawText);

View File

@@ -44,7 +44,7 @@ pub trait ParsedRXingResult {
fn maybe_append(&self, value: &str, result: &mut String) { fn maybe_append(&self, value: &str, result: &mut String) {
if !value.is_empty() { if !value.is_empty() {
// Don't add a newline before the first value // Don't add a newline before the first value
if result.len() > 0 { if !result.is_empty() {
result.push('\n'); result.push('\n');
} }
result.push_str(value); result.push_str(value);

View File

@@ -46,14 +46,14 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
} }
// Not actually checking the checksum again here // Not actually checking the checksum again here
let normalizedProductID; let normalizedProductID=
// Expand UPC-E for purposes of searching // Expand UPC-E for purposes of searching
if format == &BarcodeFormat::UPC_E && rawText.len() == 8 { if format == &BarcodeFormat::UPC_E && rawText.len() == 8 {
// unimplemented!("UPCEReader is required to parse this"); // unimplemented!("UPCEReader is required to parse this");
normalizedProductID = crate::oned::convertUPCEtoUPCA(&rawText); crate::oned::convertUPCEtoUPCA(&rawText)
} else { } else {
normalizedProductID = rawText.clone(); rawText.clone()
} };
Some(ParsedClientResult::ProductResult( Some(ParsedClientResult::ProductResult(
ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID), ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID),

View File

@@ -97,9 +97,9 @@ lazy_static! {
} }
// const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+"); // const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+");
const AMPERSAND: &'static str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&"); const AMPERSAND: &str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&");
const EQUALS: &'static str = "="; //private static final Pattern EQUALS = Pattern.compile("="); const EQUALS: &str = "="; //private static final Pattern EQUALS = Pattern.compile("=");
const BYTE_ORDER_MARK: &'static str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff"; const BYTE_ORDER_MARK: &str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff";
// const EMPTY_STR_ARRAY: &'static str = ""; // const EMPTY_STR_ARRAY: &'static str = "";
@@ -108,7 +108,7 @@ pub fn getMassagedText(result: &RXingResult) -> String {
if text.starts_with(BYTE_ORDER_MARK) { if text.starts_with(BYTE_ORDER_MARK) {
text = text[1..].to_owned(); text = text[1..].to_owned();
} }
return text; text
} }
pub fn parse_result_with_parsers( pub fn parse_result_with_parsers(
@@ -117,8 +117,8 @@ pub fn parse_result_with_parsers(
) -> ParsedClientResult { ) -> ParsedClientResult {
for parser in parsers { for parser in parsers {
let result = parser(the_rxing_result); let result = parser(the_rxing_result);
if result.is_some() { if let Some(res) = result {
return result.unwrap(); return res;
} }
} }
parseRXingResult(the_rxing_result) parseRXingResult(the_rxing_result)
@@ -150,8 +150,8 @@ pub fn parseRXingResult(the_rxing_result: &RXingResult) -> ParsedClientResult {
for parser in PARSERS { for parser in PARSERS {
let result = parser(the_rxing_result); let result = parser(the_rxing_result);
if result.is_some() { if let Some(res) = result {
return result.unwrap(); return res;
} }
} }
// ParsedRXingResult result = parser.parse(theRXingResult); // ParsedRXingResult result = parser.parse(theRXingResult);
@@ -193,7 +193,7 @@ pub fn maybeWrap(value: Option<String>) -> Option<Vec<String>> {
if value.is_none() { if value.is_none() {
None None
} else { } else {
Some(vec![value.unwrap().to_owned()]) Some(vec![value.unwrap()])
} }
} }
@@ -222,16 +222,16 @@ pub fn unescapeBackslash(escaped: &str) -> String {
} }
pub fn parseHexDigit(c: char) -> i32 { pub fn parseHexDigit(c: char) -> i32 {
if c >= '0' && c <= '9' { if ('0'..='9').contains(&c) {
return (c as u8 - '0' as u8) as i32; return (c as u8 - b'0') as i32;
} }
if c >= 'a' && c <= 'f' { if ('a'..='f').contains(&c) {
return 10 + (c as u8 - 'a' as u8) as i32; return 10 + (c as u8 - b'a') as i32;
} }
if c >= 'A' && c <= 'F' { if ('A'..='F').contains(&c) {
return 10 + (c as u8 - 'A' as u8) as i32; return 10 + (c as u8 - b'A') as i32;
} }
return -1; -1
} }
pub fn isStringOfDigits(value: &str, length: usize) -> bool { pub fn isStringOfDigits(value: &str, length: usize) -> bool {
@@ -242,16 +242,12 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool {
if value.is_empty() || length == 0 { if value.is_empty() || length == 0 {
return false; return false;
} }
let max = offset as usize + length; let max = offset + length;
let sub_seq = &value[offset as usize..max]; let sub_seq = &value[offset..max];
let is_a_match = if let Some(mtch) = DIGITS.find(sub_seq) { let is_a_match = if let Some(mtch) = DIGITS.find(sub_seq) {
if mtch.start() == 0 && mtch.end() == sub_seq.len() { mtch.start() == 0 && mtch.end() == sub_seq.len()
true
} else {
false
}
} else { } else {
false false
}; };
@@ -261,9 +257,7 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool {
pub fn parseNameValuePairs(uri: &str) -> Option<HashMap<String, String>> { pub fn parseNameValuePairs(uri: &str) -> Option<HashMap<String, String>> {
let paramStart = uri.find('?'); let paramStart = uri.find('?');
if paramStart.is_none() { paramStart?;
return None;
}
let mut result = HashMap::with_capacity(3); let mut result = HashMap::with_capacity(3);
let paramStart = paramStart.unwrap_or(0); let paramStart = paramStart.unwrap_or(0);
@@ -285,7 +279,7 @@ pub fn appendKeyValue(keyValue: &str, result: &mut HashMap<String, String>) {
let kvp: Vec<&str> = keyValueTokens.take(2).collect(); let kvp: Vec<&str> = keyValueTokens.take(2).collect();
if let [key, value] = kvp[..] { if let [key, value] = kvp[..] {
let p_value = urlDecode(value).unwrap_or("".to_owned()); let p_value = urlDecode(value).unwrap_or_else(|_| "".to_owned());
result.insert(key.to_owned(), p_value); result.insert(key.to_owned(), p_value);
} }
@@ -305,9 +299,9 @@ pub fn urlDecode(encoded: &str) -> Result<String, Exceptions> {
if let Ok(decoded) = decode(encoded) { if let Ok(decoded) = decode(encoded) {
Ok(decoded.to_string()) Ok(decoded.to_string())
} else { } else {
Err(Exceptions::IllegalStateException( Err(Exceptions::IllegalStateException(Some(
"UnsupportedEncodingException".to_owned(), "UnsupportedEncodingException".to_owned(),
)) )))
} }
} }
@@ -334,14 +328,13 @@ pub fn matchPrefixedField(
let start = i; // Found the start of a match here let start = i; // Found the start of a match here
let mut more = true; let mut more = true;
while more { while more {
let next_index = rawText[i..].find(endChar); if let Some(next_index) = rawText[i..].find(endChar) {
if next_index.is_none() { i += next_index;
} else {
// No terminating end character? uh, done. Set i such that loop terminates and break // No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.len(); i = rawText.len();
more = false; more = false;
continue; continue;
} else {
i += next_index.unwrap();
} }
if countPrecedingBackslashes(rawText, i) % 2 != 0 { if countPrecedingBackslashes(rawText, i) % 2 != 0 {
@@ -399,7 +392,7 @@ pub fn countPrecedingBackslashes(s: &str, pos: usize) -> u32 {
break; break;
} }
} }
return count; count
} }
pub fn matchSinglePrefixedField( pub fn matchSinglePrefixedField(
@@ -409,11 +402,7 @@ pub fn matchSinglePrefixedField(
trim: bool, trim: bool,
) -> Option<String> { ) -> Option<String> {
let matches = matchPrefixedField(prefix, rawText, endChar, trim); let matches = matchPrefixedField(prefix, rawText, endChar, trim);
if let Some(m) = matches { matches.map(|m| m[0].clone())
Some(m[0].clone())
} else {
None
}
// return matches == null ? null : matches[0]; // return matches == null ? null : matches[0];
} }

View File

@@ -69,13 +69,13 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// Drop sms, query portion // Drop sms, query portion
let query_start = raw_text[4..].find('?'); let query_start = raw_text[4..].find('?');
let sms_uriwithout_query; let sms_uriwithout_query=
// If it's not query syntax, the question mark is part of the subject or message // If it's not query syntax, the question mark is part of the subject or message
if query_start.is_none() || !querySyntax { if query_start.is_none() || !querySyntax {
sms_uriwithout_query = &raw_text[4..]; &raw_text[4..]
} else { } else {
sms_uriwithout_query = &raw_text[4..4 + query_start.unwrap_or(0)]; &raw_text[4..4 + query_start.unwrap_or(0)]
} };
let mut last_comma: i32 = -1; let mut last_comma: i32 = -1;
let mut comma: i32 = sms_uriwithout_query[(last_comma + 1) as usize..] let mut comma: i32 = sms_uriwithout_query[(last_comma + 1) as usize..]
@@ -103,7 +103,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
); );
Some(ParsedClientResult::SMSResult( Some(ParsedClientResult::SMSResult(
SMSParsedRXingResult::with_arrays(numbers, vias, subject.to_owned(), body.to_owned()), SMSParsedRXingResult::with_arrays(numbers, vias, subject, body),
)) ))
// return new SMSParsedRXingResult(numbers.toArray(EMPTY_STR_ARRAY), // return new SMSParsedRXingResult(numbers.toArray(EMPTY_STR_ARRAY),
@@ -120,8 +120,8 @@ fn add_number_via(numbers: &mut Vec<String>, vias: &mut Vec<String>, number_part
// if numberEnd < 0 { // if numberEnd < 0 {
numbers.push(number_part[..number_end].to_string()); numbers.push(number_part[..number_end].to_string());
let maybe_via = &number_part[number_end + 1..]; let maybe_via = &number_part[number_end + 1..];
let via = if maybe_via.starts_with("via=") { let via = if let Some(stripped) = maybe_via.strip_prefix("via=") {
&maybe_via[4..] stripped
} else { } else {
"" ""
}; };

View File

@@ -60,6 +60,6 @@ impl TelParsedRXingResult {
} }
pub fn getTitle(&self) -> &str { pub fn getTitle(&self) -> &str {
&&self.title &self.title
} }
} }

View File

@@ -35,8 +35,8 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult>
return None; return None;
} }
// Normalize "TEL:" to "tel:" // Normalize "TEL:" to "tel:"
let telURI = if rawText.starts_with("TEL:") { let telURI = if let Some(stripped) = rawText.strip_prefix("TEL:") {
format!("tel:{}", &rawText[4..]) format!("tel:{}", stripped)
} else { } else {
rawText.clone() rawText.clone()
}; };
@@ -50,7 +50,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult>
// let number = queryStart < 0 ? : ; // let number = queryStart < 0 ? : ;
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new( Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(
number.to_owned(), number.to_owned(),
telURI.to_owned(), telURI,
"".to_owned(), "".to_owned(),
))) )))
} }

View File

@@ -63,7 +63,7 @@ impl URIParsedRXingResult {
*/ */
#[deprecated] #[deprecated]
pub fn is_possibly_malicious_uri(&self) -> bool { pub fn is_possibly_malicious_uri(&self) -> bool {
return URIResultParser::is_possibly_malicious_uri(&self.uri); URIResultParser::is_possibly_malicious_uri(&self.uri)
} }
/** /**
@@ -98,6 +98,6 @@ impl URIParsedRXingResult {
// if (nextSlash < 0) { // if (nextSlash < 0) {
// nextSlash = uri.length(); // nextSlash = uri.length();
// } // }
return ResultParser::isSubstringOfDigits(uri, start, nextSlash - start); ResultParser::isSubstringOfDigits(uri, start, nextSlash - start)
} }
} }

View File

@@ -44,7 +44,7 @@ lazy_static! {
Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap(); Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap();
} }
const ALLOWED_URI_CHARS_PATTERN: &'static str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+"; const ALLOWED_URI_CHARS_PATTERN: &str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+";
// const USER_IN_HOST: &'static str = ":/*([^/@]+)@[^/]+"; // const USER_IN_HOST: &'static str = ":/*([^/@]+)@[^/]+";
/// See http://www.ietf.org/rfc/rfc2396.txt /// See http://www.ietf.org/rfc/rfc2396.txt
// const URL_WITH_PROTOCOL_PATTERN: &'static str = "[a-zA-Z][a-zA-Z0-9+-.]+:"; // const URL_WITH_PROTOCOL_PATTERN: &'static str = "[a-zA-Z][a-zA-Z0-9+-.]+:";
@@ -83,11 +83,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
*/ */
pub fn is_possibly_malicious_uri(uri: &str) -> bool { pub fn is_possibly_malicious_uri(uri: &str) -> bool {
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) { let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) {
if fnd.start() == 0 && fnd.end() == uri.len() { fnd.start() == 0 && fnd.end() == uri.len()
true
} else {
false
}
} else { } else {
false false
}; };
@@ -97,7 +93,7 @@ pub fn is_possibly_malicious_uri(uri: &str) -> bool {
} }
pub fn is_basically_valid_uri(uri: &str) -> bool { pub fn is_basically_valid_uri(uri: &str) -> bool {
if uri.contains(" ") { if uri.contains(' ') {
// Quick hack check for a common case // Quick hack check for a common case
return false; return false;
} }
@@ -111,12 +107,7 @@ pub fn is_basically_valid_uri(uri: &str) -> bool {
// let m = Regex::new(URL_WITHOUT_PROTOCOL_PATTERN).expect("Regex patterns should always copile"); //.matcher(uri); // let m = Regex::new(URL_WITHOUT_PROTOCOL_PATTERN).expect("Regex patterns should always copile"); //.matcher(uri);
if let Some(found) = URL_WITHOUT_PROTOCOL_PATTERN.find(uri) { if let Some(found) = URL_WITHOUT_PROTOCOL_PATTERN.find(uri) {
if found.start() == 0 { found.start() == 0
// match at start only
true
} else {
false
}
} else { } else {
false false
} }

View File

@@ -58,9 +58,9 @@ lazy_static! {
// const NEWLINE_ESCAPE: &'static str = "\\\\[nN]"; // const NEWLINE_ESCAPE: &'static str = "\\\\[nN]";
// const VCARD_ESCAPES: &'static str = "\\\\([,;\\\\])"; // const VCARD_ESCAPES: &'static str = "\\\\([,;\\\\])";
// const EQUALS: &'static str = "="; // const EQUALS: &'static str = "=";
const SEMICOLON: &'static str = ";"; const SEMICOLON: &str = ";";
// const UNESCAPED_SEMICOLONS: &'static str = "(?<!\\\\);+"; // const UNESCAPED_SEMICOLONS: &'static str = "(?<!\\\\);+";
const COMMA: &'static str = ","; const COMMA: &str = ",";
// const SEMICOLON_OR_COMMA: &'static str = "[;,]"; // const SEMICOLON_OR_COMMA: &'static str = "[;,]";
/** /**
@@ -130,14 +130,14 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let urls = matchVCardPrefixedField("URL", &rawText, true, false); let urls = matchVCardPrefixedField("URL", &rawText, true, false);
let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false); let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false);
let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false); let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false);
let geo = if geoString.is_none() { let geo = if let Some(geo_string) = geoString {
Vec::new()
} else {
SEMICOLON_OR_COMMA SEMICOLON_OR_COMMA
.split(&geoString.unwrap()[0]) .split(&geo_string[0])
.map(|x| x.to_owned()) .map(|x| x.to_owned())
.collect() .collect()
// SEMICOLON_OR_COMMA.split(geoString.unwrap()[0]) // SEMICOLON_OR_COMMA.split(geoString.unwrap()[0])
} else {
Vec::new()
}; };
// if geo.len() != 2 { // if geo.len() != 2 {
// geo = null; // geo = null;
@@ -322,7 +322,7 @@ pub fn matchVCardPrefixedField(
// matches.add(match); // matches.add(match);
// } else { // } else {
metadata.push(element); metadata.push(element);
matches.push(metadata.into_iter().map(|s| s.to_owned()).collect()); matches.push(metadata.into_iter().collect());
// } // }
i += 1; i += 1;
} else { } else {
@@ -414,29 +414,22 @@ fn decodeQuotedPrintable(value: &str, charset: &str) -> String {
} }
fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut String) { fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut String) {
if fragmentBuffer.len() > 0 { if !fragmentBuffer.is_empty() {
let fragmentBytes = fragmentBuffer.clone(); let fragmentBytes = fragmentBuffer.clone();
let fragment; let fragment;
if charset.is_empty() { if charset.is_empty() {
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned()); fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned());
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8); // fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} else { } else if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
fragment = if let Ok(encoded_result) = fragment = if let Ok(encoded_result) =
enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict) enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict)
{ {
encoded_result encoded_result
} else { } else {
String::from_utf8(fragmentBytes).unwrap_or("".to_owned()) String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned())
} }
} else { } else {
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned()) fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned())
}
// try {
// fragment = new String(fragmentBytes, charset);
// } catch (UnsupportedEncodingException e) {
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
// }
} }
fragmentBuffer.clear(); fragmentBuffer.clear();
result.push_str(&fragment); result.push_str(&fragment);
@@ -505,7 +498,7 @@ fn toTypes(lists: Option<Vec<Vec<String>>>) -> Vec<String> {
if let Some(value) = list.get(0) { if let Some(value) = list.get(0) {
if !value.is_empty() { if !value.is_empty() {
let mut v_type = String::new(); let mut v_type = String::new();
let final_value = list.get(list.len() - 1).unwrap_or(&"".to_owned()).clone(); let final_value = list.last().unwrap_or(&"".to_owned()).clone();
if !final_value.is_empty() { if !final_value.is_empty() {
for i in 0..list.len() - 1 { for i in 0..list.len() - 1 {
// for (int i = 1; i < list.size(); i++) { // for (int i = 1; i < list.size(); i++) {
@@ -553,7 +546,7 @@ fn formatNames(names: &mut Vec<Vec<String>>) {
for list in names { for list in names {
// for (List<String> list : names) { // for (List<String> list : names) {
let mut pos = 0; let mut pos = 0;
while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find("=") { while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find('=') {
pos += 1; pos += 1;
} }
let name = list.get(pos).unwrap_or(&"".to_owned()).clone(); let name = list.get(pos).unwrap_or(&"".to_owned()).clone();
@@ -584,9 +577,9 @@ fn formatNames(names: &mut Vec<Vec<String>>) {
} }
} }
fn maybeAppendComponent(components: &Vec<String>, i: usize, newName: &mut String) { fn maybeAppendComponent(components: &[String], i: usize, newName: &mut String) {
if !components[i].is_empty() { if !components[i].is_empty() {
if newName.len() > 0 { if !newName.is_empty() {
newName.push(' '); newName.push(' ');
} }
newName.push_str(&components[i]); newName.push_str(&components[i]);

View File

@@ -32,7 +32,7 @@ use super::{CalendarParsedRXingResult, ParsedClientResult, ResultParser, VCardRe
*/ */
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> { pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result); let rawText = ResultParser::getMassagedText(result);
if let None = rawText.find("BEGIN:VEVENT") { if !rawText.contains("BEGIN:VEVENT") {
return None; return None;
} }
// if (vEventStart < 0) { // if (vEventStart < 0) {
@@ -51,9 +51,10 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let mut attendees = matchVCardPrefixedField("ATTENDEE", &rawText); let mut attendees = matchVCardPrefixedField("ATTENDEE", &rawText);
if !attendees.is_empty() { if !attendees.is_empty() {
for i in 0..attendees.len() { for attendee in &mut attendees {
// for i in 0..attendees.len() {
// for (int i = 0; i < attendees.length; i++) { // for (int i = 0; i < attendees.length; i++) {
attendees[i] = stripMailto(&attendees[i]); *attendee = stripMailto(attendee);
} }
} }
let description = matchSingleVCardPrefixedField("DESCRIPTION", &rawText); let description = matchSingleVCardPrefixedField("DESCRIPTION", &rawText);
@@ -64,8 +65,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
if geoString.is_empty() { if geoString.is_empty() {
latitude = f64::NAN; latitude = f64::NAN;
longitude = f64::NAN; longitude = f64::NAN;
} else { } else if let Some(semicolon) = geoString.find(';') {
if let Some(semicolon) = geoString.find(';') {
latitude = if let Ok(l) = geoString[..semicolon].parse() { latitude = if let Ok(l) = geoString[..semicolon].parse() {
l l
} else { } else {
@@ -79,16 +79,6 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
} else { } else {
return None; return None;
} }
// if (semicolon < 0) {
// return null;
// }
// try {
// latitude = Double.parseDouble(geoString.substring(0, semicolon));
// longitude = Double.parseDouble(geoString.substring(semicolon + 1));
// } catch (NumberFormatException ignored) {
// return null;
// }
}
if let Ok(cpr) = CalendarParsedRXingResult::new( if let Ok(cpr) = CalendarParsedRXingResult::new(
summary, summary,
@@ -159,9 +149,10 @@ fn matchVCardPrefixedField(prefix: &str, rawText: &str) -> Vec<String> {
} else { } else {
let size = values.len(); let size = values.len();
let mut result = vec!["".to_owned(); size]; //new String[size]; let mut result = vec!["".to_owned(); size]; //new String[size];
for i in 0..size { for (i, res) in result.iter_mut().enumerate().take(size) {
// for i in 0..size {
// for (int i = 0; i < size; i++) { // for (int i = 0; i < size; i++) {
result[i] = values.get(i).unwrap().get(0).unwrap().clone(); *res = values.get(i).unwrap().get(0).unwrap().clone();
} }
result result
} }

View File

@@ -49,9 +49,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let raw_text_res = result.getText().trim(); let raw_text_res = result.getText().trim();
let raw_text = IOQ_MATCHER.replace_all(raw_text_res, "").to_string(); let raw_text = IOQ_MATCHER.replace_all(raw_text_res, "").to_string();
// rawText = IOQ.matcher(rawText).replaceAll("").trim(); // rawText = IOQ.matcher(rawText).replaceAll("").trim();
if let None = AZ09_MATCHER.find(&raw_text) { AZ09_MATCHER.find(&raw_text)?;
return None;
}
// if !AZ09.matcher(rawText).matches() { // if !AZ09.matcher(rawText).matches() {
// return null; // return null;
// } // }
@@ -95,8 +93,8 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// } // }
} }
const IOQ: &'static str = "[IOQ]"; const IOQ: &str = "[IOQ]";
const AZ09: &'static str = "[A-Z0-9]{17}"; const AZ09: &str = "[A-Z0-9]{17}";
fn check_checksum(vin: &str) -> Result<bool, Exceptions> { fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
let mut sum = 0; let mut sum = 0;
@@ -111,13 +109,13 @@ fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
fn vin_char_value(c: char) -> Result<u32, Exceptions> { fn vin_char_value(c: char) -> Result<u32, Exceptions> {
match c { match c {
'A'..='I' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 1), 'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1),
'J'..='R' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1), 'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1),
'S'..='Z' => Ok((c as u8 as u32 - 'S' as u8 as u32) + 2), 'S'..='Z' => Ok((c as u8 as u32 - b'S' as u32) + 2),
'0'..='9' => Ok(c as u8 as u32 - '0' as u8 as u32), '0'..='9' => Ok(c as u8 as u32 - b'0' as u32),
_ => Err(Exceptions::IllegalArgumentException( _ => Err(Exceptions::IllegalArgumentException(Some(
"vin char out of range".to_owned(), "vin char out of range".to_owned(),
)), ))),
} }
// if c >= 'A' && c <= 'I' { // if c >= 'A' && c <= 'I' {
// return Ok((c as u8 as u32 - 'A' as u8 as u32) + 1); // return Ok((c as u8 as u32 - 'A' as u8 as u32) + 1);
@@ -142,9 +140,9 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
8 => Ok(10), 8 => Ok(10),
9 => Ok(0), 9 => Ok(0),
10..=17 => Ok(19 - position), 10..=17 => Ok(19 - position),
_ => Err(Exceptions::IllegalArgumentException( _ => Err(Exceptions::IllegalArgumentException(Some(
"vin position weight out of bounds".to_owned(), "vin position weight out of bounds".to_owned(),
)), ))),
} }
// if position >= 1 && position <= 7 { // if position >= 1 && position <= 7 {
// return 9 - position; // return 9 - position;
@@ -163,11 +161,11 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
fn check_char(remainder: u8) -> Result<char, Exceptions> { fn check_char(remainder: u8) -> Result<char, Exceptions> {
match remainder { match remainder {
0..=9 => Ok(('0' as u8 + remainder) as char), 0..=9 => Ok((b'0' + remainder) as char),
10 => Ok('X'), 10 => Ok('X'),
_ => Err(Exceptions::IllegalArgumentException( _ => Err(Exceptions::IllegalArgumentException(Some(
"remainder too high".to_owned(), "remainder too high".to_owned(),
)), ))),
} }
// if remainder < 10 { // if remainder < 10 {
// return Ok(('0' as u8 + remainder) as char); // return Ok(('0' as u8 + remainder) as char);
@@ -182,16 +180,16 @@ fn check_char(remainder: u8) -> Result<char, Exceptions> {
fn model_year(c: char) -> Result<u32, Exceptions> { fn model_year(c: char) -> Result<u32, Exceptions> {
match c { match c {
'E'..='H' => Ok((c as u8 as u32 - 'E' as u8 as u32) + 1984), 'E'..='H' => Ok((c as u8 as u32 - b'E' as u32) + 1984),
'J'..='N' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1988), 'J'..='N' => Ok((c as u8 as u32 - b'J' as u32) + 1988),
'P' => Ok(1993), 'P' => Ok(1993),
'R'..='T' => Ok((c as u8 as u32 - 'R' as u8 as u32) + 1994), 'R'..='T' => Ok((c as u8 as u32 - b'R' as u32) + 1994),
'V'..='Y' => Ok((c as u8 as u32 - 'V' as u8 as u32) + 1997), 'V'..='Y' => Ok((c as u8 as u32 - b'V' as u32) + 1997),
'1'..='9' => Ok((c as u8 as u32 - '1' as u8 as u32) + 2001), '1'..='9' => Ok((c as u8 as u32 - b'1' as u32) + 2001),
'A'..='D' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 2010), 'A'..='D' => Ok((c as u8 as u32 - b'A' as u32) + 2010),
_ => Err(Exceptions::IllegalArgumentException(String::from( _ => Err(Exceptions::IllegalArgumentException(Some(String::from(
"model year argument out of range", "model year argument out of range",
))), )))),
} }
// if c >= 'E' && c <= 'H' { // if c >= 'E' && c <= 'H' {
// return (c - 'E') + 1984; // return (c - 'E') + 1984;
@@ -218,24 +216,24 @@ fn model_year(c: char) -> Result<u32, Exceptions> {
} }
fn country_code(wmi: &str) -> Option<&'static str> { fn country_code(wmi: &str) -> Option<&'static str> {
let c1 = wmi.chars().nth(0).unwrap(); let c1 = wmi.chars().next().unwrap();
let c2 = wmi.chars().nth(1).unwrap(); let c2 = wmi.chars().nth(1).unwrap();
match c1 { match c1 {
'1' | '4' | '5' => Some("US"), '1' | '4' | '5' => Some("US"),
'2' => Some("CA"), '2' => Some("CA"),
'3' if c2 >= 'A' && c2 <= 'W' => Some("MX"), '3' if ('A'..='W').contains(&c2) => Some("MX"),
'9' if ((c2 >= 'A' && c2 <= 'E') || (c2 >= '3' && c2 <= '9')) => Some("BR"), '9' if (('A'..='E').contains(&c2) || ('3'..='9').contains(&c2)) => Some("BR"),
'J' if (c2 >= 'A' && c2 <= 'T') => Some("JP"), 'J' if ('A'..='T').contains(&c2) => Some("JP"),
'K' if (c2 >= 'L' && c2 <= 'R') => Some("KO"), 'K' if ('L'..='R').contains(&c2) => Some("KO"),
'L' => Some("CN"), 'L' => Some("CN"),
'M' if (c2 >= 'A' && c2 <= 'E') => Some("IN"), 'M' if ('A'..='E').contains(&c2) => Some("IN"),
'S' if (c2 >= 'A' && c2 <= 'M') => Some("UK"), 'S' if ('A'..='M').contains(&c2) => Some("UK"),
'S' if (c2 >= 'N' && c2 <= 'T') => Some("DE"), 'S' if ('N'..='T').contains(&c2) => Some("DE"),
'V' if (c2 >= 'F' && c2 <= 'R') => Some("FR"), 'V' if ('F'..='R').contains(&c2) => Some("FR"),
'V' if (c2 >= 'S' && c2 <= 'W') => Some("ES"), 'V' if ('S'..='W').contains(&c2) => Some("ES"),
'W' => Some("DE"), 'W' => Some("DE"),
'X' if (c2 == '0' || (c2 >= '3' && c2 <= '9')) => Some("RU"), 'X' if (c2 == '0' || ('3'..='9').contains(&c2)) => Some("RU"),
'Z' if (c2 >= 'A' && c2 <= 'R') => Some("IT"), 'Z' if ('A'..='R').contains(&c2) => Some("IT"),
_ => None, _ => None,
} }
} }

View File

@@ -44,7 +44,7 @@ use super::ResultParser;
// impl RXingResultParser for WifiRXingResultParser { // impl RXingResultParser for WifiRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> { pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST: &'static str = "WIFI:"; const WIFI_TEST: &str = "WIFI:";
let rawText_unstripped = ResultParser::getMassagedText(theRXingResult); let rawText_unstripped = ResultParser::getMassagedText(theRXingResult);
if !rawText_unstripped.starts_with(WIFI_TEST) { if !rawText_unstripped.starts_with(WIFI_TEST) {
@@ -52,12 +52,12 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
} }
let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned(); let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned();
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false) let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false)
.unwrap_or(String::from("")); .unwrap_or_else(|| String::from(""));
if ssid.is_empty() { if ssid.is_empty() {
return None; return None;
} }
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false) let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false)
.unwrap_or(String::from("")); .unwrap_or_else(|| String::from(""));
let n_type = let n_type =
if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) { if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) {
nt nt
@@ -85,11 +85,11 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
}; };
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false) let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false)
.unwrap_or(String::from("")); .unwrap_or_else(|| String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false) let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false)
.unwrap_or(String::from("")); .unwrap_or_else(|| String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false) let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false)
.unwrap_or(String::from("")); .unwrap_or_else(|| String::from(""));
Some(ParsedClientResult::WiFiResult( Some(ParsedClientResult::WiFiResult(
WifiParsedRXingResult::with_details( WifiParsedRXingResult::with_details(
@@ -100,7 +100,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
identity, identity,
anonymousIdentity, anonymousIdentity,
eapMethod, eapMethod,
phase2Method.unwrap_or(String::from("")), phase2Method.unwrap_or_else(|| String::from("")),
), ),
)) ))
} }

View File

@@ -243,7 +243,7 @@ fn reverse_algorithm_test() {
let newBitsNew = newBitArray.getBitArray(); let newBitsNew = newBitArray.getBitArray();
assert!(arrays_are_equal( assert!(arrays_are_equal(
&newBitsOriginal, &newBitsOriginal,
&newBitsNew, newBitsNew,
size / 32 + 1 size / 32 + 1
)); ));
} }
@@ -276,14 +276,14 @@ fn reverse_original(oldBits: &[u32], size: usize) -> Vec<u32> {
for i in 0..size { for i in 0..size {
// for (int i = 0; i < size; i++) { // for (int i = 0; i < size; i++) {
if bit_set(oldBits, size - i - 1) { if bit_set(oldBits, size - i - 1) {
newBits[i / 32 as usize] |= 1 << (i & 0x1F); newBits[i / 32_usize] |= 1 << (i & 0x1F);
} }
} }
return newBits; newBits
} }
fn bit_set(bits: &[u32], i: usize) -> bool { fn bit_set(bits: &[u32], i: usize) -> bool {
return (bits[i / 32] & (1 << (i & 0x1F))) != 0; (bits[i / 32] & (1 << (i & 0x1F))) != 0
} }
fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool { fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool {
@@ -293,7 +293,7 @@ fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool {
return false; return false;
} }
} }
return true; true
} }
// } // }

View File

@@ -61,7 +61,10 @@ fn test_set_region() {
// for (int y = 0; y < 5; y++) { // for (int y = 0; y < 5; y++) {
for x in 0..5 { for x in 0..5 {
// for (int x = 0; x < 5; x++) { // for (int x = 0; x < 5; x++) {
assert_eq!(y >= 1 && y <= 3 && x >= 1 && x <= 3, matrix.get(x, y)); assert_eq!(
(1..=3).contains(&y) && (1..=3).contains(&x),
matrix.get(x, y)
);
} }
} }
} }
@@ -133,7 +136,10 @@ fn test_rectangular_set_region() {
// for (int y = 0; y < 240; y++) { // for (int y = 0; y < 240; y++) {
for x in 0..320 { for x in 0..320 {
// for (int x = 0; x < 320; x++) { // for (int x = 0; x < 320; x++) {
assert_eq!(y >= 22 && y < 34 && x >= 105 && x < 185, matrix.get(x, y)); assert_eq!(
(22..34).contains(&y) && (105..185).contains(&x),
matrix.get(x, y)
);
} }
} }
} }
@@ -302,7 +308,7 @@ fn test_xor_case() {
centerMatrix.setRegion(1, 1, 1, 1).expect("must set"); centerMatrix.setRegion(1, 1, 1, 1).expect("must set");
let mut invertedCenterMatrix = fullMatrix.clone(); let mut invertedCenterMatrix = fullMatrix.clone();
invertedCenterMatrix.unset(1, 1); invertedCenterMatrix.unset(1, 1);
let badMatrix = BitMatrix::new(4, 4).unwrap(); let mut badMatrix = BitMatrix::new(4, 4).unwrap();
test_XOR(&emptyMatrix, &emptyMatrix, &emptyMatrix); test_XOR(&emptyMatrix, &emptyMatrix, &emptyMatrix);
test_XOR(&emptyMatrix, &centerMatrix, &centerMatrix); test_XOR(&emptyMatrix, &centerMatrix, &centerMatrix);
@@ -328,7 +334,7 @@ fn test_xor_case() {
// // good // // good
// } // }
assert!(badMatrix.clone().xor(&emptyMatrix).is_err()); assert!(badMatrix.xor(&emptyMatrix).is_err());
// try { // try {
// badMatrix.clone().xor(emptyMatrix); // badMatrix.clone().xor(emptyMatrix);
// fail(); // fail();
@@ -344,7 +350,7 @@ pub fn matrix_to_string(result: &BitMatrix) -> String {
// for (int i = 0; i < result.getWidth(); i++) { // for (int i = 0; i < result.getWidth(); i++) {
builder.push(if result.get(i, 0) { '1' } else { '0' }); builder.push(if result.get(i, 0) { '1' } else { '0' });
} }
return builder; builder
} }
fn test_XOR(dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) { fn test_XOR(dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) {
@@ -378,7 +384,7 @@ fn get_expected(width: u32, height: u32) -> BitMatrix {
); );
i += 2; i += 2;
} }
return result; result
} }
fn get_input(width: u32, height: u32) -> BitMatrix { fn get_input(width: u32, height: u32) -> BitMatrix {
@@ -389,7 +395,7 @@ fn get_input(width: u32, height: u32) -> BitMatrix {
result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]); result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]);
i += 2; i += 2;
} }
return result; result
} }
// } // }

View File

@@ -33,9 +33,10 @@ use crate::common::StringUtils;
fn test_random() { fn test_random() {
let mut r = rand::thread_rng(); let mut r = rand::thread_rng();
let mut bytes: Vec<u8> = vec![0; 1000]; let mut bytes: Vec<u8> = vec![0; 1000];
for i in 0..bytes.len() { bytes.fill_with(|| r.gen());
bytes[i] = r.gen(); // for byte in &mut bytes {
} // *byte = r.gen();
// }
assert_eq!( assert_eq!(
encoding::all::UTF_8.name(), encoding::all::UTF_8.name(),
StringUtils::guessCharset(&bytes, &HashMap::new()).name() StringUtils::guessCharset(&bytes, &HashMap::new()).name()
@@ -102,7 +103,7 @@ fn test_utf16_le() {
); );
} }
fn do_test(bytes: &Vec<u8>, charset: EncodingRef, encoding: &str) { fn do_test(bytes: &[u8], charset: EncodingRef, encoding: &str) {
let guessedCharset = StringUtils::guessCharset(bytes, &HashMap::new()); let guessedCharset = StringUtils::guessCharset(bytes, &HashMap::new());
let guessedEncoding = StringUtils::guessEncoding(bytes, &HashMap::new()); let guessedEncoding = StringUtils::guessEncoding(bytes, &HashMap::new());
assert_eq!(charset.name(), guessedCharset.name()); assert_eq!(charset.name(), guessedCharset.name());

View File

@@ -47,16 +47,13 @@ impl BitArray {
pub fn with_size(size: usize) -> Self { pub fn with_size(size: usize) -> Self {
Self { Self {
bits: BitArray::makeArray(size), bits: BitArray::makeArray(size),
size: size, size,
} }
} }
// For testing only // For testing only
pub fn with_initial_values(bits: Vec<u32>, size: usize) -> Self { pub fn with_initial_values(bits: Vec<u32>, size: usize) -> Self {
Self { Self { bits, size }
bits: bits,
size: size,
}
} }
pub fn getSize(&self) -> usize { pub fn getSize(&self) -> usize {
@@ -64,7 +61,7 @@ impl BitArray {
} }
pub fn getSizeInBytes(&self) -> usize { pub fn getSizeInBytes(&self) -> usize {
return (self.size + 7) / 8; (self.size + 7) / 8
} }
fn ensure_capacity(&mut self, newSize: usize) { fn ensure_capacity(&mut self, newSize: usize) {
@@ -148,7 +145,7 @@ impl BitArray {
currentBits = !self.bits[bitsOffset] as i64; currentBits = !self.bits[bitsOffset] as i64;
} }
let result = (bitsOffset * 32) + currentBits.trailing_zeros() as usize; let result = (bitsOffset * 32) + currentBits.trailing_zeros() as usize;
return cmp::min(result, self.size); cmp::min(result, self.size)
} }
/** /**
@@ -171,9 +168,7 @@ impl BitArray {
pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> { pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> {
let mut end = end; let mut end = end;
if end < start || end > self.size { if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(None));
"end < start || start < 0 || end > self.size".to_owned(),
));
} }
if end == start { if end == start {
return Ok(()); return Ok(());
@@ -216,9 +211,7 @@ impl BitArray {
pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool, Exceptions> { pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool, Exceptions> {
let mut end = end; let mut end = end;
if end < start || end > self.size { if end < start || end > self.size {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(None));
"end < start || start < 0 || end > self.size".to_owned(),
));
} }
if end == start { if end == start {
return Ok(true); // empty range matches return Ok(true); // empty range matches
@@ -239,7 +232,7 @@ impl BitArray {
return Ok(false); return Ok(false);
} }
} }
return Ok(true); Ok(true)
} }
pub fn appendBit(&mut self, bit: bool) { pub fn appendBit(&mut self, bit: bool) {
@@ -260,9 +253,9 @@ impl BitArray {
*/ */
pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> { pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> {
if num_bits > 32 { if num_bits > 32 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Num bits must be between 0 and 32".to_owned(), "Num bits must be between 0 and 32".to_owned(),
)); )));
} }
if num_bits == 0 { if num_bits == 0 {
@@ -293,9 +286,9 @@ impl BitArray {
pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> { pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> {
if self.size != other.size { if self.size != other.size {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Sizes don't match".to_owned(), "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++) {
@@ -335,7 +328,7 @@ impl BitArray {
* significant bit is bit 0. * significant bit is bit 0.
*/ */
pub fn getBitArray(&self) -> &Vec<u32> { pub fn getBitArray(&self) -> &Vec<u32> {
return &self.bits; &self.bits
} }
/** /**
@@ -367,7 +360,7 @@ impl BitArray {
} }
fn makeArray(size: usize) -> Vec<u32> { fn makeArray(size: usize) -> Vec<u32> {
return vec![0; (size + 31) / 32]; vec![0; (size + 31) / 32]
} }
// @Override // @Override
@@ -396,10 +389,16 @@ impl fmt::Display for BitArray {
for i in 0..self.size { for i in 0..self.size {
//for (int i = 0; i < size; i++) { //for (int i = 0; i < size; i++) {
if (i & 0x07) == 0 { if (i & 0x07) == 0 {
_str.push_str(" "); _str.push(' ');
} }
_str.push_str(if self.get(i) { "X" } else { "." }); _str.push_str(if self.get(i) { "X" } else { "." });
} }
write!(f, "{}", _str) write!(f, "{}", _str)
} }
} }
impl Default for BitArray {
fn default() -> Self {
Self::new()
}
}

View File

@@ -65,9 +65,9 @@ impl BitMatrix {
*/ */
pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> { pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> {
if width < 1 || height < 1 { if width < 1 || height < 1 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Both dimensions must be greater than 0".to_owned(), "Both dimensions must be greater than 0".to_owned(),
)); )));
} }
Ok(Self { Ok(Self {
width, width,
@@ -101,17 +101,19 @@ impl BitMatrix {
let height: u32 = image.len().try_into().unwrap(); let height: u32 = image.len().try_into().unwrap();
let width: u32 = image[0].len().try_into().unwrap(); let width: u32 = image[0].len().try_into().unwrap();
let mut bits = BitMatrix::new(width, height).unwrap(); let mut bits = BitMatrix::new(width, height).unwrap();
for i in 0..height as usize { for (i, imageI) in image.iter().enumerate().take(height as usize) {
// for i in 0..height as usize {
//for (int i = 0; i < height; i++) { //for (int i = 0; i < height; i++) {
let imageI = &image[i]; // let imageI = &image[i];
for j in 0..width as usize { for (j, imageI_j) in imageI.iter().enumerate().take(width as usize) {
// for j in 0..width as usize {
//for (int j = 0; j < width; j++) { //for (int j = 0; j < width; j++) {
if imageI[j] { if *imageI_j {
bits.set(j as u32, i as u32); bits.set(j as u32, i as u32);
} }
} }
} }
return bits; bits
} }
pub fn parse_strings( pub fn parse_strings(
@@ -141,9 +143,9 @@ 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(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"row lengths do not match".to_owned(), "row lengths do not match".to_owned(),
)); )));
} }
rowStartPos = bitsPos; rowStartPos = bitsPos;
nRows += 1; nRows += 1;
@@ -158,10 +160,10 @@ impl BitMatrix {
bits[bitsPos] = false; bits[bitsPos] = false;
bitsPos += 1; bitsPos += 1;
} else { } else {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"illegal character encountered: {}", "illegal character encountered: {}",
string_representation[pos..].to_owned() string_representation[pos..].to_owned()
))); ))));
} }
} }
@@ -172,24 +174,25 @@ 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(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"row lengths do not match".to_owned(), "row lengths do not match".to_owned(),
)); )));
} }
nRows += 1; nRows += 1;
} }
let mut matrix = BitMatrix::new(rowLength.try_into().unwrap(), nRows)?; let mut matrix = BitMatrix::new(rowLength.try_into().unwrap(), nRows)?;
for i in 0..bitsPos { for (i, bit) in bits.iter().enumerate().take(bitsPos) {
// for i in 0..bitsPos {
//for (int i = 0; i < bitsPos; i++) { //for (int i = 0; i < bitsPos; i++) {
if bits[i] { if *bit {
matrix.set( matrix.set(
(i % rowLength).try_into().unwrap(), (i % rowLength).try_into().unwrap(),
(i / rowLength).try_into().unwrap(), (i / rowLength).try_into().unwrap(),
); );
} }
} }
return Ok(matrix); Ok(matrix)
} }
/** /**
@@ -201,15 +204,15 @@ impl BitMatrix {
*/ */
pub fn get(&self, x: u32, y: u32) -> bool { pub fn get(&self, x: u32, y: u32) -> bool {
let offset = y as usize * self.row_size + (x as usize / 32); let offset = y as usize * self.row_size + (x as usize / 32);
return ((self.bits[offset] >> (x & 0x1f)) & 1) != 0; ((self.bits[offset] >> (x & 0x1f)) & 1) != 0
} }
pub fn try_get(&self, x: u32, y: u32) -> Result<bool, Exceptions> { pub fn try_get(&self, x: u32, y: u32) -> Result<bool, Exceptions> {
let offset = y as usize * self.row_size + (x as usize / 32); let offset = y as usize * self.row_size + (x as usize / 32);
if offset > self.bits.len() { if offset > self.bits.len() {
return Err(Exceptions::IndexOutOfBoundsException("".to_owned())); return Err(Exceptions::IndexOutOfBoundsException(None));
} }
return Ok(((self.bits[offset] >> (x & 0x1f)) & 1) != 0); Ok(((self.bits[offset] >> (x & 0x1f)) & 1) != 0)
} }
pub fn check_in_bounds(&self, x: u32, y: u32) -> bool { pub fn check_in_bounds(&self, x: u32, y: u32) -> bool {
@@ -263,9 +266,9 @@ impl BitMatrix {
pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> { pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> {
if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size
{ {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"input matrix dimensions do not match".to_owned(), "input matrix dimensions do not match".to_owned(),
)); )));
} }
// let mut rowArray = BitArray::with_size(self.width as usize); // let mut rowArray = BitArray::with_size(self.width as usize);
for y in 0..self.height { for y in 0..self.height {
@@ -273,9 +276,10 @@ impl BitMatrix {
let offset = y as usize * self.row_size; let offset = y as usize * self.row_size;
let rowArray = mask.getRow(y); let rowArray = mask.getRow(y);
let row = rowArray.getBitArray(); let row = rowArray.getBitArray();
for x in 0..self.row_size { for (x, row_x) in row.iter().enumerate().take(self.row_size) {
// for x in 0..self.row_size {
//for (int x = 0; x < rowSize; x++) { //for (int x = 0; x < rowSize; x++) {
self.bits[offset + x] ^= row[x]; self.bits[offset + x] ^= *row_x;
} }
} }
Ok(()) Ok(())
@@ -314,16 +318,16 @@ impl BitMatrix {
// )); // ));
// } // }
if height < 1 || width < 1 { if height < 1 || width < 1 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Height and width must be at least 1".to_owned(), "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(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"The region must fit inside the matrix".to_owned(), "The region must fit inside the matrix".to_owned(),
)); )));
} }
for y in top..bottom { for y in top..bottom {
//for (int y = top; y < bottom; y++) { //for (int y = top; y < bottom; y++) {
@@ -361,7 +365,7 @@ impl BitMatrix {
//for (int x = 0; x < rowSize; x++) { //for (int x = 0; x < rowSize; x++) {
rw.setBulk(x * 32, self.bits[offset + x]); rw.setBulk(x * 32, self.bits[offset + x]);
} }
return rw; rw
} }
/** /**
@@ -395,9 +399,9 @@ impl BitMatrix {
self.rotate180(); self.rotate180();
Ok(()) Ok(())
} }
_ => Err(Exceptions::IllegalArgumentException( _ => Err(Exceptions::IllegalArgumentException(Some(
"degrees must be a multiple of 0, 90, 180, or 270".to_owned(), "degrees must be a multiple of 0, 90, 180, or 270".to_owned(),
)), ))),
} }
} }
@@ -497,7 +501,7 @@ impl BitMatrix {
return None; return None;
} }
return Some(vec![left, top, right - left + 1, bottom - top + 1]); Some(vec![left, top, right - left + 1, bottom - top + 1])
} }
/** /**
@@ -522,7 +526,7 @@ impl BitMatrix {
bit += 1; bit += 1;
} }
x += bit; x += bit;
return Some(vec![x as u32, y as u32]); Some(vec![x as u32, y as u32])
} }
pub fn getBottomRightOnBit(&self) -> Option<Vec<u32>> { pub fn getBottomRightOnBit(&self) -> Option<Vec<u32>> {
@@ -544,28 +548,28 @@ impl BitMatrix {
} }
x += bit; x += bit;
return Some(vec![x as u32, y as u32]); Some(vec![x as u32, y as u32])
} }
/** /**
* @return The width of the matrix * @return The width of the matrix
*/ */
pub fn getWidth(&self) -> u32 { pub fn getWidth(&self) -> u32 {
return self.width; self.width
} }
/** /**
* @return The height of the matrix * @return The height of the matrix
*/ */
pub fn getHeight(&self) -> u32 { pub fn getHeight(&self) -> u32 {
return self.height; self.height
} }
/** /**
* @return The row size of the matrix * @return The row size of the matrix
*/ */
pub fn getRowSize(&self) -> usize { pub fn getRowSize(&self) -> usize {
return self.row_size; self.row_size
} }
// @Override // @Override
@@ -594,7 +598,7 @@ impl BitMatrix {
* @return string representation of entire matrix utilizing given strings * @return string representation of entire matrix utilizing given strings
*/ */
pub fn toString(&self, setString: &str, unsetString: &str) -> String { pub fn toString(&self, setString: &str, unsetString: &str) -> String {
return self.buildToString(setString, unsetString, "\n"); self.buildToString(setString, unsetString, "\n")
} }
/** /**
@@ -624,7 +628,7 @@ impl BitMatrix {
} }
result.push_str(lineSeparator); result.push_str(lineSeparator);
} }
return result; result
} }
// @Override // @Override

View File

@@ -52,14 +52,14 @@ impl BitSource {
* @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}. * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
*/ */
pub fn getBitOffset(&self) -> usize { pub fn getBitOffset(&self) -> usize {
return self.bit_offset; self.bit_offset
} }
/** /**
* @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}. * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
*/ */
pub fn getByteOffset(&self) -> usize { pub fn getByteOffset(&self) -> usize {
return self.byte_offset; self.byte_offset
} }
/** /**
@@ -69,8 +69,10 @@ impl BitSource {
* @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, Exceptions> { pub fn readBits(&mut self, numBits: usize) -> Result<u32, Exceptions> {
if numBits < 1 || numBits > 32 || numBits > self.available() { if !(1..=32).contains(&numBits) || numBits > self.available() {
return Err(Exceptions::IllegalArgumentException(numBits.to_string())); return Err(Exceptions::IllegalArgumentException(Some(
numBits.to_string(),
)));
} }
let mut result: u32 = 0; let mut result: u32 = 0;
@@ -96,7 +98,7 @@ impl BitSource {
// Next read whole bytes // Next read whole bytes
if num_bits > 0 { if num_bits > 0 {
while num_bits >= 8 { while num_bits >= 8 {
result = (result << 8) | (self.bytes[self.byte_offset] & 0xFF) as u32; result = (result << 8) | self.bytes[self.byte_offset] as u32;
// result = ((result as u16) << 8) as u8 | (self.bytes[self.byte_offset]); // result = ((result as u16) << 8) as u8 | (self.bytes[self.byte_offset]);
self.byte_offset += 1; self.byte_offset += 1;
num_bits -= 8; num_bits -= 8;
@@ -112,13 +114,13 @@ impl BitSource {
} }
} }
return Ok(result); Ok(result)
} }
/** /**
* @return number of bits that can be read successfully * @return number of bits that can be read successfully
*/ */
pub fn available(&self) -> usize { pub fn available(&self) -> usize {
return 8 * (self.bytes.len() - self.byte_offset) - self.bit_offset; 8 * (self.bytes.len() - self.byte_offset) - self.bit_offset
} }
} }

View File

@@ -65,3 +65,9 @@ impl BitSourceBuilder {
&self.output &self.output
} }
} }
impl Default for BitSourceBuilder {
fn default() -> Self {
Self::new()
}
}

View File

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

View File

@@ -66,9 +66,7 @@ impl GridSampler for DefaultGridSampler {
transform: &PerspectiveTransform, transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix, Exceptions> {
if dimensionX == 0 || dimensionY == 0 { if dimensionX == 0 || dimensionY == 0 {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(None));
"getNotFoundInstance".to_owned(),
));
} }
let mut bits = BitMatrix::new(dimensionX, dimensionY)?; let mut bits = BitMatrix::new(dimensionX, dimensionY)?;
let mut points = vec![0_f32; 2 * dimensionX as usize]; let mut points = vec![0_f32; 2 * dimensionX as usize];
@@ -94,9 +92,9 @@ impl GridSampler for DefaultGridSampler {
if points[x].floor() as u32 >= image.getWidth() if points[x].floor() as u32 >= image.getWidth()
|| points[x + 1].floor() as u32 >= image.getHeight() || points[x + 1].floor() as u32 >= image.getHeight()
{ {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(Some(
"index out of bounds, see documentation in file for explanation".to_owned(), "index out of bounds, see documentation in file for explanation".to_owned(),
)); )));
} }
if image.get(points[x].floor() as u32, points[x + 1].floor() as u32) { if image.get(points[x].floor() as u32, points[x + 1].floor() as u32) {
// Black(-ish) pixel // Black(-ish) pixel
@@ -115,6 +113,6 @@ impl GridSampler for DefaultGridSampler {
// throw NotFoundException.getNotFoundInstance(); // throw NotFoundException.getNotFoundInstance();
// } // }
} }
return Ok(bits); Ok(bits)
} }
} }

View File

@@ -31,7 +31,7 @@ use std::{f32, i32};
* @return nearest {@code int} * @return nearest {@code int}
*/ */
pub fn round(d: f32) -> i32 { pub fn round(d: f32) -> i32 {
return (d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32; (d + (if d < 0.0f32 { -0.5f32 } else { 0.5f32 })) as i32
} }
/** /**
@@ -44,7 +44,7 @@ pub fn round(d: f32) -> i32 {
pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 { pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 {
let xDiff: f64 = (aX - bX).into(); let xDiff: f64 = (aX - bX).into();
let yDiff: f64 = (aY - bY).into(); let yDiff: f64 = (aY - bY).into();
return (xDiff * xDiff + yDiff * yDiff).sqrt() as f32; (xDiff * xDiff + yDiff * yDiff).sqrt() as f32
} }
/** /**
@@ -57,7 +57,7 @@ pub fn distance_float(aX: f32, aY: f32, bX: f32, bY: f32) -> f32 {
pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 { pub fn distance_int(aX: i32, aY: i32, bX: i32, bY: i32) -> f32 {
let xDiff: f64 = (aX - bX).into(); let xDiff: f64 = (aX - bX).into();
let yDiff: f64 = (aY - bY).into(); let yDiff: f64 = (aY - bY).into();
return (xDiff * xDiff + yDiff * yDiff).sqrt() as f32; (xDiff * xDiff + yDiff * yDiff).sqrt() as f32
} }
/** /**
@@ -69,7 +69,7 @@ pub fn sum(array: &[i32]) -> i32 {
for a in array { for a in array {
count += a; count += a;
} }
return count; count
} }
#[cfg(test)] #[cfg(test)]
@@ -120,7 +120,7 @@ mod tests {
#[test] #[test]
fn testSum() { fn testSum() {
assert_eq!(0, MathUtils::sum(&vec![])); assert_eq!(0, MathUtils::sum(&[]));
assert_eq!(1, MathUtils::sum(&[1])); assert_eq!(1, MathUtils::sum(&[1]));
assert_eq!(4, MathUtils::sum(&[1, 3])); assert_eq!(4, MathUtils::sum(&[1, 3]));
assert_eq!(0, MathUtils::sum(&[-1, 1])); assert_eq!(0, MathUtils::sum(&[-1, 1]));

View File

@@ -55,8 +55,8 @@ impl MonochromeRectangleDetector {
let width = self.image.getWidth() as i32; let width = self.image.getWidth() as i32;
let halfHeight = height / 2; let halfHeight = height / 2;
let halfWidth = width / 2; let halfWidth = width / 2;
let deltaY = 1.max(height as i32 / (MAX_MODULES * 8)); let deltaY = 1.max(height / (MAX_MODULES * 8));
let deltaX = 1.max(width as i32 / (MAX_MODULES * 8)); let deltaX = 1.max(width / (MAX_MODULES * 8));
let mut top = 0; let mut top = 0;
let mut bottom = height; let mut bottom = height;
@@ -124,7 +124,7 @@ impl MonochromeRectangleDetector {
halfWidth / 4, halfWidth / 4,
)?; )?;
return Ok(vec![pointA, pointB, pointC, pointD]); Ok(vec![pointA, pointB, pointC, pointD])
} }
/** /**
@@ -161,14 +161,13 @@ impl MonochromeRectangleDetector {
let mut y: i32 = centerY; let mut y: i32 = centerY;
let mut x: i32 = centerX; let mut x: i32 = centerX;
while y < bottom && y >= top && x < right && x >= left { while y < bottom && y >= top && x < right && x >= left {
let range: Option<Vec<i32>>; let range: Option<Vec<i32>> = if deltaX == 0 {
if deltaX == 0 {
// horizontal slices, up and down // horizontal slices, up and down
range = self.blackWhiteRange(y, maxWhiteRun, left, right, true); self.blackWhiteRange(y, maxWhiteRun, left, right, true)
} else { } else {
// vertical slices, left and right // vertical slices, left and right
range = self.blackWhiteRange(x, maxWhiteRun, top, bottom, false); self.blackWhiteRange(x, maxWhiteRun, top, bottom, false)
} };
if range.is_none() { if range.is_none() {
if let Some(lastRange) = lastRange_z { if let Some(lastRange) = lastRange_z {
// lastRange was found // lastRange was found
@@ -178,7 +177,7 @@ impl MonochromeRectangleDetector {
if lastRange[1] > centerX { if lastRange[1] > centerX {
// straddle, choose one or the other based on direction // straddle, choose one or the other based on direction
return Ok(RXingResultPoint::new( return Ok(RXingResultPoint::new(
lastRange[if deltaY > 0 { 0 } else { 1 }] as f32, lastRange[usize::from(deltaY <= 0)] as f32,
lastY as f32, lastY as f32,
)); ));
} }
@@ -192,7 +191,7 @@ impl MonochromeRectangleDetector {
if lastRange[1] > centerY { if lastRange[1] > centerY {
return Ok(RXingResultPoint::new( return Ok(RXingResultPoint::new(
lastX as f32, lastX as f32,
lastRange[if deltaX < 0 { 0 } else { 1 }] as f32, lastRange[usize::from(deltaX >= 0)] as f32,
)); ));
} }
return Ok(RXingResultPoint::new(lastX as f32, lastRange[0] as f32)); return Ok(RXingResultPoint::new(lastX as f32, lastRange[0] as f32));
@@ -202,13 +201,13 @@ impl MonochromeRectangleDetector {
} }
} }
} else { } else {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
lastRange_z = range; lastRange_z = range;
y += deltaY; y += deltaY;
x += deltaX x += deltaX
} }
return Err(Exceptions::NotFoundException("".to_owned())); Err(Exceptions::NotFoundException(None))
} }
/** /**
@@ -243,10 +242,10 @@ impl MonochromeRectangleDetector {
} else { } else {
self.image.get(fixedDimension as u32, start as u32) self.image.get(fixedDimension as u32, start as u32)
} { } {
start = start - 1; start -= 1;
} else { } else {
let whiteRunStart = start; let whiteRunStart = start;
start = start - 1; start -= 1;
while start >= minDim while start >= minDim
&& !(if horizontal { && !(if horizontal {
self.image.get(start as u32, fixedDimension as u32) self.image.get(start as u32, fixedDimension as u32)
@@ -254,7 +253,7 @@ impl MonochromeRectangleDetector {
self.image.get(fixedDimension as u32, start as u32) self.image.get(fixedDimension as u32, start as u32)
}) })
{ {
start = start - 1; start -= 1;
} }
let whiteRunSize = whiteRunStart - start; let whiteRunSize = whiteRunStart - start;
if start < minDim || whiteRunSize > maxWhiteRun { if start < minDim || whiteRunSize > maxWhiteRun {
@@ -263,7 +262,7 @@ impl MonochromeRectangleDetector {
} }
} }
} }
start = start + 1; start += 1;
// Then try right/down // Then try right/down
let mut end = center; let mut end = center;
@@ -273,10 +272,10 @@ impl MonochromeRectangleDetector {
} else { } else {
self.image.get(fixedDimension as u32, end as u32) self.image.get(fixedDimension as u32, end as u32)
} { } {
end = end + 1; end += 1;
} else { } else {
let whiteRunStart = end; let whiteRunStart = end;
end = end + 1; end += 1;
while end < maxDim while end < maxDim
&& !(if horizontal { && !(if horizontal {
self.image.get(end as u32, fixedDimension as u32) self.image.get(end as u32, fixedDimension as u32)
@@ -284,7 +283,7 @@ impl MonochromeRectangleDetector {
self.image.get(fixedDimension as u32, end as u32) self.image.get(fixedDimension as u32, end as u32)
}) })
{ {
end = end + 1; end += 1;
} }
let whiteRunSize = end - whiteRunStart; let whiteRunSize = end - whiteRunStart;
if end >= maxDim || whiteRunSize > maxWhiteRun { if end >= maxDim || whiteRunSize > maxWhiteRun {
@@ -293,12 +292,12 @@ impl MonochromeRectangleDetector {
} }
} }
} }
end = end - 1; end -= 1;
return if end > start { if end > start {
Some(vec![start, end]) Some(vec![start, end])
} else { } else {
None None
}; }
} }
} }

View File

@@ -72,17 +72,17 @@ impl WhiteRectangleDetector {
|| downInit >= image.getHeight() as i32 || downInit >= image.getHeight() as i32
|| rightInit >= image.getWidth() as i32 || rightInit >= image.getWidth() as i32
{ {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
Ok(Self { Ok(Self {
image: image.clone(), image: image.clone(),
height: image.getHeight() as i32, height: image.getHeight() as i32,
width: image.getWidth() as i32, width: image.getWidth() as i32,
leftInit: leftInit, leftInit,
rightInit: rightInit, rightInit,
downInit: downInit, downInit,
upInit: upInit, upInit,
}) })
} }
@@ -218,7 +218,7 @@ impl WhiteRectangleDetector {
} }
if z.is_none() { if z.is_none() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let mut t: Option<RXingResultPoint> = None; let mut t: Option<RXingResultPoint> = None;
@@ -236,7 +236,7 @@ impl WhiteRectangleDetector {
} }
if t.is_none() { if t.is_none() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let mut x: Option<RXingResultPoint> = None; let mut x: Option<RXingResultPoint> = None;
@@ -254,7 +254,7 @@ impl WhiteRectangleDetector {
} }
if x.is_none() { if x.is_none() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let mut y: Option<RXingResultPoint> = None; let mut y: Option<RXingResultPoint> = None;
@@ -272,12 +272,12 @@ impl WhiteRectangleDetector {
} }
if y.is_none() { if y.is_none() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
return Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap())); Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap()))
} else { } else {
return Err(Exceptions::NotFoundException("".to_owned())); Err(Exceptions::NotFoundException(None))
} }
} }
@@ -299,7 +299,7 @@ impl WhiteRectangleDetector {
return Some(RXingResultPoint::new(x as f32, y as f32)); return Some(RXingResultPoint::new(x as f32, y as f32));
} }
} }
return None; None
} }
/** /**
@@ -339,19 +339,19 @@ impl WhiteRectangleDetector {
let tj = t.getY(); let tj = t.getY();
if yi < self.width as f32 / 2.0f32 { if yi < self.width as f32 / 2.0f32 {
return vec![ vec![
RXingResultPoint::new(ti - CORR as f32, tj + CORR as f32), RXingResultPoint::new(ti - CORR as f32, tj + CORR as f32),
RXingResultPoint::new(zi + CORR as f32, zj + CORR as f32), RXingResultPoint::new(zi + CORR as f32, zj + CORR as f32),
RXingResultPoint::new(xi - CORR as f32, xj - CORR as f32), RXingResultPoint::new(xi - CORR as f32, xj - CORR as f32),
RXingResultPoint::new(yi + CORR as f32, yj - CORR as f32), RXingResultPoint::new(yi + CORR as f32, yj - CORR as f32),
]; ]
} else { } else {
return vec![ vec![
RXingResultPoint::new(ti + CORR as f32, tj + CORR as f32), RXingResultPoint::new(ti + CORR as f32, tj + CORR as f32),
RXingResultPoint::new(zi + CORR as f32, zj - CORR as f32), RXingResultPoint::new(zi + CORR as f32, zj - CORR as f32),
RXingResultPoint::new(xi - CORR as f32, xj + CORR as f32), RXingResultPoint::new(xi - CORR as f32, xj + CORR as f32),
RXingResultPoint::new(yi - CORR as f32, yj - CORR as f32), RXingResultPoint::new(yi - CORR as f32, yj - CORR as f32),
]; ]
} }
} }
@@ -379,6 +379,6 @@ impl WhiteRectangleDetector {
} }
} }
return false; false
} }
} }

View File

@@ -141,7 +141,7 @@ impl ECIEncoderSet {
// for (CharsetEncoder encoder : ENCODERS) { // for (CharsetEncoder encoder : ENCODERS) {
if encoder if encoder
.encode( .encode(
&stringToEncode.get(i).unwrap(), stringToEncode.get(i).unwrap(),
encoding::EncoderTrap::Strict, encoding::EncoderTrap::Strict,
) )
.is_ok() .is_ok()
@@ -185,9 +185,10 @@ impl ECIEncoderSet {
//Compute priorityEncoderIndex by looking up priorityCharset in encoders //Compute priorityEncoderIndex by looking up priorityCharset in encoders
// if priorityCharset != null { // if priorityCharset != null {
if priorityCharset.is_some() { if priorityCharset.is_some() {
for i in 0..encoders.len() { // for i in 0..encoders.len() {
for (i, encoder) in encoders.iter().enumerate() {
// for (int i = 0; i < encoders.length; i++) { // for (int i = 0; i < encoders.length; i++) {
if priorityCharset.as_ref().unwrap().name() == encoders[i].name() { if priorityCharset.as_ref().unwrap().name() == encoder.name() {
priorityEncoderIndexValue = Some(i); priorityEncoderIndexValue = Some(i);
break; break;
} }
@@ -197,13 +198,17 @@ impl ECIEncoderSet {
//invariants //invariants
assert_eq!(encoders[0].name(), encoding::all::ISO_8859_1.name()); assert_eq!(encoders[0].name(), encoding::all::ISO_8859_1.name());
Self { Self {
encoders: encoders, encoders,
priorityEncoderIndex: priorityEncoderIndexValue, priorityEncoderIndex: priorityEncoderIndexValue,
} }
} }
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
return self.encoders.len(); self.encoders.len()
}
pub fn is_empty(&self) -> bool {
self.encoders.is_empty()
} }
pub fn getCharsetName(&self, index: usize) -> &'static str { pub fn getCharsetName(&self, index: usize) -> &'static str {
@@ -213,7 +218,7 @@ impl ECIEncoderSet {
pub fn getCharset(&self, index: usize) -> EncodingRef { pub fn getCharset(&self, index: usize) -> EncodingRef {
assert!(index < self.len()); assert!(index < self.len());
return self.encoders[index]; self.encoders[index]
} }
pub fn getECIValue(&self, encoderIndex: usize) -> u32 { pub fn getECIValue(&self, encoderIndex: usize) -> u32 {
@@ -240,9 +245,9 @@ impl ECIEncoderSet {
pub fn encode_char(&self, c: &str, encoderIndex: usize) -> Vec<u8> { pub fn encode_char(&self, c: &str, encoderIndex: usize) -> Vec<u8> {
assert!(encoderIndex < self.len()); assert!(encoderIndex < self.len());
let encoder = self.encoders[encoderIndex]; let encoder = self.encoders[encoderIndex];
let enc_data = encoder.encode(&c.to_string(), encoding::EncoderTrap::Strict); let enc_data = encoder.encode(c, encoding::EncoderTrap::Strict);
assert!(enc_data.is_ok()); assert!(enc_data.is_ok());
return enc_data.unwrap(); enc_data.unwrap()
} }
pub fn encode_string(&self, s: &str, encoderIndex: usize) -> Vec<u8> { pub fn encode_string(&self, s: &str, encoderIndex: usize) -> Vec<u8> {

View File

@@ -163,8 +163,8 @@ impl ECIStringBuilder {
/** /**
* @return true iff nothing has been appended * @return true iff nothing has been appended
*/ */
pub fn is_empty(&self) -> bool { pub fn is_empty(&mut self) -> bool {
return self.current_bytes.is_empty() && self.result.is_empty(); self.current_bytes.is_empty() && self.result.is_empty()
} }
pub fn build_result(mut self) -> Self { pub fn build_result(mut self) -> Self {
@@ -180,3 +180,9 @@ impl fmt::Display for ECIStringBuilder {
write!(f, "{}", self.result) write!(f, "{}", self.result)
} }
} }
impl Default for ECIStringBuilder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -72,9 +72,10 @@ impl Binarizer for GlobalHistogramBinarizer {
if width < 3 { if width < 3 {
// Special case for very small images // Special case for very small images
for x in 0..width { for (x, lum) in localLuminances.iter().enumerate().take(width) {
// for x in 0..width {
// for (int x = 0; x < width; x++) { // for (int x = 0; x < width; x++) {
if (localLuminances[x] as u32) < blackPoint { if (*lum as u32) < blackPoint {
row.set(x); row.set(x);
} }
} }
@@ -109,7 +110,7 @@ impl Binarizer for GlobalHistogramBinarizer {
&self, &self,
source: Box<dyn crate::LuminanceSource>, source: Box<dyn crate::LuminanceSource>,
) -> Rc<RefCell<dyn Binarizer>> { ) -> Rc<RefCell<dyn Binarizer>> {
return Rc::new(RefCell::new(GlobalHistogramBinarizer::new(source))); Rc::new(RefCell::new(GlobalHistogramBinarizer::new(source)))
} }
fn getWidth(&self) -> usize { fn getWidth(&self) -> usize {
@@ -134,7 +135,7 @@ impl GlobalHistogramBinarizer {
height: source.getHeight(), height: source.getHeight(),
black_matrix: None, black_matrix: None,
black_row_cache: vec![None; source.getHeight()], black_row_cache: vec![None; source.getHeight()],
source: source, source,
} }
} }
@@ -172,7 +173,7 @@ impl GlobalHistogramBinarizer {
let offset = y * width; let offset = y * width;
for x in 0..width { for x in 0..width {
// for (int x = 0; x < width; x++) { // for (int x = 0; x < width; x++) {
let pixel = localLuminances[offset + x] & 0xff; let pixel = localLuminances[offset + x];
if (pixel as u32) < blackPoint { if (pixel as u32) < blackPoint {
matrix.set(x as u32, y as u32); matrix.set(x as u32, y as u32);
} }
@@ -198,25 +199,27 @@ impl GlobalHistogramBinarizer {
let mut maxBucketCount = 0; let mut maxBucketCount = 0;
let mut firstPeak = 0; let mut firstPeak = 0;
let mut firstPeakSize = 0; let mut firstPeakSize = 0;
for x in 0..numBuckets { for (x, bucket) in buckets.iter().enumerate().take(numBuckets) {
// for x in 0..numBuckets {
// for (int x = 0; x < numBuckets; x++) { // for (int x = 0; x < numBuckets; x++) {
if buckets[x] > firstPeakSize { if *bucket > firstPeakSize {
firstPeak = x; firstPeak = x;
firstPeakSize = buckets[x]; firstPeakSize = *bucket;
} }
if buckets[x] > maxBucketCount { if *bucket > maxBucketCount {
maxBucketCount = buckets[x]; maxBucketCount = *bucket;
} }
} }
// Find the second-tallest peak which is somewhat far from the tallest peak. // Find the second-tallest peak which is somewhat far from the tallest peak.
let mut secondPeak = 0; let mut secondPeak = 0;
let mut secondPeakScore = 0; let mut secondPeakScore = 0;
for x in 0..numBuckets { for (x, bucket) in buckets.iter().enumerate().take(numBuckets) {
// for x in 0..numBuckets {
// for (int x = 0; x < numBuckets; x++) { // for (int x = 0; x < numBuckets; x++) {
let distanceToBiggest = (x as i32 - firstPeak as i32).abs() as u32; let distanceToBiggest = (x as i32 - firstPeak as i32).unsigned_abs();
// Encourage more distant second peaks by multiplying by square of distance. // Encourage more distant second peaks by multiplying by square of distance.
let score = buckets[x] * distanceToBiggest as u32 * distanceToBiggest as u32; let score = *bucket * distanceToBiggest * distanceToBiggest;
if score > secondPeakScore { if score > secondPeakScore {
secondPeak = x; secondPeak = x;
secondPeakScore = score; secondPeakScore = score;
@@ -231,9 +234,9 @@ impl GlobalHistogramBinarizer {
// If there is too little contrast in the image to pick a meaningful black point, throw rather // 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. // than waste time trying to decode the image, and risk false positives.
if secondPeak - firstPeak <= numBuckets / 16 { if secondPeak - firstPeak <= numBuckets / 16 {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(Some(
"secondPeak - firstPeak <= numBuckets / 16 ".to_owned(), "secondPeak - firstPeak <= numBuckets / 16 ".to_owned(),
)); )));
} }
// Find a valley between them that is low and closer to the white peak. // Find a valley between them that is low and closer to the white peak.

View File

@@ -144,9 +144,7 @@ pub trait GridSampler {
let x = points[offset] as i32; let x = points[offset] as i32;
let y = points[offset + 1] 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.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(None));
"getNotFoundInstance".to_owned(),
));
} }
nudged = false; nudged = false;
if x == -1 { if x == -1 {
@@ -173,9 +171,7 @@ pub trait GridSampler {
let x = points[offset as usize] as i32; let x = points[offset as usize] as i32;
let y = points[offset as usize + 1] 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.try_into().unwrap() || y < -1 || y > height.try_into().unwrap() {
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(None));
"getNotFoundInstance".to_owned(),
));
} }
nudged = false; nudged = false;
if x == -1 { if x == -1 {

View File

@@ -99,16 +99,16 @@ impl HybridBinarizer {
let ghb = GlobalHistogramBinarizer::new(source); let ghb = GlobalHistogramBinarizer::new(source);
Self { Self {
black_matrix: None, black_matrix: None,
ghb: ghb, ghb,
} }
} }
fn calculateBlackMatrix(ghb: &mut GlobalHistogramBinarizer) -> Result<BitMatrix, Exceptions> { fn calculateBlackMatrix(ghb: &mut GlobalHistogramBinarizer) -> Result<BitMatrix, Exceptions> {
let matrix; // let matrix;
let source = ghb.getLuminanceSource(); let source = ghb.getLuminanceSource();
let width = source.getWidth(); let width = source.getWidth();
let height = source.getHeight(); let height = source.getHeight();
if width >= HybridBinarizer::MINIMUM_DIMENSION let matrix = if width >= HybridBinarizer::MINIMUM_DIMENSION
&& height >= HybridBinarizer::MINIMUM_DIMENSION && height >= HybridBinarizer::MINIMUM_DIMENSION
{ {
let luminances = source.getMatrix(); let luminances = source.getMatrix();
@@ -138,12 +138,12 @@ impl HybridBinarizer {
&black_points, &black_points,
&mut new_matrix, &mut new_matrix,
); );
matrix = Ok(new_matrix); Ok(new_matrix)
} else { } else {
// If the image is too small, fall back to the global histogram approach. // If the image is too small, fall back to the global histogram approach.
let m = ghb.getBlackMatrix()?; let m = ghb.getBlackMatrix()?;
matrix = Ok(m.clone()); Ok(m.clone())
} };
// dbg!(matrix.to_string()); // dbg!(matrix.to_string());
matrix matrix
} }
@@ -159,7 +159,7 @@ impl HybridBinarizer {
sub_height: u32, sub_height: u32,
width: u32, width: u32,
height: u32, height: u32,
black_points: &Vec<Vec<u32>>, black_points: &[Vec<u32>],
matrix: &mut BitMatrix, matrix: &mut BitMatrix,
) { ) {
let maxYOffset = height - HybridBinarizer::BLOCK_SIZE as u32; let maxYOffset = height - HybridBinarizer::BLOCK_SIZE as u32;

View File

@@ -52,7 +52,7 @@ impl ECIInput for MinimalECIInput {
* @return the number of {@code char}s in this sequence * @return the number of {@code char}s in this sequence
*/ */
fn length(&self) -> usize { fn length(&self) -> usize {
return self.bytes.len(); self.bytes.len()
} }
/** /**
@@ -73,13 +73,15 @@ impl ECIInput for MinimalECIInput {
*/ */
fn charAt(&self, index: usize) -> Result<char, Exceptions> { fn charAt(&self, index: usize) -> Result<char, Exceptions> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(),
)));
} }
if self.isECI(index as u32)? { if self.isECI(index as u32)? {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"value at {} is not a character but an ECI", "value at {} is not a character but an ECI",
index index
))); ))));
} }
if self.isFNC1(index)? { if self.isFNC1(index)? {
Ok(self.fnc1 as u8 as char) Ok(self.fnc1 as u8 as char)
@@ -110,16 +112,18 @@ impl ECIInput for MinimalECIInput {
*/ */
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> { fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> {
if start > end || end > self.length() { if start > end || end > self.length() {
return Err(Exceptions::IndexOutOfBoundsException(start.to_string())); return Err(Exceptions::IndexOutOfBoundsException(Some(
start.to_string(),
)));
} }
let mut result = String::new(); let mut result = String::new();
for i in start..end { for i in start..end {
// for (int i = start; i < end; i++) { // for (int i = start; i < end; i++) {
if self.isECI(i as u32)? { if self.isECI(i as u32)? {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"value at {} is not a character but an ECI", "value at {} is not a character but an ECI",
i i
))); ))));
} }
result.push_str(&self.charAt(i)?.to_string()); result.push_str(&self.charAt(i)?.to_string());
} }
@@ -139,7 +143,9 @@ impl ECIInput for MinimalECIInput {
*/ */
fn isECI(&self, index: u32) -> Result<bool, Exceptions> { fn isECI(&self, index: u32) -> Result<bool, Exceptions> {
if index >= self.length() as u32 { if index >= self.length() as u32 {
return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(),
)));
} }
Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX) Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX)
} }
@@ -164,19 +170,21 @@ impl ECIInput for MinimalECIInput {
*/ */
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> { fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(),
)));
} }
if !self.isECI(index as u32)? { if !self.isECI(index as u32)? {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"value at {} is not an ECI but a character", "value at {} is not an ECI but a character",
index index
))); ))));
} }
Ok((self.bytes[index] as u32 - 256) as i32) Ok((self.bytes[index] as u32 - 256) as i32)
} }
fn haveNCharacters(&self, index: usize, n: usize) -> bool { fn haveNCharacters(&self, index: usize, n: usize) -> bool {
if index + n - 1 >= self.bytes.len() { if index + n > self.bytes.len() {
return false; return false;
} }
for i in 0..n { for i in 0..n {
@@ -185,7 +193,7 @@ impl ECIInput for MinimalECIInput {
return false; return false;
} }
} }
return true; true
} }
} }
impl MinimalECIInput { impl MinimalECIInput {
@@ -210,13 +218,14 @@ impl MinimalECIInput {
let bytes = if encoderSet.len() == 1 { let bytes = if encoderSet.len() == 1 {
//optimization for the case when all can be encoded without ECI in ISO-8859-1 //optimization for the case when all can be encoded without ECI in ISO-8859-1
let mut bytes_hld = vec![0; stringToEncode.len()]; let mut bytes_hld = vec![0; stringToEncode.len()];
for i in 0..stringToEncode.len() { for (i, byt) in bytes_hld.iter_mut().enumerate().take(stringToEncode.len()) {
// for i in 0..stringToEncode.len() {
// for (int i = 0; i < bytes.length; i++) { // for (int i = 0; i < bytes.length; i++) {
let c = stringToEncode.get(i).unwrap(); let c = stringToEncode.get(i).unwrap();
bytes_hld[i] = if fnc1.is_some() && c == fnc1.as_ref().unwrap() { *byt = if fnc1.is_some() && c == fnc1.as_ref().unwrap() {
1000 1000
} else { } else {
c.chars().nth(0).unwrap() as u16 c.chars().next().unwrap() as u16
}; };
} }
bytes_hld bytes_hld
@@ -225,10 +234,10 @@ impl MinimalECIInput {
}; };
Self { Self {
bytes: bytes, bytes,
fnc1: if let Some(fnc1_exists) = fnc1 { fnc1: if let Some(fnc1_exists) = fnc1 {
//}.as_ref().unwrap().chars().nth(0).unwrap() as u16, //}.as_ref().unwrap().chars().nth(0).unwrap() as u16,
fnc1_exists.chars().nth(0).unwrap() as u16 fnc1_exists.chars().next().unwrap() as u16
} else { } else {
1000 1000
}, },
@@ -252,12 +261,14 @@ impl MinimalECIInput {
*/ */
pub fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> { pub fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> {
if index >= self.length() { if index >= self.length() {
return Err(Exceptions::IndexOutOfBoundsException(index.to_string())); return Err(Exceptions::IndexOutOfBoundsException(Some(
index.to_string(),
)));
} }
Ok(self.bytes[index] == 1000) Ok(self.bytes[index] == 1000)
} }
fn addEdge(edges: &mut Vec<Vec<Option<Rc<InputEdge>>>>, to: usize, edge: Rc<InputEdge>) { fn addEdge(edges: &mut [Vec<Option<Rc<InputEdge>>>], to: usize, edge: Rc<InputEdge>) {
if edges[to][edge.encoderIndex].is_none() if edges[to][edge.encoderIndex].is_none()
|| edges[to][edge.encoderIndex] || edges[to][edge.encoderIndex]
.clone() .clone()
@@ -272,7 +283,7 @@ impl MinimalECIInput {
fn addEdges( fn addEdges(
stringToEncode: &str, stringToEncode: &str,
encoderSet: &ECIEncoderSet, encoderSet: &ECIEncoderSet,
edges: &mut Vec<Vec<Option<Rc<InputEdge>>>>, edges: &mut [Vec<Option<Rc<InputEdge>>>],
from: usize, from: usize,
previous: Option<Rc<InputEdge>>, previous: Option<Rc<InputEdge>>,
fnc1: Option<&str>, fnc1: Option<&str>,
@@ -285,7 +296,7 @@ impl MinimalECIInput {
//if let Some(fnc1) = fnc1 { //if let Some(fnc1) = fnc1 {
if encoderSet.getPriorityEncoderIndex().is_some() if encoderSet.getPriorityEncoderIndex().is_some()
&& ((fnc1.is_some() && ((fnc1.is_some()
&& ch.chars().nth(0).unwrap() == fnc1.as_ref().unwrap().chars().nth(0).unwrap()) && ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap())
|| encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex().unwrap())) || encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex().unwrap()))
{ {
start = encoderSet.getPriorityEncoderIndex().unwrap(); start = encoderSet.getPriorityEncoderIndex().unwrap();
@@ -296,7 +307,7 @@ impl MinimalECIInput {
for i in start..end { for i in start..end {
// for (int i = start; i < end; i++) { // for (int i = start; i < end; i++) {
if (fnc1.is_some() if (fnc1.is_some()
&& ch.chars().nth(0).unwrap() == fnc1.as_ref().unwrap().chars().nth(0).unwrap()) && ch.chars().next().unwrap() == fnc1.as_ref().unwrap().chars().next().unwrap())
|| encoderSet.canEncode(ch, i) || encoderSet.canEncode(ch, i)
{ {
Self::addEdge( Self::addEdge(
@@ -380,19 +391,17 @@ impl MinimalECIInput {
// 0..0, // 0..0,
// [256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16], // [256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16],
// ); // );
intsAL.insert( intsAL.insert(0, 256_u16 + encoderSet.getECIValue(c.encoderIndex) as u16);
0,
256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16,
);
} }
current = c.previous.clone(); current = c.previous.clone();
} }
let mut ints = vec![0; intsAL.len()]; let mut ints = vec![0; intsAL.len()];
for i in 0..ints.len() { // for i in 0..ints.len() {
// for (int i = 0; i < ints.length; i++) { // // for (int i = 0; i < ints.length; i++) {
ints[i] = *intsAL.get(i).unwrap() as u16; // ints[i] = *intsAL.get(i).unwrap();
} // }
return ints; ints[..].copy_from_slice(&intsAL[..]);
ints
} }
} }
@@ -432,7 +441,7 @@ impl InputEdge {
String::from(c) String::from(c)
}, },
encoderIndex, encoderIndex,
previous: Some(prev.clone()), previous: Some(prev),
cachedTotalSize: size, cachedTotalSize: size,
} }
} else { } else {

View File

@@ -81,7 +81,7 @@ impl PerspectiveTransform {
let q_to_s = PerspectiveTransform::quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); let q_to_s = PerspectiveTransform::quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
let s_to_q = let s_to_q =
PerspectiveTransform::squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); PerspectiveTransform::squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
return s_to_q.times(&q_to_s); s_to_q.times(&q_to_s)
} }
pub fn transform_points_single(&self, points: &mut [f32]) { pub fn transform_points_single(&self, points: &mut [f32]) {
@@ -133,7 +133,7 @@ impl PerspectiveTransform {
let dy3 = y0 - y1 + y2 - y3; let dy3 = y0 - y1 + y2 - y3;
if dx3 == 0.0f32 && dy3 == 0.0f32 { if dx3 == 0.0f32 && dy3 == 0.0f32 {
// Affine // Affine
return PerspectiveTransform::new( PerspectiveTransform::new(
x1 - x0, x1 - x0,
x2 - x1, x2 - x1,
x0, x0,
@@ -143,7 +143,7 @@ impl PerspectiveTransform {
0.0f32, 0.0f32,
0.0f32, 0.0f32,
1.0f32, 1.0f32,
); )
} else { } else {
let dx1 = x1 - x2; let dx1 = x1 - x2;
let dx2 = x3 - x2; let dx2 = x3 - x2;
@@ -152,7 +152,7 @@ impl PerspectiveTransform {
let denominator = dx1 * dy2 - dx2 * dy1; let denominator = dx1 * dy2 - dx2 * dy1;
let a13 = (dx3 * dy2 - dx2 * dy3) / denominator; let a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
let a23 = (dx1 * dy3 - dx3 * dy1) / denominator; let a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
return PerspectiveTransform::new( PerspectiveTransform::new(
x1 - x0 + a13 * x1, x1 - x0 + a13 * x1,
x3 - x0 + a23 * x3, x3 - x0 + a23 * x3,
x0, x0,
@@ -162,7 +162,7 @@ impl PerspectiveTransform {
a13, a13,
a23, a23,
1.0f32, 1.0f32,
); )
} }
} }
@@ -177,13 +177,12 @@ impl PerspectiveTransform {
y3: f32, y3: f32,
) -> Self { ) -> Self {
// Here, the adjoint serves as the inverse // Here, the adjoint serves as the inverse
return PerspectiveTransform::squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3) PerspectiveTransform::squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint()
.buildAdjoint();
} }
fn buildAdjoint(&self) -> Self { fn buildAdjoint(&self) -> Self {
// Adjoint is the transpose of the cofactor matrix: // Adjoint is the transpose of the cofactor matrix:
return PerspectiveTransform::new( PerspectiveTransform::new(
self.a22 * self.a33 - self.a23 * self.a32, self.a22 * self.a33 - self.a23 * self.a32,
self.a23 * self.a31 - self.a21 * self.a33, self.a23 * self.a31 - self.a21 * self.a33,
self.a21 * self.a32 - self.a22 * self.a31, self.a21 * self.a32 - self.a22 * self.a31,
@@ -193,11 +192,11 @@ impl PerspectiveTransform {
self.a12 * self.a23 - self.a13 * self.a22, self.a12 * self.a23 - self.a13 * self.a22,
self.a13 * self.a21 - self.a11 * self.a23, self.a13 * self.a21 - self.a11 * self.a23,
self.a11 * self.a22 - self.a12 * self.a21, self.a11 * self.a22 - self.a12 * self.a21,
); )
} }
fn times(&self, other: &Self) -> Self { fn times(&self, other: &Self) -> Self {
return PerspectiveTransform::new( PerspectiveTransform::new(
self.a11 * other.a11 + self.a21 * other.a12 + self.a31 * other.a13, self.a11 * other.a11 + self.a21 * other.a12 + self.a31 * other.a13,
self.a11 * other.a21 + self.a21 * other.a22 + self.a31 * other.a23, self.a11 * other.a21 + self.a21 * other.a22 + self.a31 * other.a23,
self.a11 * other.a31 + self.a21 * other.a32 + self.a31 * other.a33, self.a11 * other.a31 + self.a21 * other.a32 + self.a31 * other.a33,
@@ -207,6 +206,6 @@ impl PerspectiveTransform {
self.a13 * other.a11 + self.a23 * other.a12 + self.a33 * other.a13, self.a13 * other.a11 + self.a23 * other.a12 + self.a33 * other.a13,
self.a13 * other.a21 + self.a23 * other.a22 + self.a33 * other.a23, self.a13 * other.a21 + self.a23 * other.a22 + self.a33 * other.a23,
self.a13 * other.a31 + self.a23 * other.a32 + self.a33 * other.a33, self.a13 * other.a31 + self.a23 * other.a32 + self.a33 * other.a33,
); )
} }
} }

View File

@@ -38,9 +38,9 @@ const DECODER_TEST_ITERATIONS: i32 = 10;
fn test_data_matrix() { fn test_data_matrix() {
let dm256 = super::get_predefined_genericgf(super::PredefinedGenericGF::DataMatrixField256); let dm256 = super::get_predefined_genericgf(super::PredefinedGenericGF::DataMatrixField256);
// real life test cases // real life test cases
test_encode_decode(&dm256, &vec![142, 164, 186], &vec![114, 25, 5, 88, 102]); test_encode_decode(dm256, &vec![142, 164, 186], &vec![114, 25, 5, 88, 102]);
test_encode_decode( test_encode_decode(
&dm256, dm256,
&vec![ &vec![
0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64, 0x70, 0x65, 0x66, 0x2F, 0x68, 0x70, 0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64, 0x70, 0x65, 0x66, 0x2F, 0x68, 0x70,
0x70, 0x68, 0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71, 0x30, 0x7B, 0x79, 0x6A, 0x70, 0x68, 0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71, 0x30, 0x7B, 0x79, 0x6A,
@@ -62,7 +62,7 @@ fn test_qr_code() {
let qrcf256 = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256); let qrcf256 = super::get_predefined_genericgf(super::PredefinedGenericGF::QrCodeField256);
// Test case from example given in ISO 18004, Annex I // Test case from example given in ISO 18004, Annex I
test_encode_decode( test_encode_decode(
&qrcf256, qrcf256,
&vec![ &vec![
0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11,
@@ -70,7 +70,7 @@ fn test_qr_code() {
&vec![0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87, 0x2C, 0x55], &vec![0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87, 0x2C, 0x55],
); );
test_encode_decode( test_encode_decode(
&qrcf256, qrcf256,
&vec![ &vec![
0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F, 0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50, 0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F, 0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50,
0x61, 0x67, 0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0x61, 0x67, 0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11,
@@ -92,28 +92,28 @@ fn test_qr_code() {
fn test_aztec() { fn test_aztec() {
// real life test cases // real life test cases
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam),
&vec![0x5, 0x6], &vec![0x5, 0x6],
&vec![0x3, 0x2, 0xB, 0xB, 0x7], &vec![0x3, 0x2, 0xB, 0xB, 0x7],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam),
&vec![0x0, 0x0, 0x0, 0x9], &vec![0x0, 0x0, 0x0, 0x9],
&vec![0xA, 0xD, 0x8, 0x6, 0x5, 0x6], &vec![0xA, 0xD, 0x8, 0x6, 0x5, 0x6],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecParam),
&vec![0x2, 0x8, 0x8, 0x7], &vec![0x2, 0x8, 0x8, 0x7],
&vec![0xE, 0xC, 0xA, 0x9, 0x6, 0x8], &vec![0xE, 0xC, 0xA, 0x9, 0x6, 0x8],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData6), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData6),
&vec![0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B], &vec![0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B],
&vec![0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14], &vec![0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData8), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData8),
&vec![ &vec![
0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6, 0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA, 0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6, 0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA,
0xF8, 0xCE, 0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9, 0x6C, 0x6B, 0x9F, 0x08, 0xF8, 0xCE, 0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9, 0x6C, 0x6B, 0x9F, 0x08,
@@ -129,7 +129,7 @@ fn test_aztec() {
], ],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData10), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData10),
&vec![ &vec![
0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD, 0x02E, 0x056, 0x26A, 0x281, 0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD, 0x02E, 0x056, 0x26A, 0x281,
0x1C2, 0x1A6, 0x296, 0x045, 0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2, 0x1C2, 0x1A6, 0x296, 0x045, 0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2,
@@ -176,7 +176,7 @@ fn test_aztec() {
], ],
); );
test_encode_decode( test_encode_decode(
&super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData12), super::get_predefined_genericgf(super::PredefinedGenericGF::AztecData12),
&vec![ &vec![
0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85, 0x69A, 0xA81, 0x709, 0xA6A, 0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85, 0x69A, 0xA81, 0x709, 0xA6A,
0x584, 0x510, 0x4AA, 0x256, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C, 0x584, 0x510, 0x4AA, 0x256, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C,
@@ -432,7 +432,7 @@ fn test_encode_decode_random(field: GenericGFRef, dataSize: usize, ecSize: usize
ecWords[0..ecSize].clone_from_slice(&message[dataSize..dataSize + ecSize]); ecWords[0..ecSize].clone_from_slice(&message[dataSize..dataSize + ecSize]);
//System.arraycopy(message, dataSize, ecWords, 0, ecSize); //System.arraycopy(message, dataSize, ecWords, 0, ecSize);
// check to see if Decoder can fix up to ecWords/2 random errors // check to see if Decoder can fix up to ecWords/2 random errors
test_decoder(&field, &dataWords, &ecWords); test_decoder(field, &dataWords, &ecWords);
} }
} }
@@ -536,7 +536,7 @@ fn test_decoder(field: GenericGFRef, dataWords: &Vec<i32>, ecWords: &Vec<i32>) {
ecWords.len(), ecWords.len(),
i i
), ),
&dataWords, dataWords,
&message, &message,
); );
} }
@@ -545,7 +545,7 @@ fn test_decoder(field: GenericGFRef, dataWords: &Vec<i32>, ecWords: &Vec<i32>) {
} }
} }
fn assert_data_equals(message: String, expected: &Vec<i32>, received: &Vec<i32>) { fn assert_data_equals(message: String, expected: &Vec<i32>, received: &[i32]) {
for i in 0..expected.len() { for i in 0..expected.len() {
//for (int i = 0; i < expected.length; i++) { //for (int i = 0; i < expected.length; i++) {
if expected[i] != received[i] { if expected[i] != received[i] {
@@ -553,7 +553,7 @@ fn assert_data_equals(message: String, expected: &Vec<i32>, received: &Vec<i32>)
"{}. Mismatch at {}. Expected {}, got {}", "{}. Mismatch at {}. Expected {}, got {}",
message, message,
i, i,
array_to_string(&expected), array_to_string(expected),
array_to_string(&received[0..expected.len()]) array_to_string(&received[0..expected.len()])
); );
//fail(); //fail();
@@ -563,12 +563,12 @@ fn assert_data_equals(message: String, expected: &Vec<i32>, received: &Vec<i32>)
fn array_to_string(data: &[i32]) -> String { fn array_to_string(data: &[i32]) -> String {
let mut sb = String::from("{"); let mut sb = String::from("{");
for i in 0..data.len() { for dtm in data.iter() {
//for (int i = 0; i < data.length; i++) { //for (int i = 0; i < data.length; i++) {
//sb.append(String.format(i > 0 ? ",%X" : "%X", data[i])); //sb.append(String.format(i > 0 ? ",%X" : "%X", data[i]));
sb.push_str(&format!("{}", data[i])); sb.push_str(&format!("{}", *dtm));
} }
sb.push_str("}"); sb.push('}');
sb sb
} }

View File

@@ -42,10 +42,11 @@ impl GenericGF {
let mut expTable = vec![0; size]; let mut expTable = vec![0; size];
let mut logTable = vec![0; size]; let mut logTable = vec![0; size];
let mut x = 1; let mut x = 1;
for i in 0..size { for expTableEntry in expTable.iter_mut().take(size) {
// for i in 0..size {
//for (int i = 0; i < size; i++) { //for (int i = 0; i < size; i++) {
//expTable.push(x); //expTable.push(x);
expTable[i] = x; *expTableEntry = x;
x *= 2; // we're assuming the generator alpha is 2 x *= 2; // we're assuming the generator alpha is 2
if x >= size as i32 { if x >= size as i32 {
x ^= primitive; x ^= primitive;
@@ -53,10 +54,11 @@ impl GenericGF {
x &= sz_m_1; x &= sz_m_1;
} }
} }
for i in 0..size - 1 { for (i, loc) in expTable.iter().enumerate().take(size - 1) {
// for i in 0..size - 1 {
//for (int i = 0; i < size - 1; i++) { //for (int i = 0; i < size - 1; i++) {
let loc: usize = expTable[i] as usize; // let loc: usize = expTable[i] as usize;
logTable[loc] = i as i32; logTable[*loc as usize] = i as i32;
} }
logTable[0] = 0; logTable[0] = 0;
@@ -106,7 +108,7 @@ impl GenericGF {
} }
let mut coefficients = vec![0; degree + 1]; let mut coefficients = vec![0; degree + 1];
coefficients[0] = coefficient; coefficients[0] = coefficient;
return GenericGFPoly::new(source, &coefficients).unwrap(); GenericGFPoly::new(source, &coefficients).unwrap()
} }
/** /**
@@ -115,7 +117,7 @@ impl GenericGF {
* @return sum/difference of a and b * @return sum/difference of a and b
*/ */
pub fn addOrSubtract(a: i32, b: i32) -> i32 { pub fn addOrSubtract(a: i32, b: i32) -> i32 {
return a ^ b; a ^ b
} }
/** /**
@@ -123,7 +125,7 @@ impl GenericGF {
*/ */
pub fn exp(&self, a: i32) -> i32 { pub fn exp(&self, a: i32) -> i32 {
// let pos: usize = a.try_into().unwrap(); // let pos: usize = a.try_into().unwrap();
return self.expTable[a as usize]; self.expTable[a as usize]
} }
/** /**
@@ -131,10 +133,10 @@ impl GenericGF {
*/ */
pub fn log(&self, a: i32) -> Result<i32, Exceptions> { pub fn log(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 { if a == 0 {
return Err(Exceptions::IllegalArgumentException("".to_owned())); return Err(Exceptions::IllegalArgumentException(None));
} }
// let pos: usize = a.try_into().unwrap(); // let pos: usize = a.try_into().unwrap();
return Ok(self.logTable[a as usize]); Ok(self.logTable[a as usize])
} }
/** /**
@@ -142,11 +144,11 @@ impl GenericGF {
*/ */
pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> { pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 { if a == 0 {
return Err(Exceptions::ArithmeticException("".to_owned())); return Err(Exceptions::ArithmeticException(None));
} }
let log_t_loc: usize = a as usize; let log_t_loc: usize = a as usize;
let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize; let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize;
return Ok(self.expTable[loc]); Ok(self.expTable[loc])
} }
/** /**
@@ -159,15 +161,15 @@ impl GenericGF {
let a_loc: usize = a as usize; //.try_into().unwrap(); let a_loc: usize = a as usize; //.try_into().unwrap();
let b_loc: usize = b as usize; //.try_into().unwrap(); let b_loc: usize = b as usize; //.try_into().unwrap();
let comb_loc: usize = (self.logTable[a_loc] + self.logTable[b_loc]) as usize; let comb_loc: usize = (self.logTable[a_loc] + self.logTable[b_loc]) as usize;
return self.expTable[comb_loc % (self.size - 1)]; self.expTable[comb_loc % (self.size - 1)]
} }
pub fn getSize(&self) -> usize { pub fn getSize(&self) -> usize {
return self.size; self.size
} }
pub fn getGeneratorBase(&self) -> i32 { pub fn getGeneratorBase(&self) -> i32 {
return self.generatorBase; self.generatorBase
} }
} }

View File

@@ -48,13 +48,13 @@ impl GenericGFPoly {
* constant polynomial (that is, it is not the monomial "0") * constant polynomial (that is, it is not the monomial "0")
*/ */
pub fn new(field: GenericGFRef, coefficients: &Vec<i32>) -> Result<Self, Exceptions> { pub fn new(field: GenericGFRef, coefficients: &Vec<i32>) -> Result<Self, Exceptions> {
if coefficients.len() == 0 { if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"coefficients.len()".to_owned(), "coefficients.len()".to_owned(),
)); )));
} }
Ok(Self { Ok(Self {
field: field, field,
coefficients: { coefficients: {
let coefficients_length = coefficients.len(); let coefficients_length = coefficients.len();
if coefficients_length > 1 && coefficients[0] == 0 { if coefficients_length > 1 && coefficients[0] == 0 {
@@ -85,28 +85,28 @@ impl GenericGFPoly {
} }
pub fn getCoefficients(&self) -> &Vec<i32> { pub fn getCoefficients(&self) -> &Vec<i32> {
return &self.coefficients; &self.coefficients
} }
/** /**
* @return degree of this polynomial * @return degree of this polynomial
*/ */
pub fn getDegree(&self) -> usize { pub fn getDegree(&self) -> usize {
return self.coefficients.len() - 1; self.coefficients.len() - 1
} }
/** /**
* @return true iff this polynomial is the monomial "0" * @return true iff this polynomial is the monomial "0"
*/ */
pub fn isZero(&self) -> bool { pub fn isZero(&self) -> bool {
return self.coefficients[0] == 0; self.coefficients[0] == 0
} }
/** /**
* @return coefficient of x^degree term in this polynomial * @return coefficient of x^degree term in this polynomial
*/ */
pub fn getCoefficient(&self, degree: usize) -> i32 { pub fn getCoefficient(&self, degree: usize) -> i32 {
return self.coefficients[self.coefficients.len() - 1 - degree]; self.coefficients[self.coefficients.len() - 1 - degree]
} }
/** /**
@@ -131,18 +131,18 @@ impl GenericGFPoly {
for i in 1..size { for i in 1..size {
//for (int i = 1; i < size; i++) { //for (int i = 1; i < size; i++) {
result = GenericGF::addOrSubtract( result = GenericGF::addOrSubtract(
self.field.multiply(a as i32, result as i32), self.field.multiply(a as i32, result),
self.coefficients[i], self.coefficients[i],
); );
} }
return result; result
} }
pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> { pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field { if self.field != other.field {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"GenericGFPolys do not have same GenericGF field".to_owned(), "GenericGFPolys do not have same GenericGF field".to_owned(),
)); )));
} }
if self.isZero() { if self.isZero() {
return Ok(other.clone()); return Ok(other.clone());
@@ -171,15 +171,15 @@ impl GenericGFPoly {
); );
} }
return Ok(GenericGFPoly::new(self.field, &sumDiff)?); GenericGFPoly::new(self.field, &sumDiff)
} }
pub fn multiply(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> { pub fn multiply(&self, other: &GenericGFPoly) -> 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(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"GenericGFPolys do not have same GenericGF field".to_owned(), "GenericGFPolys do not have same GenericGF field".to_owned(),
)); )));
} }
if self.isZero() || other.isZero() { if self.isZero() || other.isZero() {
return Ok(self.getZero()); return Ok(self.getZero());
@@ -200,7 +200,7 @@ impl GenericGFPoly {
); );
} }
} }
return Ok(GenericGFPoly::new(self.field, &product)?); GenericGFPoly::new(self.field, &product)
} }
pub fn multiply_with_scalar(&self, scalar: i32) -> GenericGFPoly { pub fn multiply_with_scalar(&self, scalar: i32) -> GenericGFPoly {
@@ -213,11 +213,12 @@ impl GenericGFPoly {
let size = self.coefficients.len(); let size = self.coefficients.len();
let mut product = vec![0; size]; let mut product = vec![0; size];
for i in 0..size { for (i, prod) in product.iter_mut().enumerate().take(size) {
// for i in 0..size {
//for (int i = 0; i < size; i++) { //for (int i = 0; i < size; i++) {
product[i] = self.field.multiply(self.coefficients[i], scalar); *prod = self.field.multiply(self.coefficients[i], scalar);
} }
return GenericGFPoly::new(self.field, &product).unwrap(); GenericGFPoly::new(self.field, &product).unwrap()
} }
pub fn getZero(&self) -> Self { pub fn getZero(&self) -> Self {
@@ -238,11 +239,12 @@ impl GenericGFPoly {
} }
let size = self.coefficients.len(); let size = self.coefficients.len();
let mut product = vec![0; size + degree]; let mut product = vec![0; size + degree];
for i in 0..size { for (i, prod) in product.iter_mut().enumerate().take(size) {
// for i in 0..size {
//for (int i = 0; i < size; i++) { //for (int i = 0; i < size; i++) {
product[i] = self.field.multiply(self.coefficients[i], coefficient); *prod = self.field.multiply(self.coefficients[i], coefficient);
} }
return Ok(GenericGFPoly::new(self.field, &product)?); GenericGFPoly::new(self.field, &product)
} }
pub fn divide( pub fn divide(
@@ -250,14 +252,14 @@ impl GenericGFPoly {
other: &GenericGFPoly, other: &GenericGFPoly,
) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> { ) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> {
if self.field != other.field { if self.field != other.field {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"GenericGFPolys do not have same GenericGF field".to_owned(), "GenericGFPolys do not have same GenericGF field".to_owned(),
)); )));
} }
if other.isZero() { if other.isZero() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Divide by 0".to_owned(), "Divide by 0".to_owned(),
)); )));
} }
let mut quotient = self.getZero(); let mut quotient = self.getZero();
@@ -267,9 +269,9 @@ impl GenericGFPoly {
let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) { let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) {
Ok(val) => val, Ok(val) => val,
Err(_issue) => { Err(_issue) => {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"arithmetic issue".to_owned(), "arithmetic issue".to_owned(),
)) )))
} }
}; };
@@ -285,7 +287,7 @@ impl GenericGFPoly {
remainder = remainder.addOrSubtract(&term)?; remainder = remainder.addOrSubtract(&term)?;
} }
return Ok((quotient, remainder)); Ok((quotient, remainder))
} }
} }
@@ -301,22 +303,20 @@ impl fmt::Display for GenericGFPoly {
if coefficient != 0 { if coefficient != 0 {
if coefficient < 0 { if coefficient < 0 {
if degree == self.getDegree() { if degree == self.getDegree() {
result.push_str("-"); result.push('-');
} else { } else {
result.push_str(" - "); result.push_str(" - ");
} }
coefficient = -coefficient; coefficient = -coefficient;
} else { } else if !result.is_empty() {
if result.len() > 0 {
result.push_str(" + "); result.push_str(" + ");
} }
}
if degree == 0 || coefficient != 1 { if degree == 0 || coefficient != 1 {
if let Ok(alpha_power) = self.field.log(coefficient) { if let Ok(alpha_power) = self.field.log(coefficient) {
if alpha_power == 0 { if alpha_power == 0 {
result.push_str("1"); result.push('1');
} else if alpha_power == 1 { } else if alpha_power == 1 {
result.push_str("a"); result.push('a');
} else { } else {
result.push_str("a^"); result.push_str("a^");
result.push_str(&format!("{}", alpha_power)); result.push_str(&format!("{}", alpha_power));
@@ -325,7 +325,7 @@ impl fmt::Display for GenericGFPoly {
} }
if degree != 0 { if degree != 0 {
if degree == 1 { if degree == 1 {
result.push_str("x"); result.push('x');
} else { } else {
result.push_str("x^"); result.push_str("x^");
result.push_str(&format!("{}", degree)); result.push_str(&format!("{}", degree));

View File

@@ -48,7 +48,7 @@ pub struct ReedSolomonDecoder {
impl ReedSolomonDecoder { impl ReedSolomonDecoder {
pub fn new(field: GenericGFRef) -> Self { pub fn new(field: GenericGFRef) -> Self {
Self { field: field } Self { field }
} }
/** /**
@@ -78,11 +78,7 @@ impl ReedSolomonDecoder {
} }
let syndrome = match GenericGFPoly::new(self.field, &syndromeCoefficients) { let syndrome = match GenericGFPoly::new(self.field, &syndromeCoefficients) {
Ok(res) => res, Ok(res) => res,
Err(_fail) => { Err(_fail) => return Err(Exceptions::ReedSolomonException(None)),
return Err(Exceptions::ReedSolomonException(
"IllegalArgumentException".to_owned(),
))
}
}; };
let sigmaOmega = self.runEuclideanAlgorithm( let sigmaOmega = self.runEuclideanAlgorithm(
&GenericGF::buildMonomial(self.field, twoS as usize, 1), &GenericGF::buildMonomial(self.field, twoS as usize, 1),
@@ -91,21 +87,21 @@ impl ReedSolomonDecoder {
)?; )?;
let sigma = &sigmaOmega[0]; let sigma = &sigmaOmega[0];
let omega = &sigmaOmega[1]; let omega = &sigmaOmega[1];
let errorLocations = self.findErrorLocations(&sigma)?; let errorLocations = self.findErrorLocations(sigma)?;
let errorMagnitudes = self.findErrorMagnitudes(&omega, &errorLocations); let errorMagnitudes = self.findErrorMagnitudes(omega, &errorLocations);
for i in 0..errorLocations.len() { for i in 0..errorLocations.len() {
//for (int i = 0; i < errorLocations.length; i++) { //for (int i = 0; i < errorLocations.length; i++) {
let log_value = self.field.log(errorLocations[i] as i32)?; let log_value = self.field.log(errorLocations[i] as i32)?;
if log_value > received.len() as i32 - 1 { if log_value > received.len() as i32 - 1 {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"Bad error location".to_owned(), "Bad error location".to_owned(),
)); )));
} }
let position: isize = received.len() as isize - 1 - log_value as isize; let position: isize = received.len() as isize - 1 - log_value as isize;
if position < 0 { if position < 0 {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"Bad error location".to_owned(), "Bad error location".to_owned(),
)); )));
} }
received[position as usize] = received[position as usize] =
GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]); GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]);
@@ -143,9 +139,9 @@ 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(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"r_{i-1} was zero".to_owned(), "r_{i-1} was zero".to_owned(),
)); )));
} }
r = rLastLast; r = rLastLast;
let mut q = r.getZero(); let mut q = r.getZero();
@@ -153,9 +149,9 @@ impl ReedSolomonDecoder {
let dltInverse = match self.field.inverse(denominatorLeadingTerm) { let dltInverse = match self.field.inverse(denominatorLeadingTerm) {
Ok(inv) => inv, Ok(inv) => inv,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(), "ArithmetricException".to_owned(),
)) )))
} }
}; };
while r.getDegree() >= rLast.getDegree() && !r.isZero() { while r.getDegree() >= rLast.getDegree() && !r.isZero() {
@@ -167,24 +163,24 @@ impl ReedSolomonDecoder {
{ {
Ok(res) => res, Ok(res) => res,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(), "IllegalArgumentException".to_owned(),
)) )))
} }
}; };
r = match r.addOrSubtract(&match rLast.multiply_by_monomial(degreeDiff, scale) { r = match r.addOrSubtract(&match rLast.multiply_by_monomial(degreeDiff, scale) {
Ok(res) => res, Ok(res) => res,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(), "IllegalArgumentException".to_owned(),
)) )))
} }
}) { }) {
Ok(res) => res, Ok(res) => res,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(), "IllegalArgumentException".to_owned(),
)) )))
} }
}; };
} }
@@ -192,47 +188,47 @@ impl ReedSolomonDecoder {
t = match (match q.multiply(&tLast) { t = match (match q.multiply(&tLast) {
Ok(res) => res, Ok(res) => res,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(), "IllegalArgumentException".to_owned(),
)) )))
} }
}) })
.addOrSubtract(&tLastLast) .addOrSubtract(&tLastLast)
{ {
Ok(res) => res, Ok(res) => res,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"IllegalArgumentException".to_owned(), "IllegalArgumentException".to_owned(),
)) )))
} }
}; };
if r.getDegree() >= rLast.getDegree() { if r.getDegree() >= rLast.getDegree() {
return Err(Exceptions::ReedSolomonException(format!( return Err(Exceptions::ReedSolomonException(Some(format!(
"Division algorithm failed to reduce polynomial? r: {}, rLast: {}", "Division algorithm failed to reduce polynomial? r: {}, rLast: {}",
r, rLast r, rLast
))); ))));
} }
} }
let sigmaTildeAtZero = t.getCoefficient(0); let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 { if sigmaTildeAtZero == 0 {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"sigmaTilde(0) was zero".to_owned(), "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) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(), "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);
return Ok(vec![sigma, omega]); Ok(vec![sigma, omega])
} }
fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result<Vec<usize>, Exceptions> { fn findErrorLocations(&self, errorLocator: &GenericGFPoly) -> Result<Vec<usize>, Exceptions> {
@@ -254,20 +250,20 @@ impl ReedSolomonDecoder {
result[e] = match self.field.inverse(i as i32) { result[e] = match self.field.inverse(i as i32) {
Ok(res) => res as usize, Ok(res) => res as usize,
Err(_err) => { Err(_err) => {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"ArithmetricException".to_owned(), "ArithmetricException".to_owned(),
)) )))
} }
}; };
e += 1; e += 1;
} }
} }
if e != numErrors { if e != numErrors {
return Err(Exceptions::ReedSolomonException( return Err(Exceptions::ReedSolomonException(Some(
"Error locator degree does not match number of roots".to_owned(), "Error locator degree does not match number of roots".to_owned(),
)); )));
} }
return Ok(result); Ok(result)
} }
fn findErrorMagnitudes( fn findErrorMagnitudes(
@@ -282,14 +278,15 @@ impl ReedSolomonDecoder {
//for (int i = 0; i < s; i++) { //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).unwrap();
let mut denominator = 1; let mut denominator = 1;
for j in 0..s { for (j, loc) in errorLocations.iter().enumerate().take(s) {
// for j in 0..s {
//for (int j = 0; j < s; j++) { //for (int j = 0; j < s; j++) {
if i != j { if i != j {
//denominator = field.multiply(denominator, //denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes // Below is a funny-looking workaround from Steven Parkes
let term = self.field.multiply(errorLocations[j] as i32, xiInverse); let term = self.field.multiply(*loc as i32, xiInverse);
let termPlus1 = if (term & 0x1) == 0 { let termPlus1 = if (term & 0x1) == 0 {
term | 1 term | 1
} else { } else {
@@ -306,6 +303,6 @@ impl ReedSolomonDecoder {
result[i] = self.field.multiply(result[i], xiInverse); result[i] = self.field.multiply(result[i], xiInverse);
} }
} }
return result; result
} }
} }

View File

@@ -45,10 +45,7 @@ impl ReedSolomonEncoder {
fn buildGenerator(&mut self, degree: usize) -> &GenericGFPoly { fn buildGenerator(&mut self, degree: usize) -> &GenericGFPoly {
if degree >= self.cachedGenerators.len() { if degree >= self.cachedGenerators.len() {
let mut lastGenerator = self let mut lastGenerator = self.cachedGenerators.last().unwrap();
.cachedGenerators
.get(self.cachedGenerators.len() - 1)
.unwrap();
let cg_len = self.cachedGenerators.len(); let cg_len = self.cachedGenerators.len();
let mut nextGenerator; let mut nextGenerator;
for d in cg_len..=degree { for d in cg_len..=degree {
@@ -71,20 +68,20 @@ impl ReedSolomonEncoder {
} }
} }
let rv = self.cachedGenerators.get(degree).unwrap(); let rv = self.cachedGenerators.get(degree).unwrap();
return rv; rv
} }
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> { pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> {
if ec_bytes == 0 { if ec_bytes == 0 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"No error correction bytes".to_owned(), "No error correction bytes".to_owned(),
)); )));
} }
let data_bytes = to_encode.len() - ec_bytes; let data_bytes = to_encode.len() - ec_bytes;
if data_bytes == 0 { if data_bytes == 0 {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"No data bytes provided".to_owned(), "No data bytes provided".to_owned(),
)); )));
} }
let fld = self.field; let fld = self.field;
let generator = self.buildGenerator(ec_bytes); let generator = self.buildGenerator(ec_bytes);
@@ -93,7 +90,7 @@ impl ReedSolomonEncoder {
//System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); //System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);
let mut info = GenericGFPoly::new(fld, &info_coefficients)?; let mut info = GenericGFPoly::new(fld, &info_coefficients)?;
info = info.multiply_by_monomial(ec_bytes, 1)?; info = info.multiply_by_monomial(ec_bytes, 1)?;
let remainder = &info.divide(&generator)?.1; let remainder = &info.divide(generator)?.1;
let coefficients = remainder.getCoefficients(); let coefficients = remainder.getCoefficients();
let num_zero_coefficients = ec_bytes - coefficients.len(); let num_zero_coefficients = ec_bytes - coefficients.len();
for i in 0..num_zero_coefficients { for i in 0..num_zero_coefficients {

View File

@@ -98,14 +98,13 @@ impl StringUtils {
* none of these can possibly be correct * none of these can possibly be correct
*/ */
pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> EncodingRef { pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> EncodingRef {
match hints.get(&DecodeHintType::CHARACTER_SET) { if let Some(DecodeHintValue::CharacterSet(cs_name)) =
Some(hint) => { hints.get(&DecodeHintType::CHARACTER_SET)
if let DecodeHintValue::CharacterSet(cs_name) = hint { {
// 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).unwrap();
// }
} }
}
_ => {}
};
// if hints.contains_key(&DecodeHintType::CHARACTER_SET) { // if hints.contains_key(&DecodeHintType::CHARACTER_SET) {
// return Charset.forName(hints.get(DecodeHintType.CHARACTER_SET).toString()); // return Charset.forName(hints.get(DecodeHintType.CHARACTER_SET).toString());
// } // }
@@ -141,7 +140,8 @@ impl StringUtils {
let utf8bom = bytes.len() > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; let utf8bom = bytes.len() > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF;
for i in 0..length { // for i in 0..length {
for value in bytes.iter().take(length).copied() {
// for (int i = 0; // for (int i = 0;
// i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); // i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8);
// i++) { // i++) {
@@ -149,7 +149,7 @@ impl StringUtils {
break; break;
} }
let value = bytes[i]; // let value = bytes[i];
// UTF-8 stuff // UTF-8 stuff
if can_be_utf8 { if can_be_utf8 {
@@ -270,6 +270,6 @@ impl StringUtils {
return encoding::all::UTF_8; return encoding::all::UTF_8;
} }
// Otherwise, we take a wild guess with platform encoding // Otherwise, we take a wild guess with platform encoding
return encoding::all::UTF_8; encoding::all::UTF_8
} }
} }

View File

@@ -83,7 +83,7 @@ impl Reader for DataMatrixReader {
points = detectorRXingResult.getPoints().clone(); points = detectorRXingResult.getPoints().clone();
} }
let mut result = RXingResult::new( let mut result = RXingResult::new(
decoderRXingResult.getText().clone(), decoderRXingResult.getText(),
decoderRXingResult.getRawBytes().clone(), decoderRXingResult.getRawBytes().clone(),
points.clone(), points.clone(),
BarcodeFormat::DATA_MATRIX, BarcodeFormat::DATA_MATRIX,
@@ -127,10 +127,10 @@ impl DataMatrixReader {
*/ */
fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix, Exceptions> { fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let Some(leftTopBlack) = image.getTopLeftOnBit() else { let Some(leftTopBlack) = image.getTopLeftOnBit() else {
return Err(Exceptions::NotFoundException("".to_owned())) return Err(Exceptions::NotFoundException(None))
}; };
let Some(rightBottomBlack) = image.getBottomRightOnBit()else { let Some(rightBottomBlack) = image.getBottomRightOnBit()else {
return Err(Exceptions::NotFoundException("".to_owned())) return Err(Exceptions::NotFoundException(None))
}; };
let moduleSize = Self::moduleSize(&leftTopBlack, image)?; let moduleSize = Self::moduleSize(&leftTopBlack, image)?;
@@ -143,7 +143,7 @@ impl DataMatrixReader {
let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32; let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32;
let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32; let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32;
if matrixWidth <= 0 || matrixHeight <= 0 { if matrixWidth <= 0 || matrixHeight <= 0 {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
// throw NotFoundException.getNotFoundInstance(); // throw NotFoundException.getNotFoundInstance();
} }
@@ -180,12 +180,12 @@ impl DataMatrixReader {
x += 1; x += 1;
} }
if x == width { if x == width {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let moduleSize = x - leftTopBlack[0]; let moduleSize = x - leftTopBlack[0];
if moduleSize == 0 { if moduleSize == 0 {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
Ok(moduleSize) Ok(moduleSize)

View File

@@ -60,23 +60,23 @@ impl Writer for DataMatrixWriter {
hints: &crate::EncodingHintDictionary, hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> { ) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if contents.is_empty() { if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Found empty contents".to_owned(), "Found empty contents".to_owned(),
)); )));
} }
if format != &BarcodeFormat::DATA_MATRIX { if format != &BarcodeFormat::DATA_MATRIX {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can only encode DATA_MATRIX, but got {:?}", "Can only encode DATA_MATRIX, but got {:?}",
format format
))); ))));
} }
if width < 0 || height < 0 { if width < 0 || height < 0 {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Requested dimensions can't be negative: {}x{}", "Requested dimensions can't be negative: {}x{}",
width, height width, height
))); ))));
} }
// Try to get force shape & min / max size // Try to get force shape & min / max size
@@ -125,7 +125,7 @@ impl Writer for DataMatrixWriter {
if hasEncodingHint { if hasEncodingHint {
let Some(EncodeHintValue::CharacterSet(char_set_name)) = let Some(EncodeHintValue::CharacterSet(char_set_name)) =
hints.get(&EncodeHintType::CHARACTER_SET) else { hints.get(&EncodeHintType::CHARACTER_SET) else {
return Err(Exceptions::IllegalArgumentException("charset does not exist".to_owned())) return Err(Exceptions::IllegalArgumentException(Some("charset does not exist".to_owned())))
}; };
charset = encoding::label::encoding_from_whatwg_label(char_set_name); charset = encoding::label::encoding_from_whatwg_label(char_set_name);
// charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
@@ -159,7 +159,7 @@ impl Writer for DataMatrixWriter {
let symbol_lookup = SymbolInfoLookup::new(); let symbol_lookup = SymbolInfoLookup::new();
let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else { let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else {
return Err(Exceptions::NotFoundException("symbol info is bad".to_owned())) return Err(Exceptions::NotFoundException(Some("symbol info is bad".to_owned())))
}; };
//2. step: ECC generation //2. step: ECC generation

View File

@@ -33,8 +33,8 @@ impl BitMatrixParser {
*/ */
pub fn new(bitMatrix: &BitMatrix) -> Result<Self, Exceptions> { pub fn new(bitMatrix: &BitMatrix) -> Result<Self, Exceptions> {
let dimension = bitMatrix.getHeight(); let dimension = bitMatrix.getHeight();
if dimension < 8 || dimension > 144 || (dimension & 0x01) != 0 { if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
let version = Self::readVersion(bitMatrix)?; let version = Self::readVersion(bitMatrix)?;
@@ -50,7 +50,7 @@ impl BitMatrixParser {
} }
pub fn getVersion(&self) -> &Version { pub fn getVersion(&self) -> &Version {
&self.version self.version
} }
/** /**
@@ -178,7 +178,7 @@ impl BitMatrixParser {
} }
if resultOffset != self.version.getTotalCodewords() as usize { if resultOffset != self.version.getTotalCodewords() as usize {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
Ok(result) Ok(result)
@@ -257,7 +257,7 @@ impl BitMatrixParser {
if self.readModule(row, column, numRows, numColumns) { if self.readModule(row, column, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
} }
return currentByte; currentByte
} }
/** /**
@@ -302,7 +302,7 @@ impl BitMatrixParser {
if self.readModule(3, numColumns - 1, numRows, numColumns) { if self.readModule(3, numColumns - 1, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
} }
return currentByte; currentByte
} }
/** /**
@@ -347,7 +347,7 @@ impl BitMatrixParser {
if self.readModule(1, numColumns - 1, numRows, numColumns) { if self.readModule(1, numColumns - 1, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
} }
return currentByte; currentByte
} }
/** /**
@@ -392,7 +392,7 @@ impl BitMatrixParser {
if self.readModule(1, numColumns - 1, numRows, numColumns) { if self.readModule(1, numColumns - 1, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
} }
return currentByte; currentByte
} }
/** /**
@@ -437,7 +437,7 @@ impl BitMatrixParser {
if self.readModule(3, numColumns - 1, numRows, numColumns) { if self.readModule(3, numColumns - 1, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
} }
return currentByte; currentByte
} }
/** /**
@@ -455,9 +455,9 @@ impl BitMatrixParser {
let symbolSizeColumns = version.getSymbolSizeColumns(); let symbolSizeColumns = version.getSymbolSizeColumns();
if bitMatrix.getHeight() != symbolSizeRows { if bitMatrix.getHeight() != symbolSizeRows {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Dimension of bitMatrix must match the version size".to_owned(), "Dimension of bitMatrix must match the version size".to_owned(),
)); )));
} }
let dataRegionSizeRows = version.getDataRegionSizeRows(); let dataRegionSizeRows = version.getDataRegionSizeRows();

View File

@@ -93,9 +93,11 @@ impl DataBlock {
let mut rawCodewordsOffset = 0; let mut rawCodewordsOffset = 0;
for i in 0..shorterBlocksNumDataCodewords { for i in 0..shorterBlocksNumDataCodewords {
// for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { // for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
for j in 0..numRXingResultBlocks {
for res in result.iter_mut().take(numRXingResultBlocks) {
// for j in 0..numRXingResultBlocks {
// for (int j = 0; j < numRXingResultBlocks; j++) { // for (int j = 0; j < numRXingResultBlocks; j++) {
result[j].codewords[i] = rawCodewords[rawCodewordsOffset]; res.codewords[i] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1; rawCodewordsOffset += 1;
} }
} }
@@ -107,10 +109,10 @@ impl DataBlock {
} else { } else {
numRXingResultBlocks numRXingResultBlocks
}; };
for j in 0..numLongerBlocks { for res in result.iter_mut().take(numLongerBlocks) {
// for j in 0..numLongerBlocks {
// for (int j = 0; j < numLongerBlocks; j++) { // for (int j = 0; j < numLongerBlocks; j++) {
result[j].codewords[longerBlocksNumDataCodewords - 1] = res.codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset];
rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1; rawCodewordsOffset += 1;
} }
@@ -136,7 +138,7 @@ impl DataBlock {
} }
if rawCodewordsOffset != rawCodewords.len() { if rawCodewordsOffset != rawCodewords.len() {
return Err(Exceptions::IllegalArgumentException("".to_owned())); return Err(Exceptions::IllegalArgumentException(None));
} }
Ok(result) Ok(result)

View File

@@ -137,7 +137,7 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
decodeECISegment(&mut bits, &mut result)?; decodeECISegment(&mut bits, &mut result)?;
isECIencoded = true; // ECI detection only, atm continue decoding as ASCII isECIencoded = true; // ECI detection only, atm continue decoding as ASCII
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
}; };
mode = Mode::ASCII_ENCODE; mode = Mode::ASCII_ENCODE;
} }
@@ -145,7 +145,7 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
break; break;
} }
} //while (mode != Mode.PAD_ENCODE && bits.available() > 0); } //while (mode != Mode.PAD_ENCODE && bits.available() > 0);
if resultTrailer.len() > 0 { if !resultTrailer.is_empty() {
result.appendCharacters(&resultTrailer); result.appendCharacters(&resultTrailer);
} }
if isECIencoded { if isECIencoded {
@@ -158,15 +158,13 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
} else { } else {
symbologyModifier = 4; symbologyModifier = 4;
} }
} else { } else if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
symbologyModifier = 2; symbologyModifier = 2;
} else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) { } else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) {
symbologyModifier = 3; symbologyModifier = 3;
} else { } else {
symbologyModifier = 1; symbologyModifier = 1;
} }
}
Ok(DecoderRXingResult::with_symbology( Ok(DecoderRXingResult::with_symbology(
bytes.to_vec(), bytes.to_vec(),
@@ -196,7 +194,7 @@ fn decodeAsciiSegment(
loop { loop {
let mut oneByte = bits.readBits(8)?; let mut oneByte = bits.readBits(8)?;
if oneByte == 0 { if oneByte == 0 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} else if oneByte <= 128 { } else if oneByte <= 128 {
// ASCII data (ASCII value + 1) // ASCII data (ASCII value + 1)
if upperShift { if upperShift {
@@ -256,11 +254,11 @@ fn decodeAsciiSegment(
// Not to be used in ASCII encodation // Not to be used in ASCII encodation
// but work around encoders that end with 254, latch back to ASCII // but work around encoders that end with 254, latch back to ASCII
if oneByte != 254 || bits.available() != 0 { if oneByte != 254 || bits.available() != 0 {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException(None))
}}, }},
} }
} }
if !(bits.available() > 0) { if bits.available() == 0 {
break; break;
} }
} //while (bits.available() > 0); } //while (bits.available() > 0);
@@ -296,9 +294,10 @@ fn decodeC40Segment(
parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues); parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues);
for i in 0..3 { for cValue in cValues {
// for i in 0..3 {
// for (int i = 0; i < 3; i++) { // for (int i = 0; i < 3; i++) {
let cValue = cValues[i]; // let cValue = cValues[i];
match shift { match shift {
0 => { 0 => {
if cValue < 3 { if cValue < 3 {
@@ -312,15 +311,15 @@ fn decodeC40Segment(
result.append_char(c40char); result.append_char(c40char);
} }
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
} }
1 => { 1 => {
if upperShift { if upperShift {
result.append_char(char::from_u32((cValue + 128) as u32).unwrap()); result.append_char(char::from_u32(cValue + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char(char::from_u32(cValue as u32).unwrap()); result.append_char(char::from_u32(cValue).unwrap());
} }
shift = 0; shift = 0;
} }
@@ -346,25 +345,25 @@ fn decodeC40Segment(
upperShift = true upperShift = true
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
} }
} }
shift = 0; shift = 0;
} }
3 => { 3 => {
if upperShift { if upperShift {
result.append_char(char::from_u32(cValue as u32 + 224).unwrap()); result.append_char(char::from_u32(cValue + 224).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char(char::from_u32(cValue as u32 + 96).unwrap()); result.append_char(char::from_u32(cValue + 96).unwrap());
} }
shift = 0; shift = 0;
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
} }
} }
if !(bits.available() > 0) { if bits.available() == 0 {
break; break;
} }
} //while (bits.available() > 0); } //while (bits.available() > 0);
@@ -409,14 +408,13 @@ fn decodeTextSegment(
} else if cValue < TEXT_BASIC_SET_CHARS.len() as u32 { } else if cValue < TEXT_BASIC_SET_CHARS.len() as u32 {
let textChar = TEXT_BASIC_SET_CHARS[cValue as usize]; let textChar = TEXT_BASIC_SET_CHARS[cValue as usize];
if upperShift { if upperShift {
result result.append_char(char::from_u32(textChar as u32 + 128_u32).unwrap());
.append_char(char::from_u32(textChar as u32 + 128 as u32).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char(textChar); result.append_char(textChar);
} }
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
} }
1 => { 1 => {
@@ -452,7 +450,7 @@ fn decodeTextSegment(
upperShift = true upperShift = true
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
} }
} }
shift = 0; shift = 0;
@@ -468,14 +466,14 @@ fn decodeTextSegment(
} }
shift = 0; shift = 0;
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
} }
} }
if !(bits.available() > 0) { if bits.available() == 0 {
break; break;
} }
} //while (bits.available() > 0); } //while (bits.available() > 0);
@@ -543,12 +541,12 @@ fn decodeAnsiX12Segment(
// A - Z // A - Z
result.append_char(char::from_u32(cValue + 51).unwrap()); result.append_char(char::from_u32(cValue + 51).unwrap());
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
} }
} }
} }
if !(bits.available() > 0) { if bits.available() == 0 {
break; break;
} }
} //while (bits.available() > 0); } //while (bits.available() > 0);
@@ -601,7 +599,7 @@ fn decodeEdifactSegment(
result.append_char(char::from_u32(edifactValue).unwrap()); result.append_char(char::from_u32(edifactValue).unwrap());
} }
if !(bits.available() > 0) { if bits.available() == 0 {
break; break;
} }
} }
@@ -635,18 +633,19 @@ fn decodeBase256Segment(
// We're seeing NegativeArraySizeException errors from users. // We're seeing NegativeArraySizeException errors from users.
// but we shouldn't in rust because it's unsigned // but we shouldn't in rust because it's unsigned
// if count < 0 { // if count < 0 {
// return Err(Exceptions::FormatException("".to_owned())); // return Err(Exceptions::FormatException(None));
// } // }
let mut bytes = vec![0u8; count as usize]; let mut bytes = vec![0u8; count as usize];
for i in 0..count as usize { for byte in bytes.iter_mut().take(count as usize) {
// for i in 0..count as usize {
// for (int i = 0; i < count; i++) { // for (int i = 0; i < count; i++) {
// Have seen this particular error in the wild, such as at // Have seen this particular error in the wild, such as at
// http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
if bits.available() < 8 { if bits.available() < 8 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
bytes[i] = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
codewordPosition += 1; codewordPosition += 1;
} }
result.append_string( result.append_string(
@@ -665,7 +664,7 @@ fn decodeBase256Segment(
*/ */
fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<(), Exceptions> { fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<(), Exceptions> {
if bits.available() < 8 { if bits.available() < 8 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
let c1 = bits.readBits(8)?; let c1 = bits.readBits(8)?;
if c1 <= 127 { if c1 <= 127 {

View File

@@ -50,7 +50,7 @@ impl Decoder {
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> { pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> {
self.decode(&BitMatrix::parse_bools(&image)) self.decode(&BitMatrix::parse_bools(image))
} }
/** /**
@@ -72,7 +72,7 @@ impl Decoder {
let version = parser.getVersion(); let version = parser.getVersion();
// Separate into data blocks // Separate into data blocks
let dataBlocks = DataBlock::getDataBlocks(&codewords, &version)?; let dataBlocks = DataBlock::getDataBlocks(&codewords, version)?;
// Count total number of data bytes // Count total number of data bytes
let mut totalBytes = 0; let mut totalBytes = 0;
@@ -140,3 +140,9 @@ impl Decoder {
Ok(()) Ok(())
} }
} }
impl Default for Decoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -111,7 +111,7 @@ impl Version {
numColumns: u32, numColumns: u32,
) -> Result<&'static Version, Exceptions> { ) -> Result<&'static Version, Exceptions> {
if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 { if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
for version in VERSIONS.iter() { for version in VERSIONS.iter() {
@@ -120,7 +120,7 @@ impl Version {
} }
} }
Err(Exceptions::FormatException("".to_owned())) Err(Exceptions::FormatException(None))
} }
/** /**

View File

@@ -53,7 +53,9 @@ impl<'a> Detector<'_> {
if let Some(point) = self.correctTopRight(&points) { if let Some(point) = self.correctTopRight(&points) {
points[3] = point; points[3] = point;
} else { } else {
return Err(Exceptions::NotFoundException("point 4 unfound".to_owned())); return Err(Exceptions::NotFoundException(Some(
"point 4 unfound".to_owned(),
)));
} }
// points[3] = self.correctTopRight(&points); // points[3] = self.correctTopRight(&points);
// if points[3] == null { // if points[3] == null {
@@ -82,7 +84,7 @@ impl<'a> Detector<'_> {
} }
let bits = Self::sampleGrid( let bits = Self::sampleGrid(
&self.image, self.image,
&topLeft, &topLeft,
&bottomLeft, &bottomLeft,
&bottomRight, &bottomRight,
@@ -253,9 +255,9 @@ impl<'a> Detector<'_> {
+ self.transitionsBetween(&pointCs, &candidate2); + self.transitionsBetween(&pointCs, &candidate2);
if sumc1 > sumc2 { if sumc1 > sumc2 {
return Some(candidate1); Some(candidate1)
} else { } else {
return Some(candidate2); Some(candidate2)
} }
} }
@@ -315,10 +317,10 @@ impl<'a> Detector<'_> {
} }
fn isValid(&self, p: &RXingResultPoint) -> bool { fn isValid(&self, p: &RXingResultPoint) -> bool {
return p.getX() >= 0.0 p.getX() >= 0.0
&& p.getX() <= self.image.getWidth() as f32 - 1.0 && p.getX() <= self.image.getWidth() as f32 - 1.0
&& p.getY() > 0.0 && p.getY() > 0.0
&& p.getY() <= self.image.getHeight() as f32 - 1.0; && p.getY() <= self.image.getHeight() as f32 - 1.0
} }
fn sampleGrid( fn sampleGrid(
@@ -332,7 +334,7 @@ impl<'a> Detector<'_> {
) -> Result<BitMatrix, Exceptions> { ) -> Result<BitMatrix, Exceptions> {
let sampler = DefaultGridSampler {}; let sampler = DefaultGridSampler {};
return sampler.sample_grid_detailed( sampler.sample_grid_detailed(
image, image,
dimensionX, dimensionX,
dimensionY, dimensionY,
@@ -352,7 +354,7 @@ impl<'a> Detector<'_> {
bottomRight.getY(), bottomRight.getY(),
bottomLeft.getX(), bottomLeft.getX(),
bottomLeft.getY(), bottomLeft.getY(),
); )
} }
/** /**
@@ -404,6 +406,6 @@ impl<'a> Detector<'_> {
x += xstep; x += xstep;
} }
return transitions; transitions
} }
} }

View File

@@ -73,10 +73,10 @@ impl Encoder for ASCIIEncoder {
} }
_ => { _ => {
return Err(Exceptions::IllegalStateException(format!( return Err(Exceptions::IllegalStateException(Some(format!(
"Illegal mode: {}", "Illegal mode: {}",
newMode newMode
))); ))));
} }
} }
} else if high_level_encoder::isExtendedASCII(c) { } else if high_level_encoder::isExtendedASCII(c) {
@@ -105,10 +105,15 @@ impl ASCIIEncoder {
let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48); let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48);
Ok((num + 130) as char) Ok((num + 130) as char)
} else { } else {
Err(Exceptions::IllegalArgumentException(format!( Err(Exceptions::IllegalArgumentException(Some(format!(
"not digits: {}{}", "not digits: {}{}",
digit1, digit2 digit1, digit2
))) ))))
} }
} }
} }
impl Default for ASCIIEncoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -65,10 +65,10 @@ impl Encoder for Base256Encoder {
let (ci_pos, _) = buffer.char_indices().nth(1).unwrap(); let (ci_pos, _) = buffer.char_indices().nth(1).unwrap();
buffer.insert(ci_pos, char::from_u32(dataCount as u32 % 250).unwrap()); buffer.insert(ci_pos, char::from_u32(dataCount as u32 % 250).unwrap());
} else { } else {
return Err(Exceptions::IllegalStateException(format!( return Err(Exceptions::IllegalStateException(Some(format!(
"Message length not in valid ranges: {}", "Message length not in valid ranges: {}",
dataCount dataCount
))); ))));
} }
} }
let c = buffer.chars().count(); let c = buffer.chars().count();
@@ -96,3 +96,9 @@ impl Base256Encoder {
} }
} }
} }
impl Default for Base256Encoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -167,7 +167,7 @@ impl C40Encoder {
let c = context.getCurrentChar(); let c = context.getCurrentChar();
let lastCharSize = encodeChar(c, removed); let lastCharSize = encodeChar(c, removed);
context.resetSymbolInfo(); //Deal with possible reduction in symbol size context.resetSymbolInfo(); //Deal with possible reduction in symbol size
return lastCharSize; lastCharSize
} }
pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) { pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) {
@@ -219,9 +219,9 @@ impl C40Encoder {
context.writeCodeword(C40_UNLATCH); context.writeCodeword(C40_UNLATCH);
} }
} else { } else {
return Err(Exceptions::IllegalStateException( return Err(Exceptions::IllegalStateException(Some(
"Unexpected case. Please report!".to_owned(), "Unexpected case. Please report!".to_owned(),
)); )));
} }
context.signalEncoderChange(ASCII_ENCODATION); context.signalEncoderChange(ASCII_ENCODATION);
@@ -233,11 +233,11 @@ impl C40Encoder {
sb.push('\u{3}'); sb.push('\u{3}');
return 1; return 1;
} }
if c >= '0' && c <= '9' { if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char); sb.push((c as u8 - 48 + 4) as char);
return 1; return 1;
} }
if c >= 'A' && c <= 'Z' { if ('A'..='Z').contains(&c) {
sb.push((c as u8 - 65 + 14) as char); sb.push((c as u8 - 65 + 14) as char);
return 1; return 1;
} }
@@ -274,7 +274,7 @@ impl C40Encoder {
} }
fn encodeToCodewords(sb: &str) -> String { fn encodeToCodewords(sb: &str) -> String {
let v = (1600 * sb.chars().nth(0).unwrap() as u32) let v = (1600 * sb.chars().next().unwrap() as u32)
+ (40 * sb.chars().nth(1).unwrap() as u32) + (40 * sb.chars().nth(1).unwrap() as u32)
+ sb.chars().nth(2).unwrap() as u32 + sb.chars().nth(2).unwrap() as u32
+ 1; + 1;
@@ -286,3 +286,9 @@ impl C40Encoder {
// return new String(new char[] {cw1, cw2}); // return new String(new char[] {cw1, cw2});
} }
} }
impl Default for C40Encoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -64,7 +64,7 @@ impl DefaultPlacement {
} }
pub fn setBit(&mut self, col: usize, row: usize, bit: bool) { pub fn setBit(&mut self, col: usize, row: usize, bit: bool) {
self.bits[row * self.numcols + col] = if bit { 1 } else { 0 }; self.bits[row * self.numcols + col] = u8::from(bit); //if bit { 1 } else { 0 };
} }
pub fn noBit(&self, col: usize, row: usize) -> bool { pub fn noBit(&self, col: usize, row: usize) -> bool {
@@ -281,7 +281,7 @@ mod test_placement {
fn unvisualize(visualized: &str) -> String { fn unvisualize(visualized: &str) -> String {
let mut sb = String::new(); let mut sb = String::new();
for token in visualized.split(" ") { for token in visualized.split(' ') {
// for (String token : SPACE.split(visualized)) { // for (String token : SPACE.split(visualized)) {
let tkn: u32 = token.parse().unwrap(); let tkn: u32 = token.parse().unwrap();
sb.push(char::from_u32(tkn).unwrap()); sb.push(char::from_u32(tkn).unwrap());

View File

@@ -65,7 +65,7 @@ impl EdifactEncoder {
* @param context the encoder context * @param context the encoder context
* @param buffer the buffer with the remaining encoded characters * @param buffer the buffer with the remaining encoded characters
*/ */
fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> { fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> {
let mut runner = || -> Result<(), Exceptions> { let mut runner = || -> Result<(), Exceptions> {
let count = buffer.chars().count(); let count = buffer.chars().count();
if count == 0 { if count == 0 {
@@ -89,9 +89,9 @@ impl EdifactEncoder {
} }
if count > 4 { if count > 4 {
return Err(Exceptions::IllegalStateException( return Err(Exceptions::IllegalStateException(Some(
"Count must not exceed 4".to_owned(), "Count must not exceed 4".to_owned(),
)); )));
} }
let restChars = count - 1; let restChars = count - 1;
let encoded = Self::encodeToCodewords(buffer)?; let encoded = Self::encodeToCodewords(buffer)?;
@@ -127,9 +127,9 @@ impl EdifactEncoder {
} }
fn encodeChar(c: char, sb: &mut String) { fn encodeChar(c: char, sb: &mut String) {
if c >= ' ' && c <= '?' { if (' '..='?').contains(&c) {
sb.push(c); sb.push(c);
} else if c >= '@' && c <= '^' { } else if ('@'..='^').contains(&c) {
sb.push((c as u8 - 64) as char); sb.push((c as u8 - 64) as char);
} else { } else {
high_level_encoder::illegalCharacter(c).expect(""); high_level_encoder::illegalCharacter(c).expect("");
@@ -139,11 +139,11 @@ impl EdifactEncoder {
fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> { fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> {
let len = sb.chars().count(); let len = sb.chars().count();
if len == 0 { if len == 0 {
return Err(Exceptions::IllegalStateException( return Err(Exceptions::IllegalStateException(Some(
"StringBuilder must not be empty".to_owned(), "StringBuilder must not be empty".to_owned(),
)); )));
} }
let c1 = sb.chars().nth(0).unwrap(); let c1 = sb.chars().next().unwrap();
let c2 = if len >= 2 { let c2 = if len >= 2 {
sb.chars().nth(1).unwrap() sb.chars().nth(1).unwrap()
} else { } else {
@@ -161,9 +161,9 @@ impl EdifactEncoder {
}; };
let v: u32 = ((c1 as u32) << 18) + ((c2 as u32) << 12) + ((c3 as u32) << 6) + c4 as u32; let v: u32 = ((c1 as u32) << 18) + ((c2 as u32) << 12) + ((c3 as u32) << 6) + c4 as u32;
let cw1 = (v as u32 >> 16) & 255; let cw1 = (v >> 16) & 255;
let cw2 = (v as u32 >> 8) & 255; let cw2 = (v >> 8) & 255;
let cw3 = v as u32 & 255; let cw3 = v & 255;
let mut res = String::with_capacity(3); let mut res = String::with_capacity(3);
res.push(char::from_u32(cw1).unwrap()); res.push(char::from_u32(cw1).unwrap());
if len >= 2 { if len >= 2 {
@@ -176,3 +176,9 @@ impl EdifactEncoder {
Ok(res) Ok(res)
} }
} }
impl Default for EdifactEncoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -64,9 +64,9 @@ impl<'a> EncoderContext<'_> {
.decode(&encoded_bytes, encoding::DecoderTrap::Strict) .decode(&encoded_bytes, encoding::DecoderTrap::Strict)
.expect("round trip decode should always work") .expect("round trip decode should always work")
} else { } else {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"Message contains characters outside ISO-8859-1 encoding.".to_owned(), "Message contains characters outside ISO-8859-1 encoding.".to_owned(),
)); )));
}; };
Ok(Self { Ok(Self {
symbol_lookup: Rc::new(SymbolInfoLookup::new()), symbol_lookup: Rc::new(SymbolInfoLookup::new()),

View File

@@ -152,9 +152,9 @@ const ALOG: [u32; 255] = {
*/ */
pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String, Exceptions> { pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String, Exceptions> {
if codewords.chars().count() != symbolInfo.getDataCapacity() as usize { if codewords.chars().count() != symbolInfo.getDataCapacity() as usize {
return Err(Exceptions::IllegalArgumentException( return Err(Exceptions::IllegalArgumentException(Some(
"The number of codewords does not match the selected symbol".to_owned(), "The number of codewords does not match the selected symbol".to_owned(),
)); )));
} }
let mut sb = String::with_capacity( let mut sb = String::with_capacity(
(symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()) as usize, (symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()) as usize,
@@ -171,7 +171,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
for i in 0..blockCount { for i in 0..blockCount {
// for (int i = 0; i < blockCount; i++) { // for (int i = 0; i < blockCount; i++) {
dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i as u32 + 1) as u32; dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i as u32 + 1) as u32;
errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i as u32 + 1) as u32; errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i as u32 + 1);
} }
for block in 0..blockCount { for block in 0..blockCount {
// for (int block = 0; block < blockCount; block++) { // for (int block = 0; block < blockCount; block++) {
@@ -186,7 +186,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
let ecc = createECCBlock(&temp, errorSizes[block] as usize)?; let ecc = createECCBlock(&temp, errorSizes[block] as usize)?;
let mut pos = 0; let mut pos = 0;
let mut e = block; let mut e = block;
while e < errorSizes[block] as usize * blockCount as usize { while e < errorSizes[block] as usize * blockCount {
// for (int e = block; e < errorSizes[block] * blockCount; e += blockCount) { // for (int e = block; e < errorSizes[block] * blockCount; e += blockCount) {
let (char_index, replace_char) = sb let (char_index, replace_char) = sb
.char_indices() .char_indices()
@@ -209,18 +209,19 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptions> { fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptions> {
let mut table = -1_isize; let mut table = -1_isize;
for i in 0..FACTOR_SETS.len() { for (i, set) in FACTOR_SETS.iter().enumerate() {
// for i in 0..FACTOR_SETS.len() {
// for (int i = 0; i < FACTOR_SETS.length; i++) { // for (int i = 0; i < FACTOR_SETS.length; i++) {
if FACTOR_SETS[i] as usize == numECWords { if set == &(numECWords as u32) {
table = i as isize; table = i as isize;
break; break;
} }
} }
if table < 0 { if table < 0 {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal number of error correction codewords specified: {}", "Illegal number of error correction codewords specified: {}",
numECWords numECWords
))); ))));
} }
let poly = &FACTORS[table as usize]; let poly = &FACTORS[table as usize];
let mut ecc = vec![0 as char; numECWords]; let mut ecc = vec![0 as char; numECWords];

View File

@@ -119,7 +119,7 @@ fn testC40EncodationSpecialCases1() {
let substitute_symbols = SymbolInfoLookup::new(); let substitute_symbols = SymbolInfoLookup::new();
let substitute_symbols = useTestSymbols(substitute_symbols); let substitute_symbols = useTestSymbols(substitute_symbols);
let sil = Rc::new(substitute_symbols.clone()); let sil = Rc::new(substitute_symbols);
let visualized = encodeHighLevelCompareSIL("AIMAIMAIMAIMAIMAIM", false, Some(sil.clone())); let visualized = encodeHighLevelCompareSIL("AIMAIMAIMAIMAIMAIM", false, Some(sil.clone()));
assert_eq!("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized); assert_eq!("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized);

View File

@@ -284,7 +284,7 @@ pub fn encodeHighLevelWithDimensionForceC40(
pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize { pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize {
let newMode = lookAheadTestIntern(msg, startpos, currentMode); let newMode = lookAheadTestIntern(msg, startpos, currentMode);
if currentMode as usize == X12_ENCODATION && newMode as usize == X12_ENCODATION { if currentMode as usize == X12_ENCODATION && newMode == X12_ENCODATION {
// let msg_graphemes = msg.graphemes(true); // let msg_graphemes = msg.graphemes(true);
let endpos = (startpos + 3).min(msg.chars().count() as u32); let endpos = (startpos + 3).min(msg.chars().count() as u32);
for i in startpos..endpos { for i in startpos..endpos {
@@ -540,20 +540,15 @@ fn findMinimums(
mins[i] += 1; mins[i] += 1;
} }
} }
return min; min
} }
fn getMinimumCount(mins: &[u8]) -> u32 { fn getMinimumCount(mins: &[u8]) -> u32 {
let mut minCount = 0; mins.iter().take(6).sum::<u8>() as u32
for i in 0..6 {
// for (int i = 0; i < 6; i++) {
minCount += mins[i] as u32;
}
minCount
} }
pub fn isDigit(ch: char) -> bool { pub fn isDigit(ch: char) -> bool {
ch >= '0' && ch <= '9' ('0'..='9').contains(&ch)
} }
pub fn isExtendedASCII(ch: char) -> bool { pub fn isExtendedASCII(ch: char) -> bool {
@@ -561,15 +556,15 @@ pub fn isExtendedASCII(ch: char) -> bool {
} }
pub fn isNativeC40(ch: char) -> bool { pub fn isNativeC40(ch: char) -> bool {
(ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') (ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch)
} }
pub fn isNativeText(ch: char) -> bool { pub fn isNativeText(ch: char) -> bool {
(ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') (ch == ' ') || ('0'..='9').contains(&ch) || ('a'..='z').contains(&ch)
} }
pub fn isNativeX12(ch: char) -> bool { pub fn isNativeX12(ch: char) -> bool {
return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); isX12TermSep(ch) || (ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch)
} }
fn isX12TermSep(ch: char) -> bool { fn isX12TermSep(ch: char) -> bool {
@@ -579,7 +574,7 @@ fn isX12TermSep(ch: char) -> bool {
} }
pub fn isNativeEDIFACT(ch: char) -> bool { pub fn isNativeEDIFACT(ch: char) -> bool {
ch >= ' ' && ch <= '^' (' '..='^').contains(&ch)
} }
fn isSpecialB256(_ch: char) -> bool { fn isSpecialB256(_ch: char) -> bool {
@@ -607,8 +602,8 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 {
pub fn illegalCharacter(c: char) -> Result<(), Exceptions> { pub fn illegalCharacter(c: char) -> Result<(), Exceptions> {
// let hex = Integer.toHexString(c); // let hex = Integer.toHexString(c);
// hex = "0000".substring(0, 4 - hex.length()) + hex; // hex = "0000".substring(0, 4 - hex.length()) + hex;
Err(Exceptions::IllegalArgumentException(format!( Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal character: {} (0x{})", "Illegal character: {} (0x{})",
c, c c, c
))) ))))
} }

View File

@@ -65,22 +65,22 @@ const ISO_8859_1_ENCODER: EncodingRef = encoding::all::ISO_8859_1;
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Mode { enum Mode {
ASCII, Ascii,
C40, C40,
TEXT, Text,
X12, X12,
EDF, Edf,
B256, B256,
} }
impl Mode { impl Mode {
pub fn ordinal(&self) -> usize { pub fn ordinal(&self) -> usize {
match self { match self {
Mode::ASCII => 0, Mode::Ascii => 0,
Mode::C40 => 1, Mode::C40 => 1,
Mode::TEXT => 2, Mode::Text => 2,
Mode::X12 => 3, Mode::X12 => 3,
Mode::EDF => 4, Mode::Edf => 4,
Mode::B256 => 5, Mode::B256 => 5,
} }
} }
@@ -177,8 +177,7 @@ pub fn encodeHighLevelWithDetails(
&encode(msg, priorityCharset, fnc1, shape, macroId)?, &encode(msg, priorityCharset, fnc1, shape, macroId)?,
encoding::DecoderTrap::Strict, encoding::DecoderTrap::Strict,
) )
.expect("should decode") .expect("should decode"))
.to_owned())
// return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1); // return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1);
} }
@@ -214,7 +213,7 @@ fn encode(
.to_vec()) .to_vec())
} }
fn addEdge(edges: &mut Vec<Vec<Option<Rc<Edge>>>>, edge: Rc<Edge>) -> Result<(), Exceptions> { fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<(), Exceptions> {
let vertexIndex = (edge.fromPosition + edge.characterLength) as usize; let vertexIndex = (edge.fromPosition + edge.characterLength) as usize;
if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none() if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none()
|| edges[vertexIndex][edge.getEndMode()?.ordinal()] || edges[vertexIndex][edge.getEndMode()?.ordinal()]
@@ -256,7 +255,7 @@ fn getNumberOfC40Words(
} else if !isExtendedASCII(ci, input.getFNC1Character()) { } else if !isExtendedASCII(ci, input.getFNC1Character()) {
thirdsCount += 2; //shift thirdsCount += 2; //shift
} else { } else {
let asciiValue = ci as u8 & 0xff; let asciiValue = ci as u8;
if asciiValue >= 128 if asciiValue >= 128
&& (c40 && high_level_encoder::isNativeC40((asciiValue - 128) as char) && (c40 && high_level_encoder::isNativeC40((asciiValue - 128) as char)
|| !c40 && high_level_encoder::isNativeText((asciiValue - 128) as char)) || !c40 && high_level_encoder::isNativeText((asciiValue - 128) as char))
@@ -280,20 +279,20 @@ fn getNumberOfC40Words(
fn addEdges( fn addEdges(
input: Rc<Input>, input: Rc<Input>,
edges: &mut Vec<Vec<Option<Rc<Edge>>>>, edges: &mut [Vec<Option<Rc<Edge>>>],
from: u32, from: u32,
previous: Option<Rc<Edge>>, previous: Option<Rc<Edge>>,
) -> Result<(), Exceptions> { ) -> Result<(), Exceptions> {
if input.isECI(from)? { if input.isECI(from)? {
addEdge( addEdge(
edges, edges,
Rc::new(Edge::new(input, Mode::ASCII, from, 1, previous.clone())?), Rc::new(Edge::new(input, Mode::Ascii, from, 1, previous)?),
)?; )?;
return Ok(()); return Ok(());
} }
let ch = input.charAt(from as usize)?; let ch = input.charAt(from as usize)?;
if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::EDF { if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::Edf {
//not possible to unlatch a full EDF edge to something //not possible to unlatch a full EDF edge to something
//else //else
if high_level_encoder::isDigit(ch) if high_level_encoder::isDigit(ch)
@@ -305,7 +304,7 @@ fn addEdges(
edges, edges,
Rc::new(Edge::new( Rc::new(Edge::new(
input.clone(), input.clone(),
Mode::ASCII, Mode::Ascii,
from, from,
2, 2,
previous.clone(), previous.clone(),
@@ -317,7 +316,7 @@ fn addEdges(
edges, edges,
Rc::new(Edge::new( Rc::new(Edge::new(
input.clone(), input.clone(),
Mode::ASCII, Mode::Ascii,
from, from,
1, 1,
previous.clone(), previous.clone(),
@@ -325,7 +324,7 @@ fn addEdges(
)?; )?;
} }
let modes = [Mode::C40, Mode::TEXT]; let modes = [Mode::C40, Mode::Text];
for mode in modes { for mode in modes {
// for (Mode mode : modes) { // for (Mode mode : modes) {
let mut characterLength = [0u32; 1]; let mut characterLength = [0u32; 1];
@@ -387,7 +386,7 @@ fn addEdges(
edges, edges,
Rc::new(Edge::new( Rc::new(Edge::new(
input.clone(), input.clone(),
Mode::EDF, Mode::Edf,
from, from,
i + 1, i + 1,
previous.clone(), previous.clone(),
@@ -404,7 +403,7 @@ fn addEdges(
{ {
addEdge( addEdge(
edges, edges,
Rc::new(Edge::new(input, Mode::EDF, from, 4, previous.clone())?), Rc::new(Edge::new(input, Mode::Edf, from, 4, previous)?),
)?; )?;
} }
Ok(()) Ok(())
@@ -626,7 +625,7 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> {
// for (int j = 0; j < 6; j++) { // for (int j = 0; j < 6; j++) {
if edges[inputLength][j].is_some() { if edges[inputLength][j].is_some() {
let edge = edges[inputLength][j].as_ref().unwrap(); let edge = edges[inputLength][j].as_ref().unwrap();
let size = if j >= 1 && j <= 3 { let size = if (1..=3).contains(&j) {
edge.cachedTotalSize + 1 edge.cachedTotalSize + 1
} else { } else {
edge.cachedTotalSize edge.cachedTotalSize
@@ -640,10 +639,10 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> {
} }
if minimalJ < 0 { if minimalJ < 0 {
return Err(Exceptions::RuntimeException(format!( return Err(Exceptions::RuntimeException(Some(format!(
"Internal error: failed to encode \"{}\"", "Internal error: failed to encode \"{}\"",
input input
))); ))));
} }
RXingResult::new(edges[inputLength][minimalJ as usize].clone()) RXingResult::new(edges[inputLength][minimalJ as usize].clone())
} }
@@ -704,7 +703,7 @@ impl Edge {
* B256 -> ASCII: without latch after n bytes * B256 -> ASCII: without latch after n bytes
*/ */
match mode { match mode {
Mode::ASCII => { Mode::Ascii => {
size += 1; size += 1;
if input.isECI(fromPosition).expect("bool") if input.isECI(fromPosition).expect("bool")
|| isExtendedASCII( || isExtendedASCII(
@@ -717,7 +716,7 @@ impl Edge {
size += 1; size += 1;
} }
if previousMode == Mode::C40 if previousMode == Mode::C40
|| previousMode == Mode::TEXT || previousMode == Mode::Text
|| previousMode == Mode::X12 || previousMode == Mode::X12
{ {
size += 1; // unlatch 254 to ASCII size += 1; // unlatch 254 to ASCII
@@ -725,21 +724,22 @@ impl Edge {
} }
Mode::B256 => { Mode::B256 => {
size += 1; size += 1;
if previousMode != Mode::B256 { if previousMode != Mode::B256 || Self::getB256Size(mode, previous.clone()) == 250 {
size += 1; //byte count size += 1; //byte count
} else if Self::getB256Size(mode, previous.clone()) == 250 {
size += 1; //extra byte count
} }
if previousMode == Mode::ASCII { // } else if Self::getB256Size(mode, previous.clone()) == 250 {
// size += 1; //extra byte count
// }
if previousMode == Mode::Ascii {
size += 1; //latch to B256 size += 1; //latch to B256
} else if previousMode == Mode::C40 } else if previousMode == Mode::C40
|| previousMode == Mode::TEXT || previousMode == Mode::Text
|| previousMode == Mode::X12 || previousMode == Mode::X12
{ {
size += 2; //unlatch to ASCII, latch to B256 size += 2; //unlatch to ASCII, latch to B256
} }
} }
Mode::C40 | Mode::TEXT | Mode::X12 => { Mode::C40 | Mode::Text | Mode::X12 => {
if mode == Mode::X12 { if mode == Mode::X12 {
size += 2; size += 2;
} else { } else {
@@ -754,22 +754,22 @@ impl Edge {
* 2; * 2;
} }
if previousMode == Mode::ASCII || previousMode == Mode::B256 { if previousMode == Mode::Ascii || previousMode == Mode::B256 {
size += 1; //additional byte for latch from ASCII to this mode size += 1; //additional byte for latch from ASCII to this mode
} else if previousMode != mode } else if previousMode != mode
&& (previousMode == Mode::C40 && (previousMode == Mode::C40
|| previousMode == Mode::TEXT || previousMode == Mode::Text
|| previousMode == Mode::X12) || previousMode == Mode::X12)
{ {
size += 2; //unlatch 254 to ASCII followed by latch to this mode size += 2; //unlatch 254 to ASCII followed by latch to this mode
} }
} }
Mode::EDF => { Mode::Edf => {
size += 3; size += 3;
if previousMode == Mode::ASCII || previousMode == Mode::B256 { if previousMode == Mode::Ascii || previousMode == Mode::B256 {
size += 1; //additional byte for latch from ASCII to this mode size += 1; //additional byte for latch from ASCII to this mode
} else if previousMode == Mode::C40 } else if previousMode == Mode::C40
|| previousMode == Mode::TEXT || previousMode == Mode::Text
|| previousMode == Mode::X12 || previousMode == Mode::X12
{ {
size += 2; //unlatch 254 to ASCII followed by latch to this mode size += 2; //unlatch 254 to ASCII followed by latch to this mode
@@ -811,7 +811,7 @@ impl Edge {
if let Some(prev) = previous { if let Some(prev) = previous {
prev.mode prev.mode
} else { } else {
Mode::ASCII Mode::Ascii
} }
// if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode} // if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode}
} }
@@ -820,7 +820,7 @@ impl Edge {
if let Some(prev) = previous { if let Some(prev) = previous {
prev.getEndMode() prev.getEndMode()
} else { } else {
Ok(Mode::ASCII) Ok(Mode::Ascii)
} }
// return previous == null ? Mode::ASCII : previous.getEndMode(); // return previous == null ? Mode::ASCII : previous.getEndMode();
} }
@@ -833,27 +833,27 @@ impl Edge {
* */ * */
pub fn getEndMode(&self) -> Result<Mode, Exceptions> { pub fn getEndMode(&self) -> Result<Mode, Exceptions> {
let mode = self.mode; let mode = self.mode;
if mode == Mode::EDF { if mode == Mode::Edf {
if self.characterLength < 4 { if self.characterLength < 4 {
return Ok(Mode::ASCII); return Ok(Mode::Ascii);
} }
let lastASCII = Self::getLastASCII(&self)?; // see 5.2.8.2 EDIFACT encodation Rules let lastASCII = Self::getLastASCII(self)?; // see 5.2.8.2 EDIFACT encodation Rules
if lastASCII > 0 if lastASCII > 0
&& self.getCodewordsRemaining(self.cachedTotalSize + lastASCII) <= 2 - lastASCII && self.getCodewordsRemaining(self.cachedTotalSize + lastASCII) <= 2 - lastASCII
{ {
return Ok(Mode::ASCII); return Ok(Mode::Ascii);
} }
} }
if mode == Mode::C40 || mode == Mode::TEXT || mode == Mode::X12 { if mode == Mode::C40 || mode == Mode::Text || mode == Mode::X12 {
// see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules // see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules
if self.fromPosition + self.characterLength >= self.input.length() as u32 if self.fromPosition + self.characterLength >= self.input.length() as u32
&& self.getCodewordsRemaining(self.cachedTotalSize) == 0 && self.getCodewordsRemaining(self.cachedTotalSize) == 0
{ {
return Ok(Mode::ASCII); return Ok(Mode::Ascii);
} }
let lastASCII = Self::getLastASCII(&self)?; let lastASCII = Self::getLastASCII(self)?;
if lastASCII == 1 && self.getCodewordsRemaining(self.cachedTotalSize + 1) == 0 { if lastASCII == 1 && self.getCodewordsRemaining(self.cachedTotalSize + 1) == 0 {
return Ok(Mode::ASCII); return Ok(Mode::Ascii);
} }
} }
@@ -969,7 +969,7 @@ impl Edge {
* minimal number of codewords. * minimal number of codewords.
**/ **/
pub fn getCodewordsRemaining(&self, minimum: u32) -> u32 { pub fn getCodewordsRemaining(&self, minimum: u32) -> u32 {
Self::getMinSymbolSize(&self, minimum) - minimum Self::getMinSymbolSize(self, minimum) - minimum
} }
pub fn getBytes1(c: u32) -> Vec<u8> { pub fn getBytes1(c: u32) -> Vec<u8> {
@@ -1003,9 +1003,9 @@ impl Edge {
2 2
} else if c == 32 { } else if c == 32 {
3 3
} else if c >= 48 && c <= 57 { } else if (48..=57).contains(&c) {
c - 44 c - 44
} else if c >= 65 && c <= 90 { } else if (65..=90).contains(&c) {
c - 51 c - 51
} else { } else {
c c
@@ -1033,7 +1033,7 @@ impl Edge {
); );
i += 2; i += 2;
} }
return Ok(result); Ok(result)
} }
pub fn getShiftValue(c: char, c40: bool, fnc1: Option<char>) -> u32 { pub fn getShiftValue(c: char, c40: bool, fnc1: Option<char>) -> u32 {
@@ -1055,7 +1055,7 @@ impl Edge {
} }
if c40 { if c40 {
let c = c as u32; let c = c as u32;
return if c <= 31 { if c <= 31 {
c c
} else if c == 32 { } else if c == 32 {
3 3
@@ -1073,10 +1073,10 @@ impl Edge {
c - 96 c - 96
} else { } else {
c c
}; }
} else { } else {
let c = c as u32; let c = c as u32;
return if c == 0 { if c == 0 {
0 0
} else if setIndex == 0 && c <= 3 { } else if setIndex == 0 && c <= 3 {
c - 1 c - 1
@@ -1086,25 +1086,25 @@ impl Edge {
c c
} else if c == 32 { } else if c == 32 {
3 3
} else if c >= 33 && c <= 47 { } else if (33..=47).contains(&c) {
c - 33 c - 33
} else if c >= 48 && c <= 57 { } else if (48..=57).contains(&c) {
c - 44 c - 44
} else if c >= 58 && c <= 64 { } else if (58..=64).contains(&c) {
c - 43 c - 43
} else if c >= 65 && c <= 90 { } else if (65..=90).contains(&c) {
c - 64 c - 64
} else if c >= 91 && c <= 95 { } else if (91..=95).contains(&c) {
c - 69 c - 69
} else if c == 96 { } else if c == 96 {
0 0
} else if c >= 97 && c <= 122 { } else if (97..=122).contains(&c) {
c - 83 c - 83
} else if c >= 123 && c <= 127 { } else if (123..=127).contains(&c) {
c - 96 c - 96
} else { } else {
c c
}; }
} }
} }
@@ -1123,7 +1123,7 @@ impl Edge {
c40Values.push(shiftValue as u8); //Shift[123] c40Values.push(shiftValue as u8); //Shift[123]
c40Values.push(Self::getC40Value(c40, shiftValue, ci, fnc1) as u8); c40Values.push(Self::getC40Value(c40, shiftValue, ci, fnc1) as u8);
} else { } else {
let asciiValue = ((ci as u8 & 0xff) - 128) as char; let asciiValue = (ci as u8 - 128) as char;
if c40 && high_level_encoder::isNativeC40(asciiValue) if c40 && high_level_encoder::isNativeC40(asciiValue)
|| !c40 && high_level_encoder::isNativeText(asciiValue) || !c40 && high_level_encoder::isNativeText(asciiValue)
{ {
@@ -1178,13 +1178,14 @@ impl Edge {
while i < numberOfThirds { while i < numberOfThirds {
// for (int i = 0; i < numberOfThirds; i += 3) { // for (int i = 0; i < numberOfThirds; i += 3) {
let mut edfValues = [0u32; 4]; let mut edfValues = [0u32; 4];
for j in 0..4 { for edfValue in &mut edfValues {
// for j in 0..4 {
// for (int j = 0; j < 4; j++) { // for (int j = 0; j < 4; j++) {
if pos <= endPos { if pos <= endPos {
edfValues[j] = self.input.charAt(pos)? as u32 & 0x3f; *edfValue = self.input.charAt(pos)? as u32 & 0x3f;
pos += 1; pos += 1;
} else { } else {
edfValues[j] = if pos == endPos + 1 { 0x1f } else { 0 }; *edfValue = if pos == endPos + 1 { 0x1f } else { 0 };
} }
} }
let mut val24 = edfValues[0] << 18; let mut val24 = edfValues[0] << 18;
@@ -1203,32 +1204,32 @@ impl Edge {
pub fn getLatchBytes(&self) -> Result<Vec<u8>, Exceptions> { pub fn getLatchBytes(&self) -> Result<Vec<u8>, Exceptions> {
match Self::getPreviousMode(self.previous.clone())? { match Self::getPreviousMode(self.previous.clone())? {
Mode::ASCII | Mode::B256 => Mode::Ascii | Mode::B256 =>
//after B256 ends (via length) we are back to ASCII //after B256 ends (via length) we are back to ASCII
{ {
match self.mode { match self.mode {
Mode::B256 => return Ok(Self::getBytes1(231)), Mode::B256 => return Ok(Self::getBytes1(231)),
Mode::C40 => return Ok(Self::getBytes1(230)), Mode::C40 => return Ok(Self::getBytes1(230)),
Mode::TEXT => return Ok(Self::getBytes1(239)), Mode::Text => return Ok(Self::getBytes1(239)),
Mode::X12 => return Ok(Self::getBytes1(238)), Mode::X12 => return Ok(Self::getBytes1(238)),
Mode::EDF => return Ok(Self::getBytes1(240)), Mode::Edf => return Ok(Self::getBytes1(240)),
_ => {} _ => {}
} }
} }
Mode::C40 | Mode::TEXT | Mode::X12 Mode::C40 | Mode::Text | Mode::X12
if self.mode != Self::getPreviousMode(self.previous.clone())? => if self.mode != Self::getPreviousMode(self.previous.clone())? =>
{ {
match self.mode { match self.mode {
Mode::ASCII => return Ok(Self::getBytes1(254)), Mode::Ascii => return Ok(Self::getBytes1(254)),
Mode::B256 => return Ok(Self::getBytes2(254, 231)), Mode::B256 => return Ok(Self::getBytes2(254, 231)),
Mode::C40 => return Ok(Self::getBytes2(254, 230)), Mode::C40 => return Ok(Self::getBytes2(254, 230)),
Mode::TEXT => return Ok(Self::getBytes2(254, 239)), Mode::Text => return Ok(Self::getBytes2(254, 239)),
Mode::X12 => return Ok(Self::getBytes2(254, 238)), Mode::X12 => return Ok(Self::getBytes2(254, 238)),
Mode::EDF => return Ok(Self::getBytes2(254, 240)), Mode::Edf => return Ok(Self::getBytes2(254, 240)),
} }
} }
Mode::C40 | Mode::TEXT | Mode::X12 => {} Mode::C40 | Mode::Text | Mode::X12 => {}
Mode::EDF => assert!(self.mode == Mode::EDF), //The rightmost EDIFACT edge always contains an unlatch character Mode::Edf => assert!(self.mode == Mode::Edf), //The rightmost EDIFACT edge always contains an unlatch character
} }
Ok(Vec::new()) Ok(Vec::new())
@@ -1237,12 +1238,12 @@ impl Edge {
// Important: The function does not return the length bytes (one or two) in case of B256 encoding // Important: The function does not return the length bytes (one or two) in case of B256 encoding
pub fn getDataBytes(&self) -> Result<Vec<u8>, Exceptions> { pub fn getDataBytes(&self) -> Result<Vec<u8>, Exceptions> {
match self.mode { match self.mode {
Mode::ASCII => { Mode::Ascii => {
if self.input.isECI(self.fromPosition)? { if self.input.isECI(self.fromPosition)? {
return Ok(Self::getBytes2( Ok(Self::getBytes2(
241, 241,
self.input.getECIValue(self.fromPosition as usize)? as u32 + 1, self.input.getECIValue(self.fromPosition as usize)? as u32 + 1,
)); ))
} else if isExtendedASCII( } else if isExtendedASCII(
self.input.charAt(self.fromPosition as usize)?, self.input.charAt(self.fromPosition as usize)?,
self.input.getFNC1Character(), self.input.getFNC1Character(),
@@ -1266,15 +1267,13 @@ impl Edge {
)); ));
} }
} }
Mode::B256 => { Mode::B256 => Ok(Self::getBytes1(
return Ok(Self::getBytes1(
self.input.charAt(self.fromPosition as usize)? as u32, self.input.charAt(self.fromPosition as usize)? as u32,
)) )),
} Mode::C40 => self.getC40Words(true, self.input.getFNC1Character()),
Mode::C40 => return self.getC40Words(true, self.input.getFNC1Character()), Mode::Text => self.getC40Words(false, self.input.getFNC1Character()),
Mode::TEXT => return self.getC40Words(false, self.input.getFNC1Character()), Mode::X12 => self.getX12Words(),
Mode::X12 => return self.getX12Words(), Mode::Edf => self.getEDFBytes(),
Mode::EDF => return self.getEDFBytes(),
} }
// assert!( false); // assert!( false);
// Ok(vec![0]) // Ok(vec![0])
@@ -1289,15 +1288,15 @@ impl RXingResult {
let solution = if let Some(edge) = solution { let solution = if let Some(edge) = solution {
edge edge
} else { } else {
return Err(Exceptions::IllegalArgumentException("()".to_string())); return Err(Exceptions::IllegalArgumentException(None));
}; };
let input = solution.input.clone(); let input = solution.input.clone();
let mut size = 0; let mut size = 0;
let mut bytesAL = Vec::new(); //new ArrayList<>(); let mut bytesAL = Vec::new(); //new ArrayList<>();
let mut randomizePostfixLength = Vec::new(); //new ArrayList<>(); let mut randomizePostfixLength = Vec::new(); //new ArrayList<>();
let mut randomizeLengths = Vec::new(); //new ArrayList<>(); let mut randomizeLengths = Vec::new(); //new ArrayList<>();
if (solution.mode == Mode::C40 || solution.mode == Mode::TEXT || solution.mode == Mode::X12) if (solution.mode == Mode::C40 || solution.mode == Mode::Text || solution.mode == Mode::X12)
&& solution.getEndMode()? != Mode::ASCII && solution.getEndMode()? != Mode::Ascii
{ {
size += Self::prepend(&Edge::getBytes1(254), &mut bytesAL); size += Self::prepend(&Edge::getBytes1(254), &mut bytesAL);
} }
@@ -1355,10 +1354,11 @@ impl RXingResult {
} }
let mut bytes = vec![0u8; bytesAL.len()]; let mut bytes = vec![0u8; bytesAL.len()];
for i in 0..bytes.len() { // for (i, byte) in bytes.iter_mut().enumerate() {
// for (int i = 0; i < bytes.length; i++) { // // for (int i = 0; i < bytes.length; i++) {
bytes[i] = *bytesAL.get(i).unwrap(); // *byte = *bytesAL.get(i).unwrap();
} // }
bytes[..].copy_from_slice(&bytesAL[..]);
Ok(Self { bytes }) Ok(Self { bytes })
} }

View File

@@ -127,9 +127,9 @@ impl SymbolInfo {
2 | 4 => Ok(2), 2 | 4 => Ok(2),
16 => Ok(4), 16 => Ok(4),
36 => Ok(6), 36 => Ok(6),
_ => Err(Exceptions::IllegalStateException( _ => Err(Exceptions::IllegalStateException(Some(
"Cannot handle this number of data regions".to_owned(), "Cannot handle this number of data regions".to_owned(),
)), ))),
} }
// switch (dataRegions) { // switch (dataRegions) {
// case 1: // case 1:
@@ -152,9 +152,9 @@ impl SymbolInfo {
4 => Ok(2), 4 => Ok(2),
16 => Ok(4), 16 => Ok(4),
36 => Ok(6), 36 => Ok(6),
_ => Err(Exceptions::IllegalStateException( _ => Err(Exceptions::IllegalStateException(Some(
"Cannot handle this number of data regions".to_owned(), "Cannot handle this number of data regions".to_owned(),
)), ))),
} }
// switch (dataRegions) { // switch (dataRegions) {
// case 1: // case 1:
@@ -344,10 +344,10 @@ impl<'a> SymbolInfoLookup<'a> {
} }
} }
if fail { if fail {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can't find a symbol arrangement that matches the message. Data codewords: {}", "Can't find a symbol arrangement that matches the message. Data codewords: {}",
dataCodewords dataCodewords
))); ))));
} }
Ok(None) Ok(None)
} }

View File

@@ -40,11 +40,11 @@ impl TextEncoder {
sb.push('\u{3}'); sb.push('\u{3}');
return 1; return 1;
} }
if c >= '0' && c <= '9' { if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char); sb.push((c as u8 - 48 + 4) as char);
return 1; return 1;
} }
if c >= 'a' && c <= 'z' { if ('a'..='z').contains(&c) {
sb.push((c as u8 - 97 + 14) as char); sb.push((c as u8 - 97 + 14) as char);
return 1; return 1;
} }
@@ -63,7 +63,7 @@ impl TextEncoder {
sb.push((c as u8 - 58 + 15) as char); sb.push((c as u8 - 58 + 15) as char);
return 2; return 2;
} }
if c >= '[' && c <= '_' { if ('['..='_').contains(&c) {
sb.push('\u{1}'); //Shift 2 Set sb.push('\u{1}'); //Shift 2 Set
sb.push((c as u8 - 91 + 22) as char); sb.push((c as u8 - 91 + 22) as char);
return 2; return 2;
@@ -86,6 +86,12 @@ impl TextEncoder {
sb.push_str("\u{1}\u{001e}"); //Shift 2, Upper Shift sb.push_str("\u{1}\u{001e}"); //Shift 2, Upper Shift
let mut len = 2; let mut len = 2;
len += Self::encodeChar((c as u8 - 128) as char, sb); len += Self::encodeChar((c as u8 - 128) as char, sb);
return len; len
}
}
impl Default for TextEncoder {
fn default() -> Self {
Self::new()
} }
} }

View File

@@ -65,19 +65,19 @@ impl X12Encoder {
'>' => sb.push('\u{2}'), '>' => sb.push('\u{2}'),
' ' => sb.push('\u{3}'), ' ' => sb.push('\u{3}'),
_ => { _ => {
if c >= '0' && c <= '9' { if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char); sb.push((c as u8 - 48 + 4) as char);
} else if c >= 'A' && c <= 'Z' { } else if ('A'..='Z').contains(&c) {
sb.push((c as u8 - 65 + 14) as char); sb.push((c as u8 - 65 + 14) as char);
} else { } else {
high_level_encoder::illegalCharacter(c).expect("detect_illegal_character"); high_level_encoder::illegalCharacter(c).expect("detect_illegal_character");
} }
} }
} }
return 1; 1
} }
fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> { fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> {
context.updateSymbolInfo(); context.updateSymbolInfo();
let available = let available =
context.getSymbolInfo().unwrap().getDataCapacity() - context.getCodewordCount() as u32; context.getSymbolInfo().unwrap().getDataCapacity() - context.getCodewordCount() as u32;
@@ -95,3 +95,9 @@ impl X12Encoder {
Ok(()) Ok(())
} }
} }
impl Default for X12Encoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -32,11 +32,11 @@ impl Dimension {
} }
pub fn getWidth(&self) -> usize { pub fn getWidth(&self) -> usize {
return self.0; self.0
} }
pub fn getHeight(&self) -> usize { pub fn getHeight(&self) -> usize {
return self.1; self.1
} }
} }

View File

@@ -2,44 +2,68 @@ use std::{error::Error, fmt};
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum Exceptions { pub enum Exceptions {
IllegalArgumentException(String), IllegalArgumentException(Option<String>),
UnsupportedOperationException(String), UnsupportedOperationException(Option<String>),
IllegalStateException(String), IllegalStateException(Option<String>),
ArithmeticException(String), ArithmeticException(Option<String>),
NotFoundException(String), NotFoundException(Option<String>),
FormatException(String), FormatException(Option<String>),
ChecksumException(String), ChecksumException(Option<String>),
ReaderException(String), ReaderException(Option<String>),
WriterException(String), WriterException(Option<String>),
ReedSolomonException(String), ReedSolomonException(Option<String>),
IndexOutOfBoundsException(String), IndexOutOfBoundsException(Option<String>),
RuntimeException(String), RuntimeException(Option<String>),
ParseException(String), ParseException(Option<String>),
ReaderDecodeException(), ReaderDecodeException(),
} }
impl fmt::Display for Exceptions { impl fmt::Display for Exceptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Exceptions::IllegalArgumentException(a) => { Exceptions::IllegalArgumentException(Some(a)) => {
write!(f, "IllegalArgumentException - {}", a) write!(f, "IllegalArgumentException - {}", a)
} }
Exceptions::UnsupportedOperationException(a) => {
Exceptions::UnsupportedOperationException(Some(a)) => {
write!(f, "UnsupportedOperationException - {}", a) write!(f, "UnsupportedOperationException - {}", a)
} }
Exceptions::IllegalStateException(a) => write!(f, "IllegalStateException - {}", a),
Exceptions::ArithmeticException(a) => write!(f, "ArithmeticException - {}", a), Exceptions::IllegalStateException(Some(a)) => {
Exceptions::NotFoundException(a) => write!(f, "NotFoundException - {}", a), write!(f, "IllegalStateException - {}", a)
Exceptions::FormatException(a) => write!(f, "FormatException - {}", a), }
Exceptions::ChecksumException(a) => write!(f, "ChecksumException - {}", a), Exceptions::ArithmeticException(Some(a)) => write!(f, "ArithmeticException - {}", a),
Exceptions::ReaderException(a) => write!(f, "ReaderException - {}", a), Exceptions::NotFoundException(Some(a)) => write!(f, "NotFoundException - {}", a),
Exceptions::WriterException(a) => write!(f, "WriterException - {}", a), Exceptions::FormatException(Some(a)) => write!(f, "FormatException - {}", a),
Exceptions::ReedSolomonException(a) => write!(f, "ReedSolomonException - {}", a), Exceptions::ChecksumException(Some(a)) => write!(f, "ChecksumException - {}", a),
Exceptions::IndexOutOfBoundsException(a) => { Exceptions::ReaderException(Some(a)) => write!(f, "ReaderException - {}", a),
Exceptions::WriterException(Some(a)) => write!(f, "WriterException - {}", a),
Exceptions::ReedSolomonException(Some(a)) => write!(f, "ReedSolomonException - {}", a),
Exceptions::IndexOutOfBoundsException(Some(a)) => {
write!(f, "IndexOutOfBoundsException - {}", a) write!(f, "IndexOutOfBoundsException - {}", a)
} }
Exceptions::RuntimeException(a) => write!(f, "RuntimeException - {}", a),
Exceptions::ParseException(a) => write!(f, "ParseException - {}", a), Exceptions::RuntimeException(Some(a)) => write!(f, "RuntimeException - {}", a),
Exceptions::ParseException(Some(a)) => write!(f, "ParseException - {}", a),
Exceptions::IllegalArgumentException(None) => write!(f, "IllegalArgumentException"),
Exceptions::UnsupportedOperationException(None) => {
write!(f, "UnsupportedOperationException")
}
Exceptions::IllegalStateException(None) => write!(f, "IllegalStateException"),
Exceptions::ArithmeticException(None) => write!(f, "ArithmeticException"),
Exceptions::NotFoundException(None) => write!(f, "NotFoundException"),
Exceptions::FormatException(None) => write!(f, "FormatException"),
Exceptions::ChecksumException(None) => write!(f, "ChecksumException"),
Exceptions::ReaderException(None) => write!(f, "ReaderException"),
Exceptions::WriterException(None) => write!(f, "WriterException"),
Exceptions::ReedSolomonException(None) => write!(f, "ReedSolomonException"),
Exceptions::IndexOutOfBoundsException(None) => write!(f, "IndexOutOfBoundsException"),
Exceptions::RuntimeException(None) => write!(f, "RuntimeException"),
Exceptions::ParseException(None) => write!(f, "ParseException"),
Exceptions::ReaderDecodeException() => write!(f, "ReaderDecodeException - -"), Exceptions::ReaderDecodeException() => write!(f, "ReaderDecodeException - -"),
} }
} }

View File

@@ -71,7 +71,7 @@ pub trait LuminanceSource {
* @return Whether this subclass supports cropping. * @return Whether this subclass supports cropping.
*/ */
fn isCropSupported(&self) -> bool { fn isCropSupported(&self) -> bool {
return false; false
} }
/** /**
@@ -91,16 +91,16 @@ pub trait LuminanceSource {
_width: usize, _width: usize,
_height: usize, _height: usize,
) -> Result<Box<dyn LuminanceSource>, Exceptions> { ) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(Exceptions::UnsupportedOperationException( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support cropping.".to_owned(), "This luminance source does not support cropping.".to_owned(),
)); )))
} }
/** /**
* @return Whether this subclass supports counter-clockwise rotation. * @return Whether this subclass supports counter-clockwise rotation.
*/ */
fn isRotateSupported(&self) -> bool { fn isRotateSupported(&self) -> bool {
return false; false
} }
/** /**
@@ -118,9 +118,9 @@ pub trait LuminanceSource {
* @return A rotated version of this object. * @return A rotated version of this object.
*/ */
fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> { fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(Exceptions::UnsupportedOperationException( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support rotation by 90 degrees.".to_owned(), "This luminance source does not support rotation by 90 degrees.".to_owned(),
)); )))
} }
/** /**
@@ -130,16 +130,16 @@ pub trait LuminanceSource {
* @return A rotated version of this object. * @return A rotated version of this object.
*/ */
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> { fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
return Err(Exceptions::UnsupportedOperationException( Err(Exceptions::UnsupportedOperationException(Some(
"This luminance source does not support rotation by 45 degrees.".to_owned(), "This luminance source does not support rotation by 45 degrees.".to_owned(),
)); )))
} }
fn invert_block_of_bytes(&self, vec_to_invert: Vec<u8>) -> Vec<u8> { fn invert_block_of_bytes(&self, vec_to_invert: Vec<u8>) -> Vec<u8> {
let mut iv = vec_to_invert.clone(); let mut iv = vec_to_invert;
for itm in iv.iter_mut() { for itm in iv.iter_mut() {
let z = *itm; let z = *itm;
*itm = 255 - (z & 0xFF); *itm = 255 - z;
} }
iv iv
} }

View File

@@ -169,14 +169,16 @@ impl BitMatrixParser {
let mut result = [0u8; 144]; let mut result = [0u8; 144];
let height = self.0.getHeight() as usize; let height = self.0.getHeight() as usize;
let width = self.0.getWidth() as usize; let width = self.0.getWidth() as usize;
for y in 0..height { for (y, bitnrRow) in BITNR.iter().enumerate().take(height) {
// for y in 0..height {
// for (int y = 0; y < height; y++) { // for (int y = 0; y < height; y++) {
let bitnrRow = BITNR[y]; // let bitnrRow = BITNR[y];
for x in 0..width { for (x, bit) in bitnrRow.iter().enumerate().take(width) {
// for x in 0..width {
// for (int x = 0; x < width; x++) { // for (int x = 0; x < width; x++) {
let bit = bitnrRow[x]; // let bit = bitnrRow[x];
if bit >= 0 && self.0.get(x as u32, y as u32) { if *bit >= 0 && self.0.get(x as u32, y as u32) {
result[bit as usize / 6] |= 1 << (5 - (bit % 6)); result[*bit as usize / 6] |= 1 << (5 - (bit % 6));
} }
} }
} }

View File

@@ -85,19 +85,18 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result<DecoderRXingResult, Exceptions>
let mut result = String::with_capacity(144); let mut result = String::with_capacity(144);
match mode { match mode {
2 | 3 => { 2 | 3 => {
let postcode; let postcode = if mode == 2 {
if mode == 2 {
let pc = getPostCode2(bytes); let pc = getPostCode2(bytes);
let ps2Length = getPostCode2Length(bytes) as usize; let ps2Length = getPostCode2Length(bytes) as usize;
if ps2Length > 10 { if ps2Length > 10 {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException(None));
} }
// NumberFormat df = new DecimalFormat("0000000000".substring(0, ps2Length)); // NumberFormat df = new DecimalFormat("0000000000".substring(0, ps2Length));
// postcode = df.format(pc); // postcode = df.format(pc);
postcode = format!("{:0>ps2Length$}", pc) format!("{:0>ps2Length$}", pc)
} else { } else {
postcode = getPostCode3(bytes); getPostCode3(bytes)
} };
// NumberFormat threeDigits = new DecimalFormat("000"); // NumberFormat threeDigits = new DecimalFormat("000");
// let country = threeDigits.format(getCountry(bytes)); // let country = threeDigits.format(getCountry(bytes));
// let service = threeDigits.format(getServiceClass(bytes)); // let service = threeDigits.format(getServiceClass(bytes));
@@ -134,11 +133,12 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result<DecoderRXingResult, Exceptions>
fn getBit(bit: u8, bytes: &[u8]) -> u8 { fn getBit(bit: u8, bytes: &[u8]) -> u8 {
let bit = bit - 1; let bit = bit - 1;
if (bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) == 0 { u8::from((bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) != 0)
0 // if (bytes[bit as usize / 6] & (1 << (5 - (bit % 6)))) == 0 {
} else { // 0
1 // } else {
} // 1
// }
} }
fn getInt(bytes: &[u8], x: &[u8]) -> u32 { fn getInt(bytes: &[u8], x: &[u8]) -> u32 {
@@ -259,5 +259,5 @@ fn subtract_two_single_char_strings(str1: &str, str2: &str) -> usize {
let str2_u16 = let str2_u16 =
((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize; ((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize;
(str1_u16 - str2_u16) as usize str1_u16 - str2_u16
} }

View File

@@ -70,7 +70,7 @@ pub fn decode_with_hints(
correctErrors(&mut codewords, 20, 68, 56, ODD)?; correctErrors(&mut codewords, 20, 68, 56, ODD)?;
datawords = vec![0u8; 78]; datawords = vec![0u8; 78];
} }
_ => return Err(Exceptions::NotFoundException("".to_owned())), _ => return Err(Exceptions::NotFoundException(None)),
} }
datawords[0..10].clone_from_slice(&codewords[0..10]); datawords[0..10].clone_from_slice(&codewords[0..10]);
@@ -79,7 +79,7 @@ pub fn decode_with_hints(
datawords[10..datawords_len].clone_from_slice(&codewords[20..datawords_len + 10]); datawords[10..datawords_len].clone_from_slice(&codewords[20..datawords_len + 10]);
// System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10); // System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10);
return decoded_bit_stream_parser::decode(&datawords, mode); decoded_bit_stream_parser::decode(&datawords, mode)
} }
fn correctErrors( fn correctErrors(

View File

@@ -62,7 +62,7 @@ impl Reader for MaxiCodeReader {
// Note that MaxiCode reader effectively always assumes PURE_BARCODE mode // Note that MaxiCode reader effectively always assumes PURE_BARCODE mode
// and can't detect it in an image // and can't detect it in an image
let bits = Self::extractPureBits(image.getBlackMatrix())?; let bits = Self::extractPureBits(image.getBlackMatrix())?;
let decoderRXingResult = decoder::decode_with_hints(bits, &hints)?; let decoderRXingResult = decoder::decode_with_hints(bits, hints)?;
let mut result = RXingResult::new( let mut result = RXingResult::new(
decoderRXingResult.getText(), decoderRXingResult.getText(),
decoderRXingResult.getRawBytes().clone(), decoderRXingResult.getRawBytes().clone(),
@@ -97,7 +97,7 @@ impl MaxiCodeReader {
fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> { fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let enclosingRectangleOption = image.getEnclosingRectangle(); let enclosingRectangleOption = image.getEnclosingRectangle();
if enclosingRectangleOption.is_none() { if enclosingRectangleOption.is_none() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let enclosingRectangle = enclosingRectangleOption.unwrap(); let enclosingRectangle = enclosingRectangleOption.unwrap();

View File

@@ -56,7 +56,7 @@ impl<T: Reader> MultipleBarcodeReader for GenericMultipleBarcodeReader<T> {
let mut results = Vec::new(); let mut results = Vec::new();
self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0); self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0);
if results.is_empty() { if results.is_empty() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
Ok(results) Ok(results)
} }

View File

@@ -52,8 +52,8 @@ impl<'a> MultiDetector<'_> {
let mut finder = MultiFinderPatternFinder::new(image, resultPointCallback); let mut finder = MultiFinderPatternFinder::new(image, resultPointCallback);
let infos = finder.findMulti(hints)?; let infos = finder.findMulti(hints)?;
if infos.len() == 0 { if infos.is_empty() {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let mut result = Vec::new(); let mut result = Vec::new();

View File

@@ -90,9 +90,9 @@ impl MultiFinderPatternFinder {
if size < 3 { if size < 3 {
// Couldn't find enough finder patterns // Couldn't find enough finder patterns
return Err(Exceptions::NotFoundException( return Err(Exceptions::NotFoundException(Some(
"Couldn't find enough finder patterns".to_owned(), "Couldn't find enough finder patterns".to_owned(),
)); )));
} }
/* /*
@@ -179,8 +179,8 @@ impl MultiFinderPatternFinder {
// Check the sizes // Check the sizes
let estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0); let estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0);
if estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE if !(MIN_MODULE_COUNT_PER_EDGE..=MAX_MODULE_COUNT_PER_EDGE)
|| estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE .contains(&estimatedModuleCount)
{ {
continue; continue;
} }
@@ -210,7 +210,7 @@ impl MultiFinderPatternFinder {
if !results.is_empty() { if !results.is_empty() {
Ok(results) Ok(results)
} else { } else {
Err(Exceptions::NotFoundException("no result".to_owned())) Err(Exceptions::NotFoundException(None))
} }
} }

View File

@@ -171,7 +171,7 @@ impl QRCodeMultiReader {
let mut newRXingResult = let mut newRXingResult =
RXingResult::new(&newText, newRawBytes, Vec::new(), BarcodeFormat::QR_CODE); RXingResult::new(&newText, newRawBytes, Vec::new(), BarcodeFormat::QR_CODE);
if newByteSegment.len() > 0 { if !newByteSegment.is_empty() {
newRXingResult.putMetadata( newRXingResult.putMetadata(
RXingResultMetadataType::BYTE_SEGMENTS, RXingResultMetadataType::BYTE_SEGMENTS,
RXingResultMetadataValue::ByteSegments(vec![newByteSegment]), RXingResultMetadataValue::ByteSegments(vec![newByteSegment]),

View File

@@ -31,6 +31,7 @@ use crate::{
* @author Sean Owen * @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin) * @author dswitkin@google.com (Daniel Switkin)
*/ */
#[derive(Default)]
pub struct MultiFormatReader { pub struct MultiFormatReader {
hints: DecodingHintDictionary, hints: DecodingHintDictionary,
readers: Vec<Box<dyn Reader>>, readers: Vec<Box<dyn Reader>>,
@@ -205,15 +206,6 @@ impl MultiFormatReader {
} }
} }
} }
return Err(Exceptions::NotFoundException("".to_owned())); Err(Exceptions::NotFoundException(None))
}
}
impl Default for MultiFormatReader {
fn default() -> Self {
Self {
hints: HashMap::new(),
readers: Vec::new(),
}
} }
} }

View File

@@ -70,10 +70,10 @@ impl Writer for MultiFormatWriter {
BarcodeFormat::DATA_MATRIX => Box::<DataMatrixWriter>::default(), BarcodeFormat::DATA_MATRIX => Box::<DataMatrixWriter>::default(),
BarcodeFormat::AZTEC => Box::<AztecWriter>::default(), BarcodeFormat::AZTEC => Box::<AztecWriter>::default(),
_ => { _ => {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"No encoder available for format {:?}", "No encoder available for format {:?}",
format format
))) ))))
} }
}; };

View File

@@ -64,7 +64,7 @@ impl OneDReader for CodaBarReader {
loop { loop {
let charOffset = self.toNarrowWidePattern(nextStart); let charOffset = self.toNarrowWidePattern(nextStart);
if charOffset == -1 { if charOffset == -1 {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
// Hack: We store the position in the alphabet table into a // Hack: We store the position in the alphabet table into a
// StringBuilder, so that we can access the decoded patterns in // StringBuilder, so that we can access the decoded patterns in
@@ -81,7 +81,7 @@ impl OneDReader for CodaBarReader {
{ {
break; break;
} }
if !(nextStart < self.counterLength) { if nextStart >= self.counterLength {
break; break;
} // no fixed end pattern so keep on reading while data is available } // no fixed end pattern so keep on reading while data is available
} //while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available } //while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available
@@ -98,7 +98,7 @@ impl OneDReader for CodaBarReader {
// otherwise this is probably a false positive. The exception is if we are // otherwise this is probably a false positive. The exception is if we are
// at the end of the row. (I.e. the barcode barely fits.) // at the end of the row. (I.e. the barcode barely fits.)
if nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2 { if nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2 {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
self.validatePattern(startOffset)?; self.validatePattern(startOffset)?;
@@ -114,9 +114,9 @@ impl OneDReader for CodaBarReader {
// self.decodeRowRXingResult.setCharAt(i, Self::ALPHABET[self.decodeRowRXingResult.chars().nth(i).unwrap() as usize]); // self.decodeRowRXingResult.setCharAt(i, Self::ALPHABET[self.decodeRowRXingResult.chars().nth(i).unwrap() as usize]);
} }
// Ensure a valid start and end character // Ensure a valid start and end character
let startchar = self.decodeRowRXingResult.chars().nth(0).unwrap(); let startchar = self.decodeRowRXingResult.chars().next().unwrap();
if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) { if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let endchar = self let endchar = self
.decodeRowRXingResult .decodeRowRXingResult
@@ -124,13 +124,13 @@ impl OneDReader for CodaBarReader {
.nth(self.decodeRowRXingResult.chars().count() - 1) .nth(self.decodeRowRXingResult.chars().count() - 1)
.unwrap(); .unwrap();
if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) { if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
// remove stop/start characters character and check if a long enough string is contained // remove stop/start characters character and check if a long enough string is contained
if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize { if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize {
// Almost surely a false positive ( start + stop + at least 1 character) // Almost surely a false positive ( start + stop + at least 1 character)
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
if !hints.contains_key(&DecodeHintType::RETURN_CODABAR_START_END) { if !hints.contains_key(&DecodeHintType::RETURN_CODABAR_START_END) {
@@ -231,7 +231,7 @@ impl CodaBarReader {
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for // Even j = bars, while odd j = spaces. Categories 2 and 3 are for
// long stripes, while 0 and 1 are for short stripes. // long stripes, while 0 and 1 are for short stripes.
let category = (j & 1) + ((pattern as usize) & 1) * 2; let category = (j & 1) + ((pattern as usize) & 1) * 2;
sizes[category] += self.counters[(pos + j) as usize]; sizes[category] += self.counters[(pos + j)];
counts[category] += 1; counts[category] += 1;
pattern >>= 1; pattern >>= 1;
} }
@@ -269,7 +269,7 @@ impl CodaBarReader {
let category = (j & 1) + ((pattern as usize) & 1) * 2; let category = (j & 1) + ((pattern as usize) & 1) * 2;
let size = self.counters[(pos + j)]; let size = self.counters[(pos + j)];
if (size as f32) < mins[category] || (size as f32) > maxes[category] { if (size as f32) < mins[category] || (size as f32) > maxes[category] {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
pattern >>= 1; pattern >>= 1;
} }
@@ -290,7 +290,7 @@ impl CodaBarReader {
let mut i = row.getNextUnset(0); let mut i = row.getNextUnset(0);
let end = row.getSize(); let end = row.getSize();
if i >= end { if i >= end {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
let mut isWhite = true; let mut isWhite = true;
let mut count = 0; let mut count = 0;
@@ -344,7 +344,7 @@ impl CodaBarReader {
i += 2; i += 2;
} }
Err(Exceptions::NotFoundException("".to_owned())) Err(Exceptions::NotFoundException(None))
} }
pub fn arrayContains(array: &[char], key: char) -> bool { pub fn arrayContains(array: &[char], key: char) -> bool {
@@ -355,7 +355,7 @@ impl CodaBarReader {
} }
} }
// } // }
return false; false
} }
// Assumes that counters[position] is a bar. // Assumes that counters[position] is a bar.
@@ -422,6 +422,6 @@ impl CodaBarReader {
return i as i32; return i as i32;
} }
} }
return -1; -1
} }
} }

View File

@@ -30,7 +30,7 @@ const DEFAULT_GUARD: char = START_END_CHARS[0];
* *
* @author dsbnatut@gmail.com (Kazuki Nishiura) * @author dsbnatut@gmail.com (Kazuki Nishiura)
*/ */
#[derive(OneDWriter)] #[derive(OneDWriter, Default)]
pub struct CodaBarWriter; pub struct CodaBarWriter;
impl OneDimensionalCodeWriter for CodaBarWriter { impl OneDimensionalCodeWriter for CodaBarWriter {
@@ -40,7 +40,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD) format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD)
} else { } else {
// Verify input and calculate decoded length. // Verify input and calculate decoded length.
let firstChar = contents.chars().nth(0).unwrap().to_ascii_uppercase(); let firstChar = contents.chars().next().unwrap().to_ascii_uppercase();
let lastChar = contents let lastChar = contents
.chars() .chars()
.nth(contents.chars().count() - 1) .nth(contents.chars().count() - 1)
@@ -52,29 +52,29 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar); let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar);
if startsNormal { if startsNormal {
if !endsNormal { if !endsNormal {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Invalid start/end guards: {}", "Invalid start/end guards: {}",
contents contents
))); ))));
} }
// else already has valid start/end // else already has valid start/end
contents.to_owned() contents.to_owned()
} else if startsAlt { } else if startsAlt {
if !endsAlt { if !endsAlt {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Invalid start/end guards: {}", "Invalid start/end guards: {}",
contents contents
))); ))));
} }
// else already has valid start/end // else already has valid start/end
contents.to_owned() contents.to_owned()
} else { } else {
// Doesn't start with a guard // Doesn't start with a guard
if endsNormal || endsAlt { if endsNormal || endsAlt {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Invalid start/end guards: {}", "Invalid start/end guards: {}",
contents contents
))); ))));
} }
// else doesn't end with guard either, so add a default // else doesn't end with guard either, so add a default
format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD) format!("{}{}{}", DEFAULT_GUARD, contents, DEFAULT_GUARD)
@@ -86,7 +86,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
//for i in 1..contents.chars().count() { //for i in 1..contents.chars().count() {
for ch in contents[1..contents.chars().count() - 1].chars() { for ch in contents[1..contents.chars().count() - 1].chars() {
// for (int i = 1; i < contents.length() - 1; i++) { // for (int i = 1; i < contents.length() - 1; i++) {
if ch.is_digit(10) || ch == '-' || ch == '$' { if ch.is_ascii_digit() || ch == '-' || ch == '$' {
resultLength += 9; resultLength += 9;
} else if CodaBarReader::arrayContains( } else if CodaBarReader::arrayContains(
&CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED, &CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED,
@@ -94,10 +94,10 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
) { ) {
resultLength += 10; resultLength += 10;
} else { } else {
return Err(Exceptions::IllegalArgumentException(format!( return Err(Exceptions::IllegalArgumentException(Some(format!(
"Cannot encode : '{}'", "Cannot encode : '{}'",
ch ch
))); ))));
} }
} }
// A blank is placed between each character. // A blank is placed between each character.
@@ -155,12 +155,6 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
} }
} }
impl Default for CodaBarWriter {
fn default() -> Self {
Self {}
}
}
/** /**
* @author dsbnatut@gmail.com (Kazuki Nishiura) * @author dsbnatut@gmail.com (Kazuki Nishiura)
* @author Sean Owen * @author Sean Owen

View File

@@ -25,7 +25,7 @@ use super::{one_d_reader, OneDReader};
* *
* @author Sean Owen * @author Sean Owen
*/ */
#[derive(OneDReader)] #[derive(OneDReader, Default)]
pub struct Code128Reader; pub struct Code128Reader;
impl OneDReader for Code128Reader { impl OneDReader for Code128Reader {
@@ -50,7 +50,7 @@ impl OneDReader for Code128Reader {
CODE_START_A => CODE_CODE_A, CODE_START_A => CODE_CODE_A,
CODE_START_B => CODE_CODE_B, CODE_START_B => CODE_CODE_B,
CODE_START_C => CODE_CODE_C, CODE_START_C => CODE_CODE_C,
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException(None)),
}; };
let mut done = false; let mut done = false;
@@ -106,7 +106,7 @@ impl OneDReader for Code128Reader {
// Take care of illegal start codes // Take care of illegal start codes
match code { match code {
CODE_START_A | CODE_START_B | CODE_START_C => { CODE_START_A | CODE_START_B | CODE_START_C => {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException(None))
} }
_ => {} _ => {}
} }
@@ -301,21 +301,21 @@ impl OneDReader for Code128Reader {
row.getSize().min(nextStart + (nextStart - lastStart) / 2), row.getSize().min(nextStart + (nextStart - lastStart) / 2),
false, false,
)? { )? {
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
// Pull out from sum the value of the penultimate check code // Pull out from sum the value of the penultimate check code
checksumTotal -= multiplier as usize * lastCode as usize; checksumTotal -= multiplier as usize * lastCode as usize;
// lastCode is the checksum then: // lastCode is the checksum then:
if (checksumTotal % 103) as u8 != lastCode { if (checksumTotal % 103) as u8 != lastCode {
return Err(Exceptions::ChecksumException("".to_owned())); return Err(Exceptions::ChecksumException(None));
} }
// Need to pull out the check digits from string // Need to pull out the check digits from string
let resultLength = result.chars().count(); let resultLength = result.chars().count();
if resultLength == 0 { if resultLength == 0 {
// false positive // false positive
return Err(Exceptions::NotFoundException("".to_owned())); return Err(Exceptions::NotFoundException(None));
} }
// Only bother if the result had at least one character, and if the checksum digit happened to // Only bother if the result had at least one character, and if the checksum digit happened to
@@ -340,9 +340,9 @@ impl OneDReader for Code128Reader {
let rawCodesSize = rawCodes.len(); let rawCodesSize = rawCodes.len();
let mut rawBytes = vec![0u8; rawCodesSize]; let mut rawBytes = vec![0u8; rawCodesSize];
for i in 0..rawCodesSize { for (i, rawByte) in rawBytes.iter_mut().enumerate().take(rawCodesSize) {
// for (int i = 0; i < rawCodesSize; i++) { // for (int i = 0; i < rawCodesSize; i++) {
rawBytes[i] = *rawCodes.get(i).unwrap(); *rawByte = *rawCodes.get(i).unwrap();
} }
let mut resultObject = RXingResult::new( let mut resultObject = RXingResult::new(
&result, &result,
@@ -419,7 +419,7 @@ impl Code128Reader {
} }
} }
Err(Exceptions::NotFoundException("".to_owned())) Err(Exceptions::NotFoundException(None))
} }
fn decodeCode( fn decodeCode(
@@ -435,7 +435,7 @@ impl Code128Reader {
// for (int d = 0; d < CODE_PATTERNS.len(); d++) { // for (int d = 0; d < CODE_PATTERNS.len(); d++) {
let pattern = &CODE_PATTERNS[d]; let pattern = &CODE_PATTERNS[d];
let variance = let variance =
one_d_reader::patternMatchVariance(counters, &pattern, MAX_INDIVIDUAL_VARIANCE); one_d_reader::patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
if variance < bestVariance { if variance < bestVariance {
bestVariance = variance; bestVariance = variance;
bestMatch = d as isize; bestMatch = d as isize;
@@ -445,17 +445,11 @@ impl Code128Reader {
if bestMatch >= 0 { if bestMatch >= 0 {
Ok(bestMatch as u8) Ok(bestMatch as u8)
} else { } else {
Err(Exceptions::NotFoundException("".to_owned())) Err(Exceptions::NotFoundException(None))
} }
} }
} }
impl Default for Code128Reader {
fn default() -> Self {
Self {}
}
}
use lazy_static::lazy_static; use lazy_static::lazy_static;
lazy_static! { lazy_static! {

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