updated cargo fmt

This commit is contained in:
Henry Schimke
2023-10-28 11:04:14 -05:00
parent 4c9ec95d00
commit 5ea03cc066
24 changed files with 122 additions and 64 deletions

View File

@@ -49,8 +49,10 @@ pub const WORD_SIZE: [u32; 33] = [
* @return Aztec symbol matrix with metadata * @return Aztec symbol matrix with metadata
*/ */
pub fn encode_simple(data: &str) -> Result<AztecCode> { pub fn encode_simple(data: &str) -> Result<AztecCode> {
let Ok(bytes) =CharacterSet::ISO8859_1.encode_replace(data) else { let Ok(bytes) = CharacterSet::ISO8859_1.encode_replace(data) else {
return Err(Exceptions::illegal_argument_with(format!("'{data}' cannot be encoded as ISO_8859_1"))); return Err(Exceptions::illegal_argument_with(format!(
"'{data}' cannot be encoded as ISO_8859_1"
)));
}; };
encode_bytes_simple(&bytes) encode_bytes_simple(&bytes)
} }

View File

@@ -86,11 +86,9 @@ impl State {
)); ));
// 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 Ok(eci_digits) = CharacterSet::ISO8859_1 let Ok(eci_digits) = CharacterSet::ISO8859_1.encode(&format!("{eci}")) else {
.encode(&format!("{eci}")) return Err(Exceptions::ILLEGAL_ARGUMENT);
else { };
return Err(Exceptions::ILLEGAL_ARGUMENT)
};
// let eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1); // let eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1);
token.add(eci_digits.len() as i32, 3); // 1-6: number of ECI digits token.add(eci_digits.len() as i32, 3); // 1-6: number of ECI digits
for eci_digit in &eci_digits { for eci_digit in &eci_digits {

View File

@@ -29,7 +29,7 @@ impl BitMatrix {
} }
pub fn getTopLeftOnBitWithPosition(&self, left: &mut u32, top: &mut u32) -> bool { pub fn getTopLeftOnBitWithPosition(&self, left: &mut u32, top: &mut u32) -> bool {
let Some(Point{x,y}) = self.getTopLeftOnBit() else { let Some(Point { x, y }) = self.getTopLeftOnBit() else {
return false; return false;
}; };
*left = x as u32; *left = x as u32;
@@ -39,7 +39,7 @@ impl BitMatrix {
} }
pub fn getBottomRightOnBitWithPosition(&self, right: &mut u32, bottom: &mut u32) -> bool { pub fn getBottomRightOnBitWithPosition(&self, right: &mut u32, bottom: &mut u32) -> bool {
let Some(Point{x,y}) = self.getBottomRightOnBit() else { let Some(Point { x, y }) = self.getBottomRightOnBit() else {
return false; return false;
}; };
*right = x as u32; *right = x as u32;

View File

@@ -130,8 +130,12 @@ impl RegressionLineTrait for DMRegressionLine {
} }
fn isHighRes(&self) -> bool { fn isHighRes(&self) -> bool {
let Some(mut min) = self.points.first().copied() else { return false }; let Some(mut min) = self.points.first().copied() else {
let Some(mut max) = self.points.first().copied() else { return false }; return false;
};
let Some(mut max) = self.points.first().copied() else {
return false;
};
for p in &self.points { for p in &self.points {
min.x = f32::min(min.x, p.x); min.x = f32::min(min.x, p.x);
min.y = f32::min(min.y, p.y); min.y = f32::min(min.y, p.y);

View File

@@ -130,8 +130,12 @@ impl RegressionLineTrait for RegressionLine {
} }
fn isHighRes(&self) -> bool { fn isHighRes(&self) -> bool {
let Some(mut min) = self.points.first().copied() else { return false }; let Some(mut min) = self.points.first().copied() else {
let Some(mut max) = self.points.first().copied() else { return false }; return false;
};
let Some(mut max) = self.points.first().copied() else {
return false;
};
for p in &self.points { for p in &self.points {
min.x = f32::min(min.x, p.x); min.x = f32::min(min.x, p.x);
min.y = f32::min(min.y, p.y); min.y = f32::min(min.y, p.y);

View File

@@ -19,8 +19,12 @@ pub struct OtsuLevelBinarizer<LS: LuminanceSource> {
impl<LS: LuminanceSource> OtsuLevelBinarizer<LS> { impl<LS: LuminanceSource> OtsuLevelBinarizer<LS> {
fn generate_threshold_matrix<LS2: LuminanceSource>(source: &LS2) -> Result<BitMatrix> { fn generate_threshold_matrix<LS2: LuminanceSource>(source: &LS2) -> Result<BitMatrix> {
let image_buffer = { let image_buffer = {
let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.get_width() as u32, source.get_height() as u32, source.get_matrix()) else { let Some(buff): Option<ImageBuffer<Luma<u8>, Vec<u8>>> = ImageBuffer::from_vec(
return Err(Exceptions::ILLEGAL_ARGUMENT) source.get_width() as u32,
source.get_height() as u32,
source.get_matrix(),
) else {
return Err(Exceptions::ILLEGAL_ARGUMENT);
}; };
buff buff
}; };

View File

@@ -78,7 +78,7 @@ impl ReedSolomonDecoder {
return Ok(0); return Ok(0);
} }
let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else { let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else {
return Err(Exceptions::REED_SOLOMON); return Err(Exceptions::REED_SOLOMON);
}; };
let sigmaOmega = self.runEuclideanAlgorithm( let sigmaOmega = self.runEuclideanAlgorithm(
&GenericGF::buildMonomial(self.field, twoS as usize, 1), &GenericGF::buildMonomial(self.field, twoS as usize, 1),

View File

@@ -181,11 +181,11 @@ impl DataMatrixReader {
*/ */
fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix> { fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix> {
let Some(leftTopBlack) = image.getTopLeftOnBit() else { let Some(leftTopBlack) = image.getTopLeftOnBit() else {
return Err(Exceptions::NOT_FOUND) return Err(Exceptions::NOT_FOUND);
}; };
let Some(rightBottomBlack) = image.getBottomRightOnBit()else { let Some(rightBottomBlack) = image.getBottomRightOnBit() else {
return Err(Exceptions::NOT_FOUND) return Err(Exceptions::NOT_FOUND);
}; };
let moduleSize = Self::moduleSize(leftTopBlack, image)?; let moduleSize = Self::moduleSize(leftTopBlack, image)?;

View File

@@ -119,9 +119,10 @@ impl Writer for DataMatrixWriter {
let hasEncodingHint = hints.contains_key(&EncodeHintType::CHARACTER_SET); let hasEncodingHint = hints.contains_key(&EncodeHintType::CHARACTER_SET);
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)
return Err(Exceptions::illegal_argument_with("charset does not exist")) else {
}; return Err(Exceptions::illegal_argument_with("charset does not exist"));
};
charset = CharacterSet::get_character_set_by_name(char_set_name); charset = CharacterSet::get_character_set_by_name(char_set_name);
//encoding::label::encoding_from_whatwg_label(char_set_name); //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());
@@ -154,9 +155,16 @@ 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(
return Err(Exceptions::not_found_with("symbol info is bad")) encoded.chars().count() as u32,
}; *shape,
&minSize,
&maxSize,
true,
)?
else {
return Err(Exceptions::not_found_with("symbol info is bad"));
};
//2. step: ECC generation //2. step: ECC generation
let codewords = error_correction::encodeECC200(&encoded, symbolInfo)?; let codewords = error_correction::encodeECC200(&encoded, symbolInfo)?;

View File

@@ -1,10 +1,10 @@
mod cpp_new_detector; mod cpp_new_detector;
use crate::common::cpp_essentials::bitmatrix_cursor_trait::*; use crate::common::cpp_essentials::bitmatrix_cursor_trait::*;
use crate::common::cpp_essentials::dm_regression_line::*; use crate::common::cpp_essentials::dm_regression_line::*;
use crate::common::cpp_essentials::edge_tracer::*; use crate::common::cpp_essentials::edge_tracer::*;
use crate::common::cpp_essentials::util; use crate::common::cpp_essentials::util;
pub use cpp_new_detector::detect; pub use cpp_new_detector::detect;

View File

@@ -359,9 +359,7 @@ fn lookAheadTestIntern(msg: &str, startpos: u32, currentMode: u32) -> usize {
return C40_ENCODATION; return C40_ENCODATION;
} }
let Some(c) = msg let Some(c) = msg.chars().nth((startpos + charsProcessed) as usize) else {
.chars()
.nth((startpos + charsProcessed) as usize) else {
break 0; break 0;
}; };
charsProcessed += 1; charsProcessed += 1;

View File

@@ -116,7 +116,9 @@ pub fn detect_in_file_with_hints(
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<RXingResult> { ) -> Result<RXingResult> {
let Ok(img) = image::open(file_name) else { let Ok(img) = image::open(file_name) else {
return Err(Exceptions::illegal_argument_with(format!("file '{file_name}' not found or cannot be opened"))); return Err(Exceptions::illegal_argument_with(format!(
"file '{file_name}' not found or cannot be opened"
)));
}; };
let mut multi_format_reader = MultiFormatReader::default(); let mut multi_format_reader = MultiFormatReader::default();

View File

@@ -183,7 +183,9 @@ fn getMessage(bytes: &[u8], start: u32, len: u32) -> String {
// for i in start..(start+len) { // for i in start..(start+len) {
// for (int i = start; i < start + len; i++) { // for (int i = start; i < start + len; i++) {
let mut set_graphemes = SETS[set].graphemes(true); let mut set_graphemes = SETS[set].graphemes(true);
let Some(c) = set_graphemes.nth(bytes[i as usize] as usize) else { break; }; let Some(c) = set_graphemes.nth(bytes[i as usize] as usize) else {
break;
};
match c { match c {
LATCHA => { LATCHA => {
set = 0; set = 0;

View File

@@ -152,8 +152,12 @@ impl Circle<'_> {
*length_set = (length, rotation, points); *length_set = (length, rotation, points);
} }
lengths.sort_by_key(|e| e.0); lengths.sort_by_key(|e| e.0);
let Some(major_axis) = lengths.last() else {return (false, PointU::default(),0,0,0)}; let Some(major_axis) = lengths.last() else {
let Some(minor_axis) = lengths.first() else {return (false, PointU::default(),0,0,0)}; return (false, PointU::default(), 0, 0, 0);
};
let Some(minor_axis) = lengths.first() else {
return (false, PointU::default(), 0, 0, 0);
};
// // find foci // // find foci
let linear_eccentricity = ((major_axis.0 / 2).pow(2) - (minor_axis.0 / 2).pow(2)).sqrt(); let linear_eccentricity = ((major_axis.0 / 2).pow(2) - (minor_axis.0 / 2).pow(2)).sqrt();
@@ -305,7 +309,7 @@ impl Circle<'_> {
pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionResult> { pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionResult> {
// find concentric circles // find concentric circles
let Some( mut circles) = find_concentric_circles(image) else { let Some(mut circles) = find_concentric_circles(image) else {
return Err(Exceptions::NOT_FOUND); return Err(Exceptions::NOT_FOUND);
}; };
@@ -328,8 +332,8 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
let Ok(symbol_box) = box_symbol(image, circle) else { let Ok(symbol_box) = box_symbol(image, circle) else {
if try_harder { if try_harder {
continue; continue;
}else { } else {
return Err(Exceptions::NOT_FOUND) return Err(Exceptions::NOT_FOUND);
} }
}; };
let grid_sampler = DefaultGridSampler; let grid_sampler = DefaultGridSampler;
@@ -350,16 +354,17 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
); );
let src = Quadrilateral::new(tl, tr, br, bl); let src = Quadrilateral::new(tl, tr, br, bl);
let Ok((bits,_)) = grid_sampler.sample_grid_detailed( let Ok((bits, _)) = grid_sampler.sample_grid_detailed(
image, image,
target_width.round() as u32, target_width.round() as u32,
target_height.round() as u32, target_height.round() as u32,
dst, src dst,
src,
) else { ) else {
if try_harder { if try_harder {
continue; continue;
}else { } else {
return Err(Exceptions::NOT_FOUND) return Err(Exceptions::NOT_FOUND);
} }
}; };
return Ok(MaxicodeDetectionResult { return Ok(MaxicodeDetectionResult {

View File

@@ -152,7 +152,7 @@ impl<'a> MultiFinderPatternFinder<'_> {
for i3 in (i2 + 1)..size { for i3 in (i2 + 1)..size {
// for (int i3 = i2 + 1; i3 < size; i3++) { // for (int i3 = i2 + 1; i3 < size; i3++) {
let Some( p3) = possibleCenters.get(i3) else { let Some(p3) = possibleCenters.get(i3) else {
continue; continue;
}; };

View File

@@ -108,7 +108,11 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32> {
// Check for forced code set hint. // Check for forced code set hint.
let mut forcedCodeSet = -1_i32; let mut forcedCodeSet = -1_i32;
if hints.contains_key(&EncodeHintType::FORCE_CODE_SET) { if hints.contains_key(&EncodeHintType::FORCE_CODE_SET) {
let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) = hints.get(&EncodeHintType::FORCE_CODE_SET) else { return Err(Exceptions::ILLEGAL_STATE) }; let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) =
hints.get(&EncodeHintType::FORCE_CODE_SET)
else {
return Err(Exceptions::ILLEGAL_STATE);
};
match codeSetHint.as_str() { match codeSetHint.as_str() {
"A" => forcedCodeSet = CODE_CODE_A as i32, "A" => forcedCodeSet = CODE_CODE_A as i32,
"B" => forcedCodeSet = CODE_CODE_B as i32, "B" => forcedCodeSet = CODE_CODE_B as i32,

View File

@@ -71,8 +71,13 @@ impl OneDimensionalCodeWriter for Code39Writer {
pos += Self::appendPattern(&mut result, pos as usize, &narrowWhite, false); pos += Self::appendPattern(&mut result, pos as usize, &narrowWhite, false);
//append next character to byte matrix //append next character to byte matrix
for i in 0..length { for i in 0..length {
let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) else { let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(
continue; contents
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) else {
continue;
}; };
Self::toIntArray( Self::toIntArray(
Code39Reader::CHARACTER_ENCODINGS[indexInString], Code39Reader::CHARACTER_ENCODINGS[indexInString],

View File

@@ -49,7 +49,14 @@ impl OneDimensionalCodeWriter for Code93Writer {
for i in 0..length { for i in 0..length {
// for (int i = 0; i < length; i++) { // for (int i = 0; i < length; i++) {
let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) else {panic!("alphabet")}; let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(
contents
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) else {
panic!("alphabet")
};
pos += Self::appendPattern( pos += Self::appendPattern(
&mut result, &mut result,
pos, pos,
@@ -132,7 +139,11 @@ impl Code93Writer {
for i in (0..contents.chars().count()).rev() { for i in (0..contents.chars().count()).rev() {
// for (int i = contents.length() - 1; i >= 0; i--) { // for (int i = contents.length() - 1; i >= 0; i--) {
let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).unwrap()) else {panic!("not in the alphabet");}; let Some(indexInString) =
Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).unwrap())
else {
panic!("not in the alphabet");
};
total += indexInString as u32 * weight; total += indexInString as u32 * weight;
weight += 1; weight += 1;
if weight > maxWeight { if weight > maxWeight {

View File

@@ -105,7 +105,7 @@ pub trait OneDReader: Reader {
} }
} }
let Ok(mut result) = self.decode_row(row_number as u32, &row, &hints) else { let Ok(mut result) = self.decode_row(row_number as u32, &row, &hints) else {
continue continue;
}; };
// We found our barcode // We found our barcode
if attempt == 1 { if attempt == 1 {

View File

@@ -87,8 +87,10 @@ fn assertCorrectImage2result(fileName: &str, expected: ExpandedProductParsedRXin
theRXingResult.getBarcodeFormat() theRXingResult.getBarcodeFormat()
); );
let ParsedClientResult::ExpandedProductResult(result) = crate::client::result::parseRXingResult(&theRXingResult) else { let ParsedClientResult::ExpandedProductResult(result) =
panic!("incorrect result type found"); crate::client::result::parseRXingResult(&theRXingResult)
else {
panic!("incorrect result type found");
}; };
assert_eq!(expected, result); assert_eq!(expected, result);

View File

@@ -267,7 +267,7 @@ pub fn decodeMacroBlock(
MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM => { MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM => {
let mut checksum = ECIStringBuilder::default(); let mut checksum = ECIStringBuilder::default();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?;
let Ok(parsed_checksum ) = checksum.to_string().parse() else { let Ok(parsed_checksum) = checksum.to_string().parse() else {
return Err(Exceptions::FORMAT); return Err(Exceptions::FORMAT);
}; };
resultMetadata.setChecksum(parsed_checksum); resultMetadata.setChecksum(parsed_checksum);
@@ -275,7 +275,7 @@ pub fn decodeMacroBlock(
MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE => { MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE => {
let mut fileSize = ECIStringBuilder::default(); let mut fileSize = ECIStringBuilder::default();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?;
let Ok(parsed_file_size)= fileSize.to_string().parse() else { let Ok(parsed_file_size) = fileSize.to_string().parse() else {
return Err(Exceptions::FORMAT); return Err(Exceptions::FORMAT);
}; };
resultMetadata.setFileSize(parsed_file_size); resultMetadata.setFileSize(parsed_file_size);

View File

@@ -392,12 +392,12 @@ pub fn DecodeBitStream(
pub fn Decode(bits: &BitMatrix) -> Result<DecoderResult<bool>> { pub fn Decode(bits: &BitMatrix) -> Result<DecoderResult<bool>> {
let Ok(pversion) = ReadVersion(bits) else { let Ok(pversion) = ReadVersion(bits) else {
return Err(Exceptions::format_with("Invalid version")) return Err(Exceptions::format_with("Invalid version"));
}; };
let version = pversion; let version = pversion;
let Ok(formatInfo) = ReadFormatInformation(bits, version.isMicroQRCode()) else { let Ok(formatInfo) = ReadFormatInformation(bits, version.isMicroQRCode()) else {
return Err(Exceptions::format_with("Invalid format information")) return Err(Exceptions::format_with("Invalid format information"));
}; };
// Read codewords // Read codewords

View File

@@ -717,7 +717,7 @@ impl<'a> FinderPatternFinder<'_> {
let minModuleSize = fpi.getEstimatedModuleSize(); let minModuleSize = fpi.getEstimatedModuleSize();
for j in (i + 1)..(self.possibleCenters.len() - 1) { for j in (i + 1)..(self.possibleCenters.len() - 1) {
let Some(fpj) = self.possibleCenters.get(j) else { let Some(fpj) = self.possibleCenters.get(j) else {
return Err(Exceptions::NOT_FOUND); return Err(Exceptions::NOT_FOUND);
}; };
let squares0 = Self::squaredDistance(fpi, fpj); let squares0 = Self::squaredDistance(fpi, fpj);

View File

@@ -52,10 +52,15 @@ impl SVGLuminanceSource {
pub fn new(svg_data: &[u8]) -> Result<Self> { pub fn new(svg_data: &[u8]) -> Result<Self> {
// Load the SVG file // Load the SVG file
let Ok(tree) = resvg::usvg::Tree::from_data(svg_data, &Options::default()) else { let Ok(tree) = resvg::usvg::Tree::from_data(svg_data, &Options::default()) else {
return Err(Exceptions::format_with(format!("could not parse svg data: {}", "err"))); return Err(Exceptions::format_with(format!(
"could not parse svg data: {}",
"err"
)));
}; };
let Some(mut pixmap) = resvg::tiny_skia::Pixmap::new(tree.size.width() as u32, tree.size.height() as u32) else { let Some(mut pixmap) =
resvg::tiny_skia::Pixmap::new(tree.size.width() as u32, tree.size.height() as u32)
else {
return Err(Exceptions::format_with("could not create pixmap")); return Err(Exceptions::format_with("could not create pixmap"));
}; };
@@ -63,9 +68,13 @@ impl SVGLuminanceSource {
tree_resvg.render(resvg::tiny_skia::Transform::default(), &mut pixmap.as_mut()); tree_resvg.render(resvg::tiny_skia::Transform::default(), &mut pixmap.as_mut());
let Some(buffer) = RgbaImage::from_raw(tree.size.width() as u32, tree.size.height() as u32, pixmap.data().to_vec()) else { let Some(buffer) = RgbaImage::from_raw(
return Err(Exceptions::format_with("could not create image buffer")); tree.size.width() as u32,
}; tree.size.height() as u32,
pixmap.data().to_vec(),
) else {
return Err(Exceptions::format_with("could not create image buffer"));
};
// let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else { // let Ok(image) = image::load_from_memory_with_format(pixmap.data(), image::ImageFormat::Bmp) else {
// return Err(Exceptions::format("could not generate image")); // return Err(Exceptions::format("could not generate image"));