Use thiserror for error handling with less boilerplate

This commit is contained in:
Steve Cook
2023-02-20 09:41:28 -05:00
parent 01e4f4a126
commit f8b29f37db
135 changed files with 868 additions and 905 deletions

View File

@@ -32,12 +32,12 @@ impl Encoder for ASCIIEncoder {
.getMessage()
.chars()
.nth(context.pos as usize)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
context
.getMessage()
.chars()
.nth(context.pos as usize + 1)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
)? as u8);
context.pos += 2;
} else {
@@ -74,7 +74,7 @@ impl Encoder for ASCIIEncoder {
}
_ => {
return Err(Exceptions::illegalStateWith(format!(
return Err(Exceptions::illegal_state_with(format!(
"Illegal mode: {newMode}"
)));
}
@@ -105,7 +105,7 @@ impl ASCIIEncoder {
let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48);
Ok((num + 130) as char)
} else {
Err(Exceptions::illegalArgumentWith(format!(
Err(Exceptions::illegal_argument_with(format!(
"not digits: {digit1}{digit2}"
)))
}

View File

@@ -54,7 +54,7 @@ impl Encoder for Base256Encoder {
context.updateSymbolInfoWithLength(currentSize);
let mustPad = (context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity()
- currentSize as u32)
> 0;
@@ -63,26 +63,26 @@ impl Encoder for Base256Encoder {
buffer.replace_range(
0..1,
&char::from_u32(dataCount as u32)
.ok_or(Exceptions::parse)?
.ok_or(Exceptions::PARSE)?
.to_string(),
);
} else if dataCount <= 1555 {
buffer.replace_range(
0..1,
&char::from_u32((dataCount as u32 / 250) + 249)
.ok_or(Exceptions::parse)?
.ok_or(Exceptions::PARSE)?
.to_string(),
);
let (ci_pos, _) = buffer
.char_indices()
.nth(1)
.ok_or(Exceptions::indexOutOfBounds)?;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
buffer.insert(
ci_pos,
char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::indexOutOfBounds)?,
char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
);
} else {
return Err(Exceptions::illegalStateWith(format!(
return Err(Exceptions::illegal_state_with(format!(
"Message length not in valid ranges: {dataCount}"
)));
}
@@ -92,10 +92,10 @@ impl Encoder for Base256Encoder {
// for (int i = 0, c = buffer.length(); i < c; i++) {
context.writeCodeword(
Self::randomize255State(
buffer.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?,
buffer.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
context.getCodewordCount() as u32 + 1,
)
.ok_or(Exceptions::parse)? as u8,
.ok_or(Exceptions::PARSE)? as u8,
);
}
Ok(())

View File

@@ -66,7 +66,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity() as usize
- curCodewordCount;
@@ -141,7 +141,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity() as usize
- curCodewordCount;
let rest = buffer.chars().count() % 3;
@@ -184,7 +184,7 @@ impl C40Encoder {
buffer: &mut String,
) -> Result<()> {
context.writeCodewords(
&Self::encodeToCodewords(buffer).ok_or(Exceptions::FormatException(None))?,
&Self::encodeToCodewords(buffer).ok_or(Exceptions::FORMAT)?,
);
buffer.replace_range(0..3, "");
// buffer.delete(0, 3);
@@ -205,7 +205,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity() as usize
- curCodewordCount;
@@ -234,7 +234,7 @@ impl C40Encoder {
context.writeCodeword(C40_UNLATCH);
}
} else {
return Err(Exceptions::illegalStateWith(
return Err(Exceptions::illegal_state_with(
"Unexpected case. Please report!",
));
}

View File

@@ -165,7 +165,7 @@ impl DefaultPlacement {
.codewords
.chars()
.nth(pos)
.ok_or(Exceptions::indexOutOfBounds)? as u32;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32;
v &= 1 << (8 - bit);
self.setBit(col as usize, row as usize, v != 0);

View File

@@ -77,7 +77,7 @@ impl EdifactEncoder {
context.updateSymbolInfo();
let mut available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity()
- context.getCodewordCount() as u32;
let remaining = context.getRemainingCharacters();
@@ -86,7 +86,7 @@ impl EdifactEncoder {
context.updateSymbolInfoWithLength(context.getCodewordCount() + 1);
available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity()
- context.getCodewordCount() as u32;
}
@@ -96,7 +96,7 @@ impl EdifactEncoder {
}
if count > 4 {
return Err(Exceptions::illegalStateWith("Count must not exceed 4"));
return Err(Exceptions::illegal_state_with("Count must not exceed 4"));
}
let restChars = count - 1;
let encoded = Self::encodeToCodewords(buffer)?;
@@ -107,7 +107,7 @@ impl EdifactEncoder {
context.updateSymbolInfoWithLength(context.getCodewordCount() + restChars);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity()
- context.getCodewordCount() as u32;
if available >= 3 {
@@ -148,23 +148,23 @@ impl EdifactEncoder {
fn encodeToCodewords(sb: &str) -> Result<String> {
let len = sb.chars().count();
if len == 0 {
return Err(Exceptions::illegalStateWith(
return Err(Exceptions::illegal_state_with(
"StringBuilder must not be empty",
));
}
let c1 = sb.chars().next().ok_or(Exceptions::indexOutOfBounds)?;
let c1 = sb.chars().next().ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
let c2 = if len >= 2 {
sb.chars().nth(1).ok_or(Exceptions::indexOutOfBounds)?
sb.chars().nth(1).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
} else {
0 as char
};
let c3 = if len >= 3 {
sb.chars().nth(2).ok_or(Exceptions::indexOutOfBounds)?
sb.chars().nth(2).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
} else {
0 as char
};
let c4 = if len >= 4 {
sb.chars().nth(3).ok_or(Exceptions::indexOutOfBounds)?
sb.chars().nth(3).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
} else {
0 as char
};
@@ -174,12 +174,12 @@ impl EdifactEncoder {
let cw2 = (v >> 8) & 255;
let cw3 = v & 255;
let mut res = String::with_capacity(3);
res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBounds)?);
res.push(char::from_u32(cw1).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?);
if len >= 2 {
res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBounds)?);
res.push(char::from_u32(cw2).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?);
}
if len >= 3 {
res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBounds)?);
res.push(char::from_u32(cw3).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?);
}
Ok(res)

View File

@@ -64,10 +64,10 @@ impl<'a> EncoderContext<'_> {
ISO_8859_1_ENCODER
.decode(&encoded_bytes, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::parseWith(format!("round trip decode should always work: {e}"))
Exceptions::parse_with(format!("round trip decode should always work: {e}"))
})?
} else {
return Err(Exceptions::illegalArgumentWith(
return Err(Exceptions::illegal_argument_with(
"Message contains characters outside ISO-8859-1 encoding.",
));
};

View File

@@ -155,7 +155,7 @@ const ALOG: [u32; 255] = {
*/
pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String> {
if codewords.chars().count() != symbolInfo.getDataCapacity() as usize {
return Err(Exceptions::illegalArgumentWith(
return Err(Exceptions::illegal_argument_with(
"The number of codewords does not match the selected symbol",
));
}
@@ -186,7 +186,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String>
codewords
.chars()
.nth(d)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
);
d += blockCount;
@@ -199,12 +199,12 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String>
let (char_index, replace_char) = sb
.char_indices()
.nth(symbolInfo.getDataCapacity() as usize + e)
.ok_or(Exceptions::indexOutOfBounds)?;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
sb.replace_range(
char_index..(replace_char.len_utf8()),
&ecc.chars()
.nth(pos)
.ok_or(Exceptions::indexOutOfBounds)?
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
.to_string(),
);
// sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos));
@@ -229,7 +229,7 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String> {
}
}
if table < 0 {
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"Illegal number of error correction codewords specified: {numECWords}"
)));
}
@@ -245,21 +245,21 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String> {
^ codewords
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBounds)? as usize;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as usize;
for k in (1..numECWords).rev() {
// for (int k = numECWords - 1; k > 0; k--) {
if m != 0 && poly[k] != 0 {
ecc[k] = char::from_u32(
ecc[k - 1] as u32 ^ ALOG[(LOG[m] + LOG[poly[k] as usize]) as usize % 255],
)
.ok_or(Exceptions::indexOutOfBounds)?;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
} else {
ecc[k] = ecc[k - 1];
}
}
if m != 0 && poly[0] != 0 {
ecc[0] = char::from_u32(ALOG[(LOG[m] + LOG[poly[0] as usize]) as usize % 255])
.ok_or(Exceptions::indexOutOfBounds)?;
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
} else {
ecc[0] = 0 as char;
}

View File

@@ -222,14 +222,14 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
if forceC40 {
c40Encoder.encodeMaximalC40(&mut context)?;
encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?;
encodingMode = context.getNewEncoding().ok_or(Exceptions::ILLEGAL_STATE)?;
context.resetEncoderSignal();
}
while context.hasMoreCharacters() {
encoders[encodingMode].encode(&mut context)?;
if context.getNewEncoding().is_some() {
encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?;
encodingMode = context.getNewEncoding().ok_or(Exceptions::ILLEGAL_STATE)?;
context.resetEncoderSignal();
}
}
@@ -237,7 +237,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
context.updateSymbolInfo();
let capacity = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity();
if len < capacity as usize
&& encodingMode != ASCII_ENCODATION
@@ -608,7 +608,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 {
pub fn illegalCharacter(c: char) -> Result<()> {
// let hex = Integer.toHexString(c);
// hex = "0000".substring(0, 4 - hex.length()) + hex;
Err(Exceptions::illegalArgumentWith(format!(
Err(Exceptions::illegal_argument_with(format!(
"Illegal character: {c} (0x{c})"
)))
}

View File

@@ -218,7 +218,7 @@ fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<()> {
if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none()
|| edges[vertexIndex][edge.getEndMode()?.ordinal()]
.as_ref()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.cachedTotalSize
> edge.cachedTotalSize
{
@@ -635,7 +635,7 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult> {
}
if minimalJ < 0 {
return Err(Exceptions::illegalStateWith(format!(
return Err(Exceptions::illegal_state_with(format!(
"Internal error: failed to encode \"{input}\""
)));
}
@@ -669,7 +669,7 @@ impl Edge {
previous: Option<Rc<Edge>>,
) -> Result<Self> {
if fromPosition + characterLength > input.length() as u32 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let mut size = if let Some(previous) = previous.clone() {
@@ -1276,7 +1276,7 @@ impl RXingResult {
let solution = if let Some(edge) = solution {
edge
} else {
return Err(Exceptions::illegalArgument);
return Err(Exceptions::ILLEGAL_ARGUMENT);
};
let input = solution.input.clone();
let mut size = 0;

View File

@@ -129,7 +129,7 @@ impl SymbolInfo {
2 | 4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::illegalStateWith(
_ => Err(Exceptions::illegal_state_with(
"Cannot handle this number of data regions",
)),
}
@@ -141,7 +141,7 @@ impl SymbolInfo {
4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::illegalStateWith(
_ => Err(Exceptions::illegal_state_with(
"Cannot handle this number of data regions",
)),
}
@@ -311,7 +311,7 @@ impl<'a> SymbolInfoLookup<'a> {
}
}
if fail {
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"Can't find a symbol arrangement that matches the message. Data codewords: {dataCodewords}"
)));
}

View File

@@ -82,7 +82,7 @@ impl X12Encoder {
context.updateSymbolInfo();
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.getDataCapacity()
- context.getCodewordCount() as u32;
let count = buffer.chars().count();