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

@@ -19,7 +19,7 @@ use std::collections::HashMap;
/**
* @author Guenther Grau
*/
#[derive(Clone)]
#[derive(Clone, Default)]
pub struct BarcodeValue(HashMap<u32, u32>);
// private final Map<Integer,Integer> values = new HashMap<>();
@@ -70,9 +70,3 @@ impl BarcodeValue {
}
}
}
impl Default for BarcodeValue {
fn default() -> Self {
Self(Default::default())
}
}

View File

@@ -44,7 +44,7 @@ impl BoundingBox {
let leftUnspecified = topLeft.is_none() || bottomLeft.is_none();
let rightUnspecified = topRight.is_none() || bottomRight.is_none();
if leftUnspecified && rightUnspecified {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let newTopLeft;

View File

@@ -33,12 +33,12 @@ use crate::{
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
ALPHA,
LOWER,
MIXED,
PUNCT,
ALPHA_SHIFT,
PUNCT_SHIFT,
Alpha,
Lower,
Mixed,
Punct,
AlphaShift,
PunctShift,
}
const TEXT_COMPACTION_MODE_LATCH: u32 = 900;
@@ -131,7 +131,7 @@ const NUMBER_OF_SEQUENCE_CODEWORDS: usize = 2;
pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Exceptions> {
let mut result = ECIStringBuilder::with_capacity(codewords.len() * 2);
let mut codeIndex = textCompaction(codewords, 1, &mut result)? as usize;
let mut codeIndex = textCompaction(codewords, 1, &mut result)?;
let mut resultMetadata = PDF417RXingResultMetadata::default();
while codeIndex < codewords[0] as usize {
let code = codewords[codeIndex];
@@ -170,7 +170,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
BEGIN_MACRO_PDF417_OPTIONAL_FIELD | MACRO_PDF417_TERMINATOR =>
// Should not see these outside a macro block
{
return Err(Exceptions::FormatException("".to_owned()))
return Err(Exceptions::FormatException(None))
}
_ => {
// Default to text compaction. During testing numerous barcodes
@@ -185,7 +185,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
result = result.build_result();
if result.is_empty() && resultMetadata.getFileId().is_empty() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let mut decoderRXingResult = DecoderRXingResult::new(
@@ -207,25 +207,26 @@ pub fn decodeMacroBlock(
let mut codeIndex = codeIndex;
if codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0] as usize {
// we must have at least two bytes left for the segment index
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS];
for i in 0..NUMBER_OF_SEQUENCE_CODEWORDS {
for seq in segmentIndexArray
.iter_mut()
.take(NUMBER_OF_SEQUENCE_CODEWORDS)
{
// for (int i = 0; i < NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) {
segmentIndexArray[i] = codewords[codeIndex];
*seq = codewords[codeIndex];
codeIndex += 1;
}
let segmentIndexString =
decodeBase900toBase10(&segmentIndexArray, NUMBER_OF_SEQUENCE_CODEWORDS)?;
if segmentIndexString.is_empty() {
resultMetadata.setSegmentIndex(0);
} else if let Ok(parsed_int) = segmentIndexString.parse::<usize>() {
resultMetadata.setSegmentIndex(parsed_int);
} else {
if let Ok(parsed_int) = segmentIndexString.parse::<usize>() {
resultMetadata.setSegmentIndex(parsed_int);
} else {
// too large; bad input?
return Err(Exceptions::FormatException("".to_owned()));
}
// too large; bad input?
return Err(Exceptions::FormatException(None));
}
// Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec
@@ -242,7 +243,7 @@ pub fn decodeMacroBlock(
}
if fileId.chars().count() == 0 {
// at least one fileId codeword is required (Annex H.2)
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
resultMetadata.setFileId(fileId);
@@ -298,14 +299,14 @@ pub fn decodeMacroBlock(
fileSize = fileSize.build_result();
resultMetadata.setFileSize(fileSize.to_string().parse().unwrap());
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
MACRO_PDF417_TERMINATOR => {
codeIndex += 1;
resultMetadata.setLastSegment(true);
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
@@ -345,13 +346,13 @@ fn textCompaction(
) -> Result<usize, Exceptions> {
let mut codeIndex = codeIndex;
// 2 character per codeword
let mut textCompactionData = vec![0; (codewords[0] as usize - codeIndex) as usize * 2];
let mut textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2];
// Used to hold the byte compaction value if there is a mode shift
let mut byteCompactionData = vec![0; (codewords[0] as usize - codeIndex) as usize * 2];
let mut byteCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2];
let mut index = 0;
let mut end = false;
let mut subMode = Mode::ALPHA;
let mut subMode = Mode::Alpha;
while (codeIndex < codewords[0] as usize) && !end {
let mut code = codewords[codeIndex];
codeIndex += 1;
@@ -454,7 +455,7 @@ fn decodeTextCompaction(
let subModeCh = textCompactionData[i];
let mut ch = 0 as char;
match subMode {
Mode::ALPHA =>
Mode::Alpha =>
// Alpha (uppercase alphabetic)
{
if subModeCh < 26 {
@@ -464,23 +465,23 @@ fn decodeTextCompaction(
match subModeCh {
26 => ch = ' ',
LL => {
subMode = Mode::LOWER;
subMode = Mode::Lower;
latchedMode = subMode;
}
ML => {
subMode = Mode::MIXED;
subMode = Mode::Mixed;
latchedMode = subMode;
}
PS => {
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode::PUNCT_SHIFT;
subMode = Mode::PunctShift;
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
result.append_char(char::from_u32(byteCompactionData[i]).unwrap())
}
TEXT_COMPACTION_MODE_LATCH => {
subMode = Mode::ALPHA;
subMode = Mode::Alpha;
latchedMode = subMode;
}
_ => {}
@@ -488,7 +489,7 @@ fn decodeTextCompaction(
}
}
Mode::LOWER =>
Mode::Lower =>
// Lower (lowercase alphabetic)
{
if subModeCh < 26 {
@@ -499,22 +500,22 @@ fn decodeTextCompaction(
AS => {
// Shift to alpha
priorToShiftMode = subMode;
subMode = Mode::ALPHA_SHIFT;
subMode = Mode::AlphaShift;
}
ML => {
subMode = Mode::MIXED;
subMode = Mode::Mixed;
latchedMode = subMode;
}
PS => {
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode::PUNCT_SHIFT;
subMode = Mode::PunctShift;
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
result.append_char(char::from_u32(byteCompactionData[i]).unwrap())
}
TEXT_COMPACTION_MODE_LATCH => {
subMode = Mode::ALPHA;
subMode = Mode::Alpha;
latchedMode = subMode;
}
_ => {}
@@ -522,7 +523,7 @@ fn decodeTextCompaction(
}
}
Mode::MIXED =>
Mode::Mixed =>
// Mixed (numeric and some punctuation)
{
if subModeCh < PL {
@@ -530,22 +531,22 @@ fn decodeTextCompaction(
} else {
match subModeCh {
PL => {
subMode = Mode::PUNCT;
subMode = Mode::Punct;
latchedMode = subMode;
}
26 => ch = ' ',
LL => {
subMode = Mode::LOWER;
subMode = Mode::Lower;
latchedMode = subMode;
}
AL | TEXT_COMPACTION_MODE_LATCH => {
subMode = Mode::ALPHA;
subMode = Mode::Alpha;
latchedMode = subMode;
}
PS => {
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode::PUNCT_SHIFT;
subMode = Mode::PunctShift;
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
result.append_char(char::from_u32(byteCompactionData[i]).unwrap())
@@ -555,7 +556,7 @@ fn decodeTextCompaction(
}
}
Mode::PUNCT =>
Mode::Punct =>
// Punctuation
{
if subModeCh < PAL {
@@ -563,7 +564,7 @@ fn decodeTextCompaction(
} else {
match subModeCh {
PAL | TEXT_COMPACTION_MODE_LATCH => {
subMode = Mode::ALPHA;
subMode = Mode::Alpha;
latchedMode = subMode;
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
@@ -574,7 +575,7 @@ fn decodeTextCompaction(
}
}
Mode::ALPHA_SHIFT => {
Mode::AlphaShift => {
// Restore sub-mode
subMode = priorToShiftMode;
if subModeCh < 26 {
@@ -582,20 +583,20 @@ fn decodeTextCompaction(
} else {
match subModeCh {
26 => ch = ' ',
TEXT_COMPACTION_MODE_LATCH => subMode = Mode::ALPHA,
TEXT_COMPACTION_MODE_LATCH => subMode = Mode::Alpha,
_ => {}
}
}
}
Mode::PUNCT_SHIFT => {
Mode::PunctShift => {
// Restore sub-mode
subMode = priorToShiftMode;
if subModeCh < PAL {
ch = PUNCT_CHARS[subModeCh as usize];
} else {
match subModeCh {
PAL | TEXT_COMPACTION_MODE_LATCH => subMode = Mode::ALPHA,
PAL | TEXT_COMPACTION_MODE_LATCH => subMode = Mode::Alpha,
MODE_SHIFT_TO_BYTE_COMPACTION_MODE =>
// PS before Shift-to-Byte is used as a padding character,
// see 5.4.2.4 of the specification
@@ -613,7 +614,7 @@ fn decodeTextCompaction(
}
i += 1;
}
return latchedMode;
latchedMode
}
/**
@@ -802,8 +803,8 @@ fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result<String, Exce
// result = result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i])));
}
let resultString = result.to_string();
if resultString.chars().nth(0).unwrap() != '1' {
return Err(Exceptions::FormatException("".to_owned()));
if !resultString.starts_with('1') {
return Err(Exceptions::FormatException(None));
}
Ok(resultString[1..].to_owned())
}

View File

@@ -138,7 +138,7 @@ impl DetectionRXingResult {
}
}
}
return unadjustedCount;
unadjustedCount
}
fn adjustRowNumbersByRow(&mut self) -> u32 {
@@ -153,7 +153,7 @@ impl DetectionRXingResult {
fn adjustRowNumbersFromBothRI(&mut self) {
if self.detectionRXingResultColumns[0].is_none()
&& self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1].is_none()
&& self.detectionRXingResultColumns[self.barcodeColumnCount + 1].is_none()
{
return;
}
@@ -167,89 +167,85 @@ impl DetectionRXingResult {
.len()
{
// for (int codewordsRow = 0; codewordsRow < LRIcodewords.length; codewordsRow++) {
if
//let (Some(lricw), Some(rricw)) =
self.detectionRXingResultColumns[0]
if self.detectionRXingResultColumns[0]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.is_some()
&& self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1]
&& self.detectionRXingResultColumns[self.barcodeColumnCount + 1]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.is_some()
{
if self.detectionRXingResultColumns[0]
&& self.detectionRXingResultColumns[0]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.as_ref()
.unwrap()
.getRowNumber()
== self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1]
== self.detectionRXingResultColumns[self.barcodeColumnCount + 1]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.as_ref()
.unwrap()
.getRowNumber()
{
// if (LRIcodewords[codewordsRow] != null &&
// RRIcodewords[codewordsRow] != null &&
// LRIcodewords[codewordsRow].getRowNumber() == RRIcodewords[codewordsRow].getRowNumber()) {
for barcodeColumn in 1..=self.barcodeColumnCount {
// for (int barcodeColumn = 1; barcodeColumn <= barcodeColumnCount; barcodeColumn++) {
if self.detectionRXingResultColumns[barcodeColumn].is_some()
//let Some(dc_col) =
//&mut self.detectionRXingResultColumns[barcodeColumn]
{
// if (LRIcodewords[codewordsRow] != null &&
// RRIcodewords[codewordsRow] != null &&
// LRIcodewords[codewordsRow].getRowNumber() == RRIcodewords[codewordsRow].getRowNumber()) {
for barcodeColumn in 1..=self.barcodeColumnCount {
// for (int barcodeColumn = 1; barcodeColumn <= barcodeColumnCount; barcodeColumn++) {
if self.detectionRXingResultColumns[barcodeColumn].is_some()
//let Some(dc_col) =
//&mut self.detectionRXingResultColumns[barcodeColumn]
{
if self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow]
.is_some()
{
if self.detectionRXingResultColumns[barcodeColumn]
//let Some(codeword) = &mut self.detectionRXingResultColumns[barcodeColumn].as_mut().unwrap().getCodewordsMut()[codewordsRow] {
let new_row_number = self.detectionRXingResultColumns[0]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.as_ref()
.unwrap()
.getRowNumber();
self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow]
.is_some()
.as_mut()
.unwrap()
.setRowNumber(new_row_number);
if !self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow]
.as_ref()
.unwrap()
.hasValidRowNumber()
{
//let Some(codeword) = &mut self.detectionRXingResultColumns[barcodeColumn].as_mut().unwrap().getCodewordsMut()[codewordsRow] {
let new_row_number = self.detectionRXingResultColumns[0]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
.as_ref()
.unwrap()
.getRowNumber();
// self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow] = None;
self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow]
.as_mut()
.unwrap()
.setRowNumber(new_row_number);
if !self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow]
.as_ref()
.unwrap()
.hasValidRowNumber()
{
// self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow] = None;
self.detectionRXingResultColumns[barcodeColumn]
.as_mut()
.unwrap()
.getCodewordsMut()[codewordsRow] = None;
}
} else {
continue;
.getCodewordsMut()[codewordsRow] = None;
}
} else {
continue;
}
// let codeword = self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow];
// if (codeword == null) {
// continue;
// }
} else {
continue;
}
// let codeword = self.detectionRXingResultColumns[barcodeColumn].getCodewords()[codewordsRow];
// if (codeword == null) {
// continue;
// }
}
}
}
@@ -260,12 +256,12 @@ impl DetectionRXingResult {
}
fn adjustRowNumbersFromRRI(&mut self) -> u32 {
if self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1].is_none() {
if self.detectionRXingResultColumns[self.barcodeColumnCount + 1].is_none() {
return 0;
}
// if let Some(col) = &self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1] {
let mut unadjustedCount = 0;
let codewords_len = self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1]
let codewords_len = self.detectionRXingResultColumns[self.barcodeColumnCount + 1]
.as_ref()
.unwrap()
.getCodewords()
@@ -273,7 +269,7 @@ impl DetectionRXingResult {
for codewordsRow in 0..codewords_len {
// for (int codewordsRow = 0; codewordsRow < codewords.length; codewordsRow++) {
// if let Some(codeword_col) = codewords[codewordsRow] {
if self.detectionRXingResultColumns[self.barcodeColumnCount as usize + 1]
if self.detectionRXingResultColumns[self.barcodeColumnCount + 1]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
@@ -282,7 +278,7 @@ impl DetectionRXingResult {
continue;
}
let rowIndicatorRowNumber = self.detectionRXingResultColumns
[self.barcodeColumnCount as usize + 1]
[self.barcodeColumnCount + 1]
.as_ref()
.unwrap()
.getCodewords()[codewordsRow]
@@ -290,7 +286,7 @@ impl DetectionRXingResult {
.unwrap()
.getRowNumber();
let mut invalidRowCounts = 0;
let mut barcodeColumn = self.barcodeColumnCount as usize + 1;
let mut barcodeColumn = self.barcodeColumnCount + 1;
while barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP {
// for (int barcodeColumn = barcodeColumnCount + 1;
// barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP;
@@ -375,7 +371,7 @@ impl DetectionRXingResult {
.getRowNumber();
let mut invalidRowCounts = 0;
let mut barcodeColumn = 1_usize;
while barcodeColumn < self.barcodeColumnCount as usize + 1
while barcodeColumn < self.barcodeColumnCount + 1
&& invalidRowCounts < ADJUST_ROW_NUMBER_SKIP
{
// for (int barcodeColumn = 1;
@@ -624,11 +620,12 @@ impl DetectionRXingResult {
barcodeColumn: usize,
detectionRXingResultColumn: Option<impl DetectionRXingResultRowIndicatorColumn + 'static>,
) {
self.detectionRXingResultColumns[barcodeColumn] = if detectionRXingResultColumn.is_none() {
None
} else {
Some(Box::new(detectionRXingResultColumn.unwrap()))
};
self.detectionRXingResultColumns[barcodeColumn] =
if let Some(detectionRXingResultColumn) = detectionRXingResultColumn {
Some(Box::new(detectionRXingResultColumn))
} else {
None
};
}
pub fn getDetectionRXingResultColumn(
@@ -660,7 +657,7 @@ impl Display for DetectionRXingResult {
for barcodeColumn in 0..self.barcodeColumnCount + 2 {
// for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) {
if self.detectionRXingResultColumns[barcodeColumn].is_none() {
write!(f, "{}", " | ")?;
write!(f, " | ")?;
// formatter.format(" | ");
continue;
}
@@ -669,7 +666,7 @@ impl Display for DetectionRXingResult {
.unwrap()
.getCodewords()[codewordsRow];
if codeword.is_none() {
write!(f, "{}", " | ")?;
write!(f, " | ")?;
// formatter.format(" | ");
continue;
}
@@ -682,7 +679,7 @@ impl Display for DetectionRXingResult {
// formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue());
}
// formatter.format("%n");
write!(f, "{}", "\n")?;
writeln!(f)?;
}
// return formatter.toString();
write!(f, "")

View File

@@ -127,19 +127,19 @@ impl DetectionRXingResultColumnTrait for DetectionRXingResultColumn {
impl Display for DetectionRXingResultColumn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.isLeft.is_some() {
write!(f, "IsLeft: {} \n", self.isLeft.as_ref().unwrap())?;
writeln!(f, "IsLeft: {} ", self.isLeft.as_ref().unwrap())?;
}
let mut row = 0;
for codeword in &self.codewords {
// for (Codeword codeword : codewords) {
if codeword.is_none() {
write!(f, "{:3}: | \n", row)?;
writeln!(f, "{:3}: | ", row)?;
row += 1;
continue;
}
write!(
writeln!(
f,
"{:3}: {:3}|{:3}\n",
"{:3}: {:3}|{:3}",
row,
codeword.as_ref().unwrap().getRowNumber(),
codeword.as_ref().unwrap().getValue()

View File

@@ -90,12 +90,11 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn {
{
self.getCodewordsMut()[codewordsRow] = None;
} else {
let checkedRows;
if maxRowHeight > 2 {
checkedRows = (maxRowHeight - 2) * rowDifference;
let checkedRows = if maxRowHeight > 2 {
(maxRowHeight - 2) * rowDifference
} else {
checkedRows = rowDifference;
}
rowDifference
};
let mut closePreviousCodewordFound = checkedRows >= codewordsRow as i32;
let mut i = 1;
while i <= checkedRows && !closePreviousCodewordFound {
@@ -103,7 +102,7 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn {
// there must be (height * rowDifference) number of codewords missing. For now we assume height = 1.
// This should hopefully get rid of most problems already.
closePreviousCodewordFound =
self.getCodewords()[codewordsRow as usize - i as usize].is_some();
self.getCodewords()[codewordsRow - i as usize].is_some();
i += 1;
}
@@ -176,10 +175,10 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn {
}
}
// Maybe we should check if we have ambiguous values?
if (barcodeColumnCount.getValue().len() == 0)
|| (barcodeRowCountUpperPart.getValue().len() == 0)
|| (barcodeRowCountLowerPart.getValue().len() == 0)
|| (barcodeECLevel.getValue().len() == 0)
if barcodeColumnCount.getValue().is_empty()
|| barcodeRowCountUpperPart.getValue().is_empty()
|| barcodeRowCountLowerPart.getValue().is_empty()
|| barcodeECLevel.getValue().is_empty()
|| barcodeColumnCount.getValue()[0] < 1
|| barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0]
< pdf_417_common::MIN_ROWS_IN_BARCODE
@@ -211,13 +210,13 @@ impl DetectionRXingResultRowIndicatorColumn for DetectionRXingResultColumn {
// }
fn setRowNumbers(code_words: &mut [Option<Codeword>]) {
for codeword_opt in code_words {
for codeword in code_words.iter_mut().flatten() {
//self.0.getCodewordsMut() {
// for (Codeword codeword : getCodewords()) {
if let Some(codeword) = codeword_opt {
// if (codeword != null) {
codeword.setRowNumberAsRowIndicatorColumn();
}
// if let Some(codeword) = codeword_opt {
// if (codeword != null) {
codeword.setRowNumberAsRowIndicatorColumn();
// }
}
}
@@ -228,13 +227,14 @@ fn removeIncorrectCodewords(
) {
// Remove codewords which do not match the metadata
// TODO Maybe we should keep the incorrect codewords for the start and end positions?
for codewordRow in 0..codewords.len() {
for codeword_row in codewords.iter_mut() {
// for codewordRow in 0..codewords.len() {
// for (int codewordRow = 0; codewordRow < codewords.length; codewordRow++) {
if let Some(codeword) = codewords[codewordRow] {
if let Some(codeword) = codeword_row {
let rowIndicatorValue = codeword.getValue() % 30;
let mut codewordRowNumber = codeword.getRowNumber();
if codewordRowNumber > barcodeMetadata.getRowCount() as i32 {
codewords[codewordRow] = None;
*codeword_row = None;
continue;
}
if !isLeft {
@@ -243,19 +243,19 @@ fn removeIncorrectCodewords(
match codewordRowNumber % 3 {
0 => {
if rowIndicatorValue * 3 + 1 != barcodeMetadata.getRowCountUpperPart() {
codewords[codewordRow] = None;
*codeword_row = None;
}
}
1 => {
if rowIndicatorValue / 3 != barcodeMetadata.getErrorCorrectionLevel()
|| rowIndicatorValue % 3 != barcodeMetadata.getRowCountLowerPart()
{
codewords[codewordRow] = None;
*codeword_row = None;
}
}
2 => {
if rowIndicatorValue + 1 != barcodeMetadata.getColumnCount() {
codewords[codewordRow] = None;
*codeword_row = None;
}
}
_ => {}
@@ -291,10 +291,10 @@ fn adjustIncompleteIndicatorColumnRowNumbers(
let mut barcodeRow = -1;
let mut maxRowHeight = 1;
let mut currentRowHeight = 0;
for codewordsRow in firstRow..lastRow {
for codword_opt in codewords.iter_mut().take(lastRow).skip(firstRow) {
// for (int codewordsRow = firstRow; codewordsRow < lastRow; codewordsRow++) {
if let Some(codeword) = &mut codewords[codewordsRow] {
if let Some(codeword) = codword_opt {
codeword.setRowNumberAsRowIndicatorColumn();
let rowDifference = codeword.getRowNumber() - barcodeRow;
@@ -308,7 +308,7 @@ fn adjustIncompleteIndicatorColumnRowNumbers(
currentRowHeight = 1;
barcodeRow = codeword.getRowNumber();
} else if codeword.getRowNumber() >= barcodeMetadata.getRowCount() as i32 {
codewords[codewordsRow] = None;
*codword_opt = None;
} else {
barcodeRow = codeword.getRowNumber();
currentRowHeight = 1;

View File

@@ -47,13 +47,13 @@ lazy_static! {
* @return number of errors
* @throws ChecksumException if errors cannot be corrected, maybe because of too many errors
*/
pub fn decode<'a>(
pub fn decode(
received: &mut [u32],
numECCodewords: u32,
erasures: &mut [u32],
) -> Result<usize, Exceptions> {
let field: Rc<&'static ModulusGF> = Rc::new(&FLD_INTERIOR);
let poly = ModulusPoly::new(field.clone(), received.to_vec())?;
let field: &'static ModulusGF = &FLD_INTERIOR;
let poly = ModulusPoly::new(field, received.to_vec())?;
let mut S = vec![0u32; numECCodewords as usize];
let mut error = false;
for i in (1..=numECCodewords).rev() {
@@ -69,7 +69,7 @@ pub fn decode<'a>(
return Ok(0);
}
let mut knownErrors: Rc<ModulusPoly> = ModulusPoly::getOne(field.clone());
let mut knownErrors: Rc<ModulusPoly> = ModulusPoly::getOne(field);
let mut b;
let mut term;
let mut kE: Rc<ModulusPoly>;
@@ -78,34 +78,34 @@ pub fn decode<'a>(
// for (int erasure : erasures) {
b = field.exp(received.len() as u32 - 1 - *erasure);
// Add (1 - bx) term:
term = ModulusPoly::new(field.clone(), vec![field.subtract(0, b), 1])?;
term = ModulusPoly::new(field, vec![field.subtract(0, b), 1])?;
kE = knownErrors.clone();
knownErrors = kE.multiply(Rc::new(term))?;
}
}
let syndrome = Rc::new(ModulusPoly::new(field.clone(), S)?);
let syndrome = Rc::new(ModulusPoly::new(field, S)?);
//syndrome = syndrome.multiply(knownErrors);
let sigmaOmega = runEuclideanAlgorithm(
ModulusPoly::buildMonomial(field.clone(), numECCodewords as usize, 1),
ModulusPoly::buildMonomial(field, numECCodewords as usize, 1),
syndrome,
numECCodewords,
field.clone(),
field,
)?;
let sigma = sigmaOmega[0].clone();
let omega = sigmaOmega[1].clone();
//sigma = sigma.multiply(knownErrors);
let mut errorLocations = findErrorLocations(sigma.clone(), field.clone())?;
let errorMagnitudes = findErrorMagnitudes(omega, sigma, &mut errorLocations, field.clone());
let mut errorLocations = findErrorLocations(sigma.clone(), field)?;
let errorMagnitudes = findErrorMagnitudes(omega, sigma, &mut errorLocations, field);
for i in 0..errorLocations.len() {
// for (int i = 0; i < errorLocations.length; i++) {
let position = received.len() as isize - 1 - field.log(errorLocations[i])? as isize;
if position < 0 {
return Err(Exceptions::ChecksumException(format!("{}", file!())));
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
}
received[position as usize] =
field.subtract(received[position as usize], errorMagnitudes[i]);
@@ -118,7 +118,7 @@ fn runEuclideanAlgorithm(
a: Rc<ModulusPoly>,
b: Rc<ModulusPoly>,
R: u32,
field: Rc<&'static ModulusGF>,
field: &'static ModulusGF,
) -> Result<[Rc<ModulusPoly>; 2], Exceptions> {
// Assume a's degree is >= b's
let mut a = a;
@@ -129,8 +129,8 @@ fn runEuclideanAlgorithm(
let mut rLast = a;
let mut r = b;
let mut tLast = ModulusPoly::getZero(field.clone());
let mut t = ModulusPoly::getOne(field.clone());
let mut tLast = ModulusPoly::getZero(field);
let mut t = ModulusPoly::getOne(field);
// Run Euclidean algorithm until r's degree is less than R/2
while r.getDegree() >= R / 2 {
@@ -142,17 +142,17 @@ fn runEuclideanAlgorithm(
// Divide rLastLast by rLast, with quotient in q and remainder in r
if rLast.isZero() {
// Oops, Euclidean algorithm already terminated?
return Err(Exceptions::ChecksumException(format!("{}", file!())));
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
}
r = rLastLast;
let mut q = ModulusPoly::getZero(field.clone()); //field.getZero();
let mut q = ModulusPoly::getZero(field); //field.getZero();
let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree() as usize);
let dltInverse = field.inverse(denominatorLeadingTerm)?;
while r.getDegree() >= rLast.getDegree() && !r.isZero() {
let degreeDiff = r.getDegree() - rLast.getDegree();
let scale = field.multiply(r.getCoefficient(r.getDegree() as usize), dltInverse);
q = q.add(ModulusPoly::buildMonomial(
field.clone(),
field,
degreeDiff as usize,
scale,
))?;
@@ -164,7 +164,7 @@ fn runEuclideanAlgorithm(
let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 {
return Err(Exceptions::ChecksumException(format!("{}", file!())));
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
}
let inverse = field.inverse(sigmaTildeAtZero)?;
@@ -176,7 +176,7 @@ fn runEuclideanAlgorithm(
fn findErrorLocations(
errorLocator: Rc<ModulusPoly>,
field: Rc<&ModulusGF>,
field: &ModulusGF,
) -> Result<Vec<u32>, Exceptions> {
// This is a direct application of Chien's search
let numErrors = errorLocator.getDegree();
@@ -192,7 +192,7 @@ fn findErrorLocations(
i += 1;
}
if e != numErrors {
return Err(Exceptions::ChecksumException(format!("{}", file!())));
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
}
Ok(result)
}
@@ -201,7 +201,7 @@ fn findErrorMagnitudes(
errorEvaluator: Rc<ModulusPoly>,
errorLocator: Rc<ModulusPoly>,
errorLocations: &mut [u32],
field: Rc<&'static ModulusGF>,
field: &'static ModulusGF,
) -> Vec<u32> {
let errorLocatorDegree = errorLocator.getDegree();
if errorLocatorDegree < 1 {
@@ -213,8 +213,8 @@ fn findErrorMagnitudes(
formalDerivativeCoefficients[errorLocatorDegree as usize - i as usize] =
field.multiply(i, errorLocator.getCoefficient(i as usize));
}
let formalDerivative = ModulusPoly::new(field.clone(), formalDerivativeCoefficients)
.expect("should generate good poly");
let formalDerivative =
ModulusPoly::new(field, formalDerivativeCoefficients).expect("should generate good poly");
// This is directly applying Forney's Formula
let s = errorLocations.len();

View File

@@ -49,7 +49,7 @@ const _MAX_ERASURES: usize = ERROR_LIMIT;
#[test]
fn testNoError() {
let mut received = PDF417_TEST_WITH_EC.clone();
let mut received = PDF417_TEST_WITH_EC;
// no errors
checkDecode(&mut received).expect("ok");
}
@@ -58,7 +58,7 @@ fn testNoError() {
fn testExplicitError() {
for i in 0..PDF417_TEST_WITH_EC.len() {
// for (int i = 0; i < PDF417_TEST_WITH_EC.length; i++) {
let mut received = PDF417_TEST_WITH_EC.clone();
let mut received = PDF417_TEST_WITH_EC;
received[i] = 610; //random.gen_range(0..256);// random.nextInt(256);
checkDecode(&mut received).expect("ok");
}
@@ -69,7 +69,7 @@ fn testOneError() {
let mut random = getRandom();
for i in 0..PDF417_TEST_WITH_EC.len() {
// for (int i = 0; i < PDF417_TEST_WITH_EC.length; i++) {
let mut received = PDF417_TEST_WITH_EC.clone();
let mut received = PDF417_TEST_WITH_EC;
received[i] = random.gen_range(0..256); //random.gen_range(0..256);// random.nextInt(256);
checkDecode(&mut received).expect("ok");
}
@@ -80,7 +80,7 @@ fn testMaxErrors() {
let mut random = getRandom();
for _testIterations in 0..100 {
// for (int testIterations = 0; testIterations < 100; testIterations++) { // # iterations is kind of arbitrary
let mut received = PDF417_TEST_WITH_EC.clone();
let mut received = PDF417_TEST_WITH_EC;
corrupt(&mut received, MAX_ERRORS as u32, &mut random);
checkDecode(&mut received).expect("ok");
}
@@ -88,7 +88,7 @@ fn testMaxErrors() {
#[test]
fn testTooManyErrors() {
let mut received = PDF417_TEST_WITH_EC.clone();
let mut received = PDF417_TEST_WITH_EC;
let mut random = getRandom();
corrupt(&mut received, MAX_ERRORS as u32 + 1, &mut random);
// try {

View File

@@ -38,9 +38,10 @@ impl ModulusGF {
let mut expTable = vec![0u32; modulus as usize]; //new int[modulus];
let mut logTable = vec![0u32; modulus as usize]; //new int[modulus];
let mut x = 1;
for i in 0..modulus as usize {
for table_entry in expTable.iter_mut().take(modulus as usize) {
// for i in 0..modulus as usize {
// for (int i = 0; i < modulus; i++) {
expTable[i] = x;
*table_entry = x;
x = (x * generator) % modulus;
}
for i in 0..modulus as usize - 1 {
@@ -49,18 +50,17 @@ impl ModulusGF {
}
// logTable[0] == 0 but this should never be used
let potential_self = Self {
// zero = new ModulusPoly(this, new int[]{0});
// one = new ModulusPoly(this, new int[]{1});
Self {
expTable,
logTable,
// zero: None,
// one: None,
modulus,
generator,
};
// zero = new ModulusPoly(this, new int[]{0});
// one = new ModulusPoly(this, new int[]{1});
potential_self
}
}
pub fn add(&self, a: u32, b: u32) -> u32 {
@@ -77,7 +77,7 @@ impl ModulusGF {
pub fn log(&self, a: u32) -> Result<u32, Exceptions> {
if a == 0 {
Err(Exceptions::ArithmeticException("".to_owned()))
Err(Exceptions::ArithmeticException(None))
} else {
Ok(self.logTable[a as usize])
}
@@ -85,7 +85,7 @@ impl ModulusGF {
pub fn inverse(&self, a: u32) -> Result<u32, Exceptions> {
if a == 0 {
Err(Exceptions::ArithmeticException("".to_owned()))
Err(Exceptions::ArithmeticException(None))
} else {
Ok(self.expTable[self.modulus as usize - self.logTable[a as usize] as usize - 1])
}

View File

@@ -25,18 +25,18 @@ use super::ModulusGF;
*/
#[derive(Clone, Debug)]
pub struct ModulusPoly {
field: Rc<&'static ModulusGF>,
field: &'static ModulusGF,
coefficients: Vec<u32>,
// zero: Option<Rc<ModulusPoly>>,
// one: Option<Rc<ModulusPoly>>,
}
impl ModulusPoly {
pub fn new(
field: Rc<&'static ModulusGF>,
field: &'static ModulusGF,
coefficients: Vec<u32>,
) -> Result<ModulusPoly, Exceptions> {
if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException("".to_owned()));
return Err(Exceptions::IllegalArgumentException(None));
}
let orig_coefs = coefficients.clone();
let mut coefficients = coefficients;
@@ -51,20 +51,21 @@ impl ModulusPoly {
coefficients = vec![0];
} else {
coefficients = vec![0u32; coefficientsLength - firstNonZero];
coefficients[..].copy_from_slice(&&orig_coefs[firstNonZero..]);
coefficients[..].copy_from_slice(&orig_coefs[firstNonZero..]);
// System.arraycopy(coefficients,
// firstNonZero,
// this.coefficients,
// 0,
// this.coefficients.length);
}
} else {
coefficients = coefficients;
}
// } else {
// coefficients = coefficients;
// }
Ok(ModulusPoly {
field: field.clone(),
coefficients: coefficients,
field,
coefficients,
// zero: Some(Self::getZero(field.clone())),
// one: Some(Self::getOne(field.clone())),
})
@@ -120,14 +121,14 @@ impl ModulusPoly {
.field
.add(self.field.multiply(a, result), self.coefficients[i]);
}
return result;
result
}
pub fn add(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
));
)));
}
if self.isZero() {
return Ok(other);
@@ -141,7 +142,7 @@ impl ModulusPoly {
if smallerCoefficients.len() > largerCoefficients.len() {
std::mem::swap(&mut smallerCoefficients, &mut largerCoefficients);
}
let mut sumDiff = vec![0032; largerCoefficients.len()];
let mut sumDiff = vec![0_u32; largerCoefficients.len()];
let lengthDiff = largerCoefficients.len() - smallerCoefficients.len();
// Copy high-order terms only found in higher-degree polynomial's coefficients
sumDiff[..lengthDiff].copy_from_slice(&largerCoefficients[..lengthDiff]);
@@ -155,31 +156,30 @@ impl ModulusPoly {
}
Ok(Rc::new(
ModulusPoly::new(self.field.clone(), sumDiff)
.expect("should always generate with known goods"),
ModulusPoly::new(self.field, sumDiff).expect("should always generate with known goods"),
))
}
pub fn subtract(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
));
)));
}
if other.isZero() {
return Ok(Rc::new(self.clone()));
};
self.add(other.negative().clone())
self.add(other.negative())
}
pub fn multiply(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if !(self.field == other.field) {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
));
)));
}
if self.isZero() || other.isZero() {
return Ok(Self::getZero(self.field.clone()).clone());
return Ok(Self::getZero(self.field));
}
let aCoefficients = &self.coefficients;
let aLength = aCoefficients.len();
@@ -199,77 +199,68 @@ impl ModulusPoly {
}
Ok(Rc::new(
ModulusPoly::new(self.field.clone(), product)
.expect("should always generate with known goods"),
ModulusPoly::new(self.field, product).expect("should always generate with known goods"),
))
}
pub fn negative(&self) -> Rc<ModulusPoly> {
let size = self.coefficients.len();
let mut negativeCoefficients = vec![0u32; size];
for i in 0..size {
for (i, neg_coef) in negativeCoefficients.iter_mut().enumerate().take(size) {
// for (int i = 0; i < size; i++) {
negativeCoefficients[i] = self.field.subtract(0, self.coefficients[i]);
*neg_coef = self.field.subtract(0, self.coefficients[i]);
}
Rc::new(
ModulusPoly::new(self.field.clone(), negativeCoefficients)
ModulusPoly::new(self.field, negativeCoefficients)
.expect("should always generate with known goods"),
)
}
pub fn multiplyByScaler(&self, scalar: u32) -> Rc<ModulusPoly> {
if scalar == 0 {
return Self::getZero(self.field.clone()).clone();
return Self::getZero(self.field);
}
if scalar == 1 {
return Rc::new(self.clone());
}
let size = self.coefficients.len();
let mut product = vec![0u32; size];
for i in 0..size {
for (i, prod) in product.iter_mut().enumerate().take(size) {
// for (int i = 0; i < size; i++) {
product[i] = self.field.multiply(self.coefficients[i], scalar);
*prod = self.field.multiply(self.coefficients[i], scalar);
}
Rc::new(
ModulusPoly::new(self.field.clone(), product)
.expect("should always generate with known goods"),
ModulusPoly::new(self.field, product).expect("should always generate with known goods"),
)
}
pub fn multiplyByMonomial(&self, degree: usize, coefficient: u32) -> Rc<ModulusPoly> {
if coefficient == 0 {
return Self::getZero(self.field.clone()).clone();
return Self::getZero(self.field);
}
let size = self.coefficients.len();
let mut product = vec![0u32; size + degree];
for i in 0..size {
for (i, prod) in product.iter_mut().enumerate().take(size) {
// for (int i = 0; i < size; i++) {
product[i] = self.field.multiply(self.coefficients[i], coefficient);
*prod = self.field.multiply(self.coefficients[i], coefficient);
}
Rc::new(
ModulusPoly::new(self.field.clone(), product)
.expect("should always generate with known goods"),
ModulusPoly::new(self.field, product).expect("should always generate with known goods"),
)
}
pub fn getZero(field: Rc<&'static ModulusGF>) -> Rc<ModulusPoly> {
Rc::new(
ModulusPoly::new(field.clone(), vec![0])
.expect("should always generate with known goods"),
)
pub fn getZero(field: &'static ModulusGF) -> Rc<ModulusPoly> {
Rc::new(ModulusPoly::new(field, vec![0]).expect("should always generate with known goods"))
}
pub fn getOne(field: Rc<&'static ModulusGF>) -> Rc<ModulusPoly> {
Rc::new(
ModulusPoly::new(field.clone(), vec![1])
.expect("should always generate with known goods"),
)
pub fn getOne(field: &'static ModulusGF) -> Rc<ModulusPoly> {
Rc::new(ModulusPoly::new(field, vec![1]).expect("should always generate with known goods"))
}
pub fn buildMonomial(
field: Rc<&'static ModulusGF>,
field: &'static ModulusGF,
degree: usize,
coefficient: u32,
) -> Rc<ModulusPoly> {
@@ -282,8 +273,7 @@ impl ModulusPoly {
let mut coefficients = vec![0_u32; degree + 1];
coefficients[0] = coefficient;
Rc::new(
ModulusPoly::new(field.clone(), coefficients)
.expect("should always generate with known goods"),
ModulusPoly::new(field, coefficients).expect("should always generate with known goods"),
)
}

View File

@@ -92,11 +92,11 @@ fn getDecodedCodewordValue(moduleBitCount: &[u32]) -> i32 {
fn getBitValue(moduleBitCount: &[u32]) -> i32 {
let mut result: u64 = 0;
for i in 0..moduleBitCount.len() {
for (i, mbc) in moduleBitCount.iter().enumerate() {
// for (int i = 0; i < moduleBitCount.length; i++) {
for _bit in 0..moduleBitCount[i] {
for _bit in 0..(*mbc) {
// for (int bit = 0; bit < moduleBitCount[i]; bit++) {
result = (result << 1) | (if i % 2 == 0 { 1 } else { 0 });
result = (result << 1) | u64::from(i % 2 == 0); //(if i % 2 == 0 { 1 } else { 0 });
}
}
result as i32
@@ -113,10 +113,9 @@ fn getClosestDecodedValue(moduleBitCount: &[u32]) -> i32 {
}
let mut bestMatchError = f32::MAX;
let mut bestMatch = -1_i32;
for j in 0..RATIOS_TABLE.len() {
for (j, ratioTableRow) in RATIOS_TABLE.iter().enumerate() {
// for (int j = 0; j < RATIOS_TABLE.length; j++) {
let mut error = 0.0;
let ratioTableRow = &RATIOS_TABLE[j];
for k in 0..pdf_417_common::BARS_IN_MODULE as usize {
// for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
let diff = ratioTableRow[k] - bitCountRatios[k];

View File

@@ -432,7 +432,7 @@ fn encodeDecodeWithLength(input: &str, expectedLength: u32) {
}
fn encodeDecode(input: &str) -> u32 {
return encodeDecodeWithAll(input, None, false, true);
encodeDecodeWithAll(input, None, false, true)
}
fn encodeDecodeWithAll(
@@ -451,9 +451,9 @@ fn encodeDecodeWithAll(
if decode {
let mut codewords = vec![0_u32; s.chars().count() + 1];
codewords[0] = codewords.len() as u32;
for i in 1..codewords.len() {
for (i, codeword) in codewords.iter_mut().enumerate().skip(1) {
// for (int i = 1; i < codewords.length; i++) {
codewords[i] = s.chars().nth(i - 1).unwrap() as u32;
*codeword = s.chars().nth(i - 1).unwrap() as u32;
}
performDecodeTest(&codewords, input);
}
@@ -499,14 +499,9 @@ fn performPermutationTest(chars: &[char], length: u32, expectedTotal: u32) {
}
fn performEncodeTest(c: char, expectedLengths: &[u32]) {
for i in 0..expectedLengths.len() {
// for (int i = 0; i < expectedLengths.length; i++) {
let mut sb = String::new(); //new StringBuilder();
for _j in 0..=i {
// for (int j = 0; j <= i; j++) {
sb.push(c);
}
encodeDecodeWithLength(&sb, expectedLengths[i]);
for (i, epected_length) in expectedLengths.iter().enumerate() {
let sb = vec![c; i + 1].into_iter().collect::<String>();
encodeDecodeWithLength(&sb, *epected_length);
}
}
@@ -548,17 +543,17 @@ fn generateText(
// }
total += weights.iter().sum::<f32>();
for i in 0..weights.len() {
for weight in weights.iter_mut() {
// for (int i = 0; i < weights.length; i++) {
weights[i] /= total;
*weight /= total;
}
let mut cnt = 0;
loop {
let mut maxValue = 0.0;
let mut maxIndex = 0;
for j in 0..weights.len() {
for (j, weight) in weights.iter().enumerate() {
// for (int j = 0; j < weights.length; j++) {
let value = random.next_f32() * weights[j];
let value = random.next_f32() * *weight;
if value > maxValue {
maxValue = value;
maxIndex = j;
@@ -571,7 +566,7 @@ fn generateText(
for j in 0..wordLength.ceil() as u32 {
// for (int j = 0; j < wordLength; j++) {
let mut c = chars[maxIndex];
if j == 0 && c >= 'a' && c <= 'z' && random.next_bool() {
if j == 0 && ('a'..='z').contains(&c) && random.next_bool() {
c = char::from_u32(c as u32 - 'a' as u32 + 'A' as u32).unwrap();
}
result.push(c);
@@ -581,7 +576,7 @@ fn generateText(
}
cnt += 1;
if !(result.chars().count() < (maxWidth as isize - maxWordWidth as isize) as usize) {
if result.chars().count() >= (maxWidth as isize - maxWordWidth as isize) as usize {
break;
}
} //while (result.length() < maxWidth - maxWordWidth);

View File

@@ -87,7 +87,7 @@ pub fn decode(
}
detectionRXingResult = merge(&mut leftRowIndicatorColumn, &mut rightRowIndicatorColumn)?;
if detectionRXingResult.is_none() {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
// detectionRXingResult = detectionRXingResult;
@@ -159,8 +159,8 @@ pub fn decode(
minCodewordWidth,
maxCodewordWidth,
);
if codeword.is_some() {
let codeword = codeword.unwrap();
if let Some(codeword) = codeword {
// let codeword = codeword.unwrap();
//detectionRXingResultColumn.setCodeword(imageRow, codeword);
detectionRXingResult
.getDetectionRXingResultColumnMut(barcodeColumn)
@@ -264,9 +264,13 @@ fn getBarcodeMetadata<T: DetectionRXingResultRowIndicatorColumn>(
leftRowIndicatorColumn: &mut Option<T>,
rightRowIndicatorColumn: &mut Option<T>,
) -> Option<BarcodeMetadata> {
let leftBarcodeMetadata;
if leftRowIndicatorColumn.is_none() {
let leftBarcodeMetadata = if leftRowIndicatorColumn.is_none()
|| leftRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
.is_none()
{
return if rightRowIndicatorColumn.is_none() {
None
} else {
@@ -276,51 +280,30 @@ fn getBarcodeMetadata<T: DetectionRXingResultRowIndicatorColumn>(
.getBarcodeMetadata()
};
} else {
if leftRowIndicatorColumn
leftRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
.is_none()
{
return if rightRowIndicatorColumn.is_none() {
None
} else {
rightRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
};
} else {
leftBarcodeMetadata = leftRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
}
}
};
// if leftRowIndicatorColumn.is_none() ||
// (leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()).is_none() {
// return if rightRowIndicatorColumn.is_none() {None} else {rightRowIndicatorColumn.getBarcodeMetadata()};
// }
let rightBarcodeMetadata;
if rightRowIndicatorColumn.is_none() {
return leftBarcodeMetadata;
} else {
if rightRowIndicatorColumn
let rightBarcodeMetadata = if rightRowIndicatorColumn.is_none()
|| rightRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
.is_none()
{
return leftBarcodeMetadata;
} else {
rightBarcodeMetadata = rightRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata();
}
}
{
return leftBarcodeMetadata;
} else {
rightRowIndicatorColumn
.as_mut()
.unwrap()
.getBarcodeMetadata()
};
// if rightRowIndicatorColumn.is_none() ||
// (rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()).is_none() {
// return leftBarcodeMetadata;
@@ -392,7 +375,7 @@ fn getRowIndicatorColumn<'a>(
fn adjustCodewordCount(
detectionRXingResult: &DetectionRXingResult,
barcodeMatrix: &mut Vec<Vec<BarcodeValue>>,
barcodeMatrix: &mut [Vec<BarcodeValue>],
) -> Result<(), Exceptions> {
let barcodeMatrix01 = &mut barcodeMatrix[0][1];
let numberOfCodewords = barcodeMatrix01.getValue();
@@ -400,20 +383,16 @@ fn adjustCodewordCount(
* detectionRXingResult.getBarcodeRowCount() as isize
- getNumberOfECCodeWords(detectionRXingResult.getBarcodeECLevel()) as isize)
as u32;
if numberOfCodewords.len() == 0 {
if calculatedNumberOfCodewords < 1
|| calculatedNumberOfCodewords > pdf_417_common::MAX_CODEWORDS_IN_BARCODE
{
return Err(Exceptions::NotFoundException("".to_owned()));
if numberOfCodewords.is_empty() {
if !(1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords) {
return Err(Exceptions::NotFoundException(None));
}
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
} else if numberOfCodewords[0] != calculatedNumberOfCodewords {
if calculatedNumberOfCodewords >= 1
&& calculatedNumberOfCodewords <= pdf_417_common::MAX_CODEWORDS_IN_BARCODE
{
// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
}
} else if numberOfCodewords[0] != calculatedNumberOfCodewords
&& (1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords)
{
// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
}
Ok(())
}
@@ -438,7 +417,7 @@ fn createDecoderRXingResult(
let values = barcodeMatrix[row as usize][column + 1].getValue();
let codewordIndex =
row as usize * detectionRXingResult.getBarcodeColumnCount() + column;
if values.len() == 0 {
if values.is_empty() {
erasures.push(codewordIndex as u32);
} else if values.len() == 1 {
codewords[codewordIndex] = values[0];
@@ -483,7 +462,7 @@ fn createDecoderRXingResultFromAmbiguousValues(
codewords: &mut [u32],
erasureArray: &mut [u32],
ambiguousIndexes: &mut [u32],
ambiguousIndexValues: &Vec<Vec<u32>>,
ambiguousIndexValues: &[Vec<u32>],
) -> Result<DecoderRXingResult, Exceptions> {
let mut ambiguousIndexCount = vec![0; ambiguousIndexes.len()];
@@ -503,8 +482,8 @@ fn createDecoderRXingResultFromAmbiguousValues(
// } catch (ChecksumException ignored) {
// //
// }
if ambiguousIndexCount.len() == 0 {
return Err(Exceptions::ChecksumException("".to_owned()));
if ambiguousIndexCount.is_empty() {
return Err(Exceptions::ChecksumException(None));
}
for i in 0..ambiguousIndexCount.len() {
// for (int i = 0; i < ambiguousIndexCount.length; i++) {
@@ -514,14 +493,14 @@ fn createDecoderRXingResultFromAmbiguousValues(
} else {
ambiguousIndexCount[i] = 0;
if i == ambiguousIndexCount.len() - 1 {
return Err(Exceptions::ChecksumException("".to_owned()));
return Err(Exceptions::ChecksumException(None));
}
}
}
tries -= 1;
}
Err(Exceptions::ChecksumException("".to_owned()))
Err(Exceptions::ChecksumException(None))
}
fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec<Vec<BarcodeValue>> {
@@ -544,19 +523,25 @@ fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec<V
for detectionRXingResultColumn in detectionRXingResult.getDetectionRXingResultColumns() {
// for (DetectionRXingResultColumn detectionRXingResultColumn : detectionRXingResult.getDetectionRXingResultColumns()) {
if detectionRXingResultColumn.is_some() {
for codeword in detectionRXingResultColumn.as_ref().unwrap().getCodewords() {
for codeword in detectionRXingResultColumn
.as_ref()
.unwrap()
.getCodewords()
.iter()
.flatten()
{
// for (Codeword codeword : detectionRXingResultColumn.getCodewords()) {
if let Some(codeword) = codeword {
// if codeword.is_some() {
let rowNumber = codeword.getRowNumber();
if rowNumber >= 0 {
if rowNumber as usize >= barcodeMatrix.len() {
// We have more rows than the barcode metadata allows for, ignore them.
continue;
}
barcodeMatrix[rowNumber as usize][column].setValue(codeword.getValue());
// if let Some(codeword) = codeword {
// if codeword.is_some() {
let rowNumber = codeword.getRowNumber();
if rowNumber >= 0 {
if rowNumber as usize >= barcodeMatrix.len() {
// We have more rows than the barcode metadata allows for, ignore them.
continue;
}
barcodeMatrix[rowNumber as usize][column].setValue(codeword.getValue());
}
// }
}
}
column += 1;
@@ -580,7 +565,7 @@ fn getStartColumn(
let mut codeword = &None;
if isValidBarcodeColumn(detectionRXingResult, (barcodeColumn - offset) as usize) {
codeword = detectionRXingResult
.getDetectionRXingResultColumn((barcodeColumn as isize - offset) as usize)
.getDetectionRXingResultColumn((barcodeColumn - offset) as usize)
.as_ref()
.unwrap()
.getCodeword(imageRow);
@@ -688,9 +673,7 @@ fn detectCodeword(
startColumn,
imageRow,
);
if moduleBitCount.is_none() {
return None;
}
moduleBitCount?;
let mut moduleBitCount = moduleBitCount.unwrap();
let endColumn;
@@ -811,7 +794,7 @@ fn adjustCodewordStartColumn(
correctedStartColumn < maxColumn
}) && leftToRight == image.get(correctedStartColumn, imageRow)
{
if (codewordStartColumn as i64 - correctedStartColumn as i64).abs() as u32
if (codewordStartColumn as i64 - correctedStartColumn as i64).unsigned_abs() as u32
> CODEWORD_SKEW_SIZE
{
return codewordStartColumn;
@@ -824,12 +807,12 @@ fn adjustCodewordStartColumn(
increment = -increment;
leftToRight = !leftToRight;
}
return correctedStartColumn;
correctedStartColumn
}
fn checkCodewordSkew(codewordSize: u32, minCodewordWidth: u32, maxCodewordWidth: u32) -> bool {
return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize
&& codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE;
minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize
&& codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE
}
fn decodeCodewords(
@@ -838,7 +821,7 @@ fn decodeCodewords(
erasures: &mut [u32],
) -> Result<DecoderRXingResult, Exceptions> {
if codewords.is_empty() {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let numECCodewords = 1 << (ecLevel + 1);
@@ -873,7 +856,7 @@ fn correctErrors(
|| numECCodewords > MAX_EC_CODEWORDS
{
// Too many errors or EC Codewords is corrupted
return Err(Exceptions::ChecksumException("".to_owned()));
return Err(Exceptions::ChecksumException(None));
}
ec::error_correction::decode(codewords, numECCodewords, erasures)
}
@@ -885,21 +868,21 @@ fn verifyCodewordCount(codewords: &mut [u32], numECCodewords: u32) -> Result<(),
if codewords.len() < 4 {
// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
let numberOfCodewords = codewords[0];
if numberOfCodewords > codewords.len() as u32 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
if numberOfCodewords == 0 {
// Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if numECCodewords < codewords.len() as u32 {
codewords[0] = codewords.len() as u32 - numECCodewords;
} else {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
}
Ok(())