Update macro and cargo fmt

This commit is contained in:
Steve Cook
2023-03-01 13:43:21 -05:00
parent 51fcc98b34
commit b561bd77c3
19 changed files with 101 additions and 64 deletions

View File

@@ -70,7 +70,7 @@ fn impl_one_d_reader_macro(ast: &syn::DeriveInput) -> TokenStream {
Ok(result) Ok(result)
} else { } else {
return Err(Exceptions::NotFoundException(None)) return Err(Exceptions::NOT_FOUND)
} }
} }
} }
@@ -143,23 +143,23 @@ fn impl_one_d_writer_macro(ast: &syn::DeriveInput) -> TokenStream {
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::illegal_argument_with(
Some("Found empty contents".to_owned()), "Found empty contents"
)); ));
} }
if width < 0 || height < 0 { if width < 0 || height < 0 {
return Err(Exceptions::IllegalArgumentException(Some(format!( return Err(Exceptions::illegal_argument_with(format!(
"Negative size is not allowed. Input: {}x{}", "Negative size is not allowed. Input: {}x{}",
width, height width, height
)))); )));
} }
if let Some(supportedFormats) = self.getSupportedWriteFormats() { if let Some(supportedFormats) = self.getSupportedWriteFormats() {
if !supportedFormats.contains(format) { if !supportedFormats.contains(format) {
return Err(Exceptions::IllegalArgumentException(Some(format!( return Err(Exceptions::illegal_argument_with(format!(
"Can only encode {:?}, but got {:?}", "Can only encode {:?}, but got {:?}",
supportedFormats, format supportedFormats, format
)))); )));
} }
} }

View File

@@ -182,10 +182,18 @@ impl CalendarParsedRXingResult {
}; };
} }
// The when string can be local time, or UTC if it ends with a Z // The when string can be local time, or UTC if it ends with a Z
if when.len() == 16 && when.chars().nth(15).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == 'Z' { if when.len() == 16
&& when
.chars()
.nth(15)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
== '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::parse_with(format!("couldn't parse string: {e}"))), Err(e) => Err(Exceptions::parse_with(format!(
"couldn't parse string: {e}"
))),
}; };
} }
// Try once more, with weird tz formatting // Try once more, with weird tz formatting
@@ -202,7 +210,9 @@ impl CalendarParsedRXingResult {
}; };
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::parse_with(format!("couldn't parse string: {e}"))), Err(e) => Err(Exceptions::parse_with(format!(
"couldn't parse string: {e}"
))),
}; };
} }

View File

@@ -300,7 +300,9 @@ pub fn urlDecode(encoded: &str) -> Result<String> {
if let Ok(decoded) = decode(encoded) { if let Ok(decoded) = decode(encoded) {
Ok(decoded.to_string()) Ok(decoded.to_string())
} else { } else {
Err(Exceptions::illegal_state_with("UnsupportedEncodingException")) Err(Exceptions::illegal_state_with(
"UnsupportedEncodingException",
))
} }
} }

View File

@@ -152,7 +152,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::illegal_argument_with("row lengths do not match")); return Err(Exceptions::illegal_argument_with(
"row lengths do not match",
));
} }
rowStartPos = bitsPos; rowStartPos = bitsPos;
nRows += 1; nRows += 1;
@@ -181,7 +183,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::illegal_argument_with("row lengths do not match")); return Err(Exceptions::illegal_argument_with(
"row lengths do not match",
));
} }
nRows += 1; nRows += 1;
} }

View File

@@ -74,7 +74,9 @@ impl ReedSolomonEncoder {
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<()> { pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<()> {
if ec_bytes == 0 { if ec_bytes == 0 {
return Err(Exceptions::illegal_argument_with("No error correction bytes")); return Err(Exceptions::illegal_argument_with(
"No error correction bytes",
));
} }
let data_bytes = to_encode.len() - ec_bytes; let data_bytes = to_encode.len() - ec_bytes;
if data_bytes == 0 { if data_bytes == 0 {

View File

@@ -79,7 +79,8 @@ impl Encoder for Base256Encoder {
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
buffer.insert( buffer.insert(
ci_pos, ci_pos,
char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, char::from_u32(dataCount as u32 % 250)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
); );
} else { } else {
return Err(Exceptions::illegal_state_with(format!( return Err(Exceptions::illegal_state_with(format!(
@@ -92,7 +93,10 @@ impl Encoder for Base256Encoder {
// for (int i = 0, c = buffer.length(); i < c; i++) { // for (int i = 0, c = buffer.length(); i < c; i++) {
context.writeCodeword( context.writeCodeword(
Self::randomize255State( Self::randomize255State(
buffer.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, buffer
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
context.getCodewordCount() as u32 + 1, context.getCodewordCount() as u32 + 1,
) )
.ok_or(Exceptions::PARSE)? as u8, .ok_or(Exceptions::PARSE)? as u8,

View File

@@ -183,9 +183,7 @@ impl C40Encoder {
context: &mut EncoderContext, context: &mut EncoderContext,
buffer: &mut String, buffer: &mut String,
) -> Result<()> { ) -> Result<()> {
context.writeCodewords( context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::FORMAT)?);
&Self::encodeToCodewords(buffer).ok_or(Exceptions::FORMAT)?,
);
buffer.replace_range(0..3, ""); buffer.replace_range(0..3, "");
// buffer.delete(0, 3); // buffer.delete(0, 3);
Ok(()) Ok(())

View File

@@ -153,9 +153,8 @@ pub fn detect_multiple_in_file_with_hints(
file_name: &str, file_name: &str,
hints: &mut DecodingHintDictionary, hints: &mut DecodingHintDictionary,
) -> Result<Vec<RXingResult>> { ) -> Result<Vec<RXingResult>> {
let img = image::open(file_name).map_err(|e| { let img = image::open(file_name)
Exceptions::runtime_with(format!("couldn't read {file_name}: {e}")) .map_err(|e| Exceptions::runtime_with(format!("couldn't read {file_name}: {e}")))?;
})?;
let multi_format_reader = MultiFormatReader::default(); let multi_format_reader = MultiFormatReader::default();
let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader);

View File

@@ -375,8 +375,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
}; };
return Ok(MaxicodeDetectionResult { return Ok(MaxicodeDetectionResult {
bits, bits,
points: symbol_box points: symbol_box.0.to_vec(),
.0.to_vec(),
rotation: symbol_box.1, rotation: symbol_box.1,
}); });
} }
@@ -1038,9 +1037,7 @@ fn compare_circle(a: &Circle, b: &Circle) -> std::cmp::Ordering {
/// Read appropriate bits from a bitmatrix for the maxicode decoder /// Read appropriate bits from a bitmatrix for the maxicode decoder
pub fn read_bits(image: &BitMatrix) -> Result<BitMatrix> { pub fn read_bits(image: &BitMatrix) -> Result<BitMatrix> {
let enclosingRectangle = image let enclosingRectangle = image.getEnclosingRectangle().ok_or(Exceptions::NOT_FOUND)?;
.getEnclosingRectangle()
.ok_or(Exceptions::NOT_FOUND)?;
let left = enclosingRectangle[0]; let left = enclosingRectangle[0];
let top = enclosingRectangle[1]; let top = enclosingRectangle[1];

View File

@@ -113,7 +113,8 @@ impl OneDReader for CodaBarReader {
.decodeRowRXingResult .decodeRowRXingResult
.chars() .chars()
.nth(i) .nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize] .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
as usize]
.to_string(), .to_string(),
); );
} }

View File

@@ -590,7 +590,8 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
contents contents
.chars() .chars()
.nth(i) .nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as isize .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
as isize
- ' ' as isize - ' ' as isize
} }
}; };

View File

@@ -322,7 +322,10 @@ impl Code39Reader {
while i < length { while i < length {
// 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 c = encoded.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let c = encoded
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
if c == '+' || c == '$' || c == '%' || c == '/' { if c == '+' || c == '$' || c == '%' || c == '/' {
let next = encoded let next = encoded
.chars() .chars()

View File

@@ -234,7 +234,10 @@ impl Code93Reader {
while i < length { while i < length {
// 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 c = encoded.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let c = encoded
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
if ('a'..='d').contains(&c) { if ('a'..='d').contains(&c) {
if i >= length - 1 { if i >= length - 1 {
return Err(Exceptions::FORMAT); return Err(Exceptions::FORMAT);
@@ -334,7 +337,12 @@ impl Code93Reader {
for i in (0..checkPosition).rev() { for i in (0..checkPosition).rev() {
total += weight total += weight
* Self::ALPHABET_STRING * Self::ALPHABET_STRING
.find(result.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?) .find(
result
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
)
.map_or_else(|| -1_i32, |v| v as i32); .map_or_else(|| -1_i32, |v| v as i32);
weight += 1; weight += 1;
if weight > weightMax as i32 { if weight > weightMax as i32 {

View File

@@ -528,8 +528,8 @@ impl RSSExpandedReader {
// Not private for unit testing // Not private for unit testing
pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result<RXingResult> { pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result<RXingResult> {
let binary = bit_array_builder::buildBitArray(&pairs.to_vec()) let binary =
.ok_or(Exceptions::ILLEGAL_STATE)?; bit_array_builder::buildBitArray(&pairs.to_vec()).ok_or(Exceptions::ILLEGAL_STATE)?;
let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?; let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?;
let resultingString = decoder.parseInformation()?; let resultingString = decoder.parseInformation()?;
@@ -692,7 +692,9 @@ impl RSSExpandedReader {
} else if previousPairs.is_empty() { } else if previousPairs.is_empty() {
rowOffset = 0; rowOffset = 0;
} else { } else {
let lastPair = previousPairs.last().ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?; let lastPair = previousPairs
.last()
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
rowOffset = lastPair rowOffset = lastPair
.getFinderPattern() .getFinderPattern()
.as_ref() .as_ref()

View File

@@ -66,9 +66,7 @@ impl UPCEANReader for UPCEReader {
} }
fn checkChecksum(&self, s: &str) -> Result<bool> { fn checkChecksum(&self, s: &str) -> Result<bool> {
self.checkStandardUPCEANChecksum( self.checkStandardUPCEANChecksum(&convertUPCEtoUPCA(s).ok_or(Exceptions::ILLEGAL_ARGUMENT)?)
&convertUPCEtoUPCA(s).ok_or(Exceptions::ILLEGAL_ARGUMENT)?,
)
} }
fn decodeEnd(&self, row: &crate::common::BitArray, endStart: usize) -> Result<[usize; 2]> { fn decodeEnd(&self, row: &crate::common::BitArray, endStart: usize) -> Result<[usize; 2]> {

View File

@@ -768,9 +768,7 @@ fn numericCompaction(
Remove leading 1 => RXingResult is 000213298174000 Remove leading 1 => RXingResult is 000213298174000
*/ */
fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result<String> { fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result<String> {
let mut result = 0 let mut result = 0.to_biguint().ok_or(Exceptions::ARITHMETIC)?;
.to_biguint()
.ok_or(Exceptions::ARITHMETIC)?;
for i in 0..count { for i in 0..count {
result += result +=
&EXP900[count - i - 1] * (codewords[i].to_biguint().ok_or(Exceptions::ARITHMETIC)?); &EXP900[count - i - 1] * (codewords[i].to_biguint().ok_or(Exceptions::ARITHMETIC)?);

View File

@@ -386,7 +386,12 @@ fn decodeAlphanumericSegment(
if fc1InEffect { if fc1InEffect {
// We need to massage the result a bit if in an FNC1 mode: // We need to massage the result a bit if in an FNC1 mode:
for i in start..result.len() { for i in start..result.len() {
if result.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == '%' { if result
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
== '%'
{
if i < result.len() - 1 if i < result.len() - 1
&& result && result
.chars() .chars()

View File

@@ -259,18 +259,13 @@ impl MinimalEncoder {
position: usize, position: usize,
edge: Option<Rc<Edge>>, edge: Option<Rc<Edge>>,
) -> Result<()> { ) -> Result<()> {
let vertexIndex = position let vertexIndex =
+ edge position + edge.as_ref().ok_or(Exceptions::FORMAT)?.characterLength as usize;
.as_ref() let modeEdges =
.ok_or(Exceptions::FORMAT)? &mut edges[vertexIndex][edge.as_ref().ok_or(Exceptions::FORMAT)?.charsetEncoderIndex];
.characterLength as usize; let modeOrdinal =
let modeEdges = &mut edges[vertexIndex][edge Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::FORMAT)?.mode))?
.as_ref() as usize;
.ok_or(Exceptions::FORMAT)?
.charsetEncoderIndex];
let modeOrdinal = Self::getCompactedOrdinal(Some(
edge.as_ref().ok_or(Exceptions::FORMAT)?.mode,
))? as usize;
if modeEdges[modeOrdinal].is_none() if modeEdges[modeOrdinal].is_none()
|| modeEdges[modeOrdinal] || modeEdges[modeOrdinal]
.as_ref() .as_ref()
@@ -378,8 +373,8 @@ impl MinimalEncoder {
0, 0,
if from + 1 >= inputLength if from + 1 >= inputLength
|| !self.canEncode( || !self.canEncode(
&Mode::ALPHANUMERIC, &Mode::ALPHANUMERIC,
self.stringToEncode self.stringToEncode
.get(from + 1) .get(from + 1)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) )
@@ -414,8 +409,8 @@ impl MinimalEncoder {
0, 0,
if from + 1 >= inputLength if from + 1 >= inputLength
|| !self.canEncode( || !self.canEncode(
&Mode::NUMERIC, &Mode::NUMERIC,
self.stringToEncode self.stringToEncode
.get(from + 1) .get(from + 1)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) )
@@ -423,8 +418,8 @@ impl MinimalEncoder {
1 1
} else if from + 2 >= inputLength } else if from + 2 >= inputLength
|| !self.canEncode( || !self.canEncode(
&Mode::NUMERIC, &Mode::NUMERIC,
self.stringToEncode self.stringToEncode
.get(from + 2) .get(from + 2)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?, .ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) )

View File

@@ -179,7 +179,9 @@ pub fn encode_with_hints(
version = Version::getVersionForNumber(versionNumber)?; version = Version::getVersionForNumber(versionNumber)?;
let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version); let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version);
if !willFit(bitsNeeded, version, &ec_level) { if !willFit(bitsNeeded, version, &ec_level) {
return Err(Exceptions::writer_with("Data too big for requested version")); return Err(Exceptions::writer_with(
"Data too big for requested version",
));
} }
} else { } else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?; version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -651,7 +653,11 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let length = content.len(); let length = content.len();
let mut i = 0; let mut i = 0;
while i < length { while i < length {
let num1 = content.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8 - b'0'; let num1 = content
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8
- b'0';
if i + 2 < length { if i + 2 < length {
// Encode three numeric letters in ten bits. // Encode three numeric letters in ten bits.
let num2 = content let num2 = content
@@ -688,8 +694,12 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()>
let length = content.len(); let length = content.len();
let mut i = 0; let mut i = 0;
while i < length { while i < length {
let code1 = let code1 = getAlphanumericCode(
getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32); content
.chars()
.nth(i)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32,
);
if code1 == -1 { if code1 == -1 {
return Err(Exceptions::WRITER); return Err(Exceptions::WRITER);
} }