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

@@ -175,7 +175,7 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result<bool> {
((temp % 3) + ((y + x) & 0x1)) & 0x1
}
_ => {
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"Invalid mask pattern: {maskPattern}"
)))
}

View File

@@ -274,7 +274,7 @@ pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMat
}
// All bits should be consumed.
if bitIndex != dataBits.getSize() {
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"Not all bits consumed: {}/{}",
bitIndex,
dataBits.getSize()
@@ -319,7 +319,7 @@ pub fn findMSBSet(value: u32) -> u32 {
// operations. We don't care if coefficients are positive or negative.
pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32> {
if poly == 0 {
return Err(Exceptions::illegalArgumentWith("0 polynomial"));
return Err(Exceptions::illegal_argument_with("0 polynomial"));
}
let mut value = value;
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
@@ -343,7 +343,7 @@ pub fn makeTypeInfoBits(
bits: &mut BitArray,
) -> Result<()> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::writerWith("Invalid mask pattern"));
return Err(Exceptions::writer_with("Invalid mask pattern"));
}
let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
bits.appendBits(typeInfo, 5)?;
@@ -357,7 +357,7 @@ pub fn makeTypeInfoBits(
if bits.getSize() != 15 {
// Just in case.
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"should not happen but we got: {}",
bits.getSize()
)));
@@ -374,7 +374,7 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()>
if bits.getSize() != 18 {
// Just in case.
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"should not happen but we got: {}",
bits.getSize()
)));
@@ -407,7 +407,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<()> {
if matrix.get(8, matrix.getHeight() - 8) == 0 {
return Err(Exceptions::writer);
return Err(Exceptions::WRITER);
}
matrix.set(8, matrix.getHeight() - 8, 1);
Ok(())
@@ -420,7 +420,7 @@ pub fn embedHorizontalSeparationPattern(
) -> Result<()> {
for x in 0..8 {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::writer);
return Err(Exceptions::WRITER);
}
matrix.set(xStart + x, yStart, 0);
}
@@ -434,7 +434,7 @@ pub fn embedVerticalSeparationPattern(
) -> Result<()> {
for y in 0..7 {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::writer);
return Err(Exceptions::WRITER);
}
matrix.set(xStart, yStart + y, 0);
}

View File

@@ -158,7 +158,7 @@ impl MinimalEncoder {
Self::getVersion(Self::getVersionSize(result.getVersion()))?,
&self.ecLevel,
) {
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"Data too big for version {version}"
)));
}
@@ -186,7 +186,7 @@ impl MinimalEncoder {
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::writerWith("Data too big for any version"));
return Err(Exceptions::writer_with("Data too big for any version"));
}
Ok(results[smallestRXingResult as usize].clone())
}
@@ -247,7 +247,7 @@ impl MinimalEncoder {
Some(Mode::ALPHANUMERIC) => Ok(1),
Some(Mode::BYTE) => Ok(3),
Some(Mode::KANJI) | None => Ok(0),
_ => Err(Exceptions::illegalArgumentWith(format!(
_ => Err(Exceptions::illegal_argument_with(format!(
"Illegal mode {mode:?}"
))),
}
@@ -262,21 +262,21 @@ impl MinimalEncoder {
let vertexIndex = position
+ edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::FORMAT)?
.characterLength as usize;
let modeEdges = &mut edges[vertexIndex][edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::FORMAT)?
.charsetEncoderIndex];
let modeOrdinal = Self::getCompactedOrdinal(Some(
edge.as_ref().ok_or(Exceptions::FormatException(None))?.mode,
edge.as_ref().ok_or(Exceptions::FORMAT)?.mode,
))? as usize;
if modeEdges[modeOrdinal].is_none()
|| modeEdges[modeOrdinal]
.as_ref()
.ok_or(Exceptions::format)?
.ok_or(Exceptions::FORMAT)?
.cachedTotalSize
> edge.as_ref().ok_or(Exceptions::format)?.cachedTotalSize
> edge.as_ref().ok_or(Exceptions::FORMAT)?.cachedTotalSize
{
modeEdges[modeOrdinal] = edge;
}
@@ -299,12 +299,12 @@ impl MinimalEncoder {
.encoders
.canEncode(
&self.stringToEncode[from],
priorityEncoderIndex.ok_or(Exceptions::format)?,
priorityEncoderIndex.ok_or(Exceptions::FORMAT)?,
)
.ok_or(Exceptions::format)?
.ok_or(Exceptions::FORMAT)?
{
start = priorityEncoderIndex.ok_or(Exceptions::format)?;
end = priorityEncoderIndex.ok_or(Exceptions::format)? + 1;
start = priorityEncoderIndex.ok_or(Exceptions::FORMAT)?;
end = priorityEncoderIndex.ok_or(Exceptions::FORMAT)? + 1;
}
for i in start..end {
@@ -313,10 +313,10 @@ impl MinimalEncoder {
.canEncode(
self.stringToEncode
.get(from)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
i,
)
.ok_or(Exceptions::format)?
.ok_or(Exceptions::FORMAT)?
{
self.addEdge(
edges,
@@ -332,7 +332,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::writer)?,
.ok_or(Exceptions::WRITER)?,
)),
)?;
}
@@ -340,7 +340,7 @@ impl MinimalEncoder {
if self.canEncode(
&Mode::KANJI,
self.stringToEncode.get(from).ok_or(Exceptions::format)?,
self.stringToEncode.get(from).ok_or(Exceptions::FORMAT)?,
) {
self.addEdge(
edges,
@@ -356,7 +356,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::writer)?,
.ok_or(Exceptions::WRITER)?,
)),
)?;
}
@@ -366,7 +366,7 @@ impl MinimalEncoder {
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) {
self.addEdge(
edges,
@@ -378,10 +378,10 @@ impl MinimalEncoder {
0,
if from + 1 >= inputLength
|| !self.canEncode(
&Mode::ALPHANUMERIC,
self.stringToEncode
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
)
{
1
@@ -393,7 +393,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::writer)?,
.ok_or(Exceptions::WRITER)?,
)),
)?;
}
@@ -402,7 +402,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
) {
self.addEdge(
edges,
@@ -414,19 +414,19 @@ impl MinimalEncoder {
0,
if from + 1 >= inputLength
|| !self.canEncode(
&Mode::NUMERIC,
self.stringToEncode
&Mode::NUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
)
{
1
} else if from + 2 >= inputLength
|| !self.canEncode(
&Mode::NUMERIC,
self.stringToEncode
&Mode::NUMERIC,
self.stringToEncode
.get(from + 2)
.ok_or(Exceptions::indexOutOfBounds)?,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?,
)
{
2
@@ -438,7 +438,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::writer)?,
.ok_or(Exceptions::WRITER)?,
)),
)?;
}
@@ -598,16 +598,16 @@ impl MinimalEncoder {
version,
edges[inputLength][minJ][minK]
.as_ref()
.ok_or(Exceptions::writer)?
.ok_or(Exceptions::WRITER)?
.clone(),
self.isGS1,
&self.ecLevel,
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::writer)?)
.ok_or(Exceptions::WRITER)?)
} else {
Err(Exceptions::writerWith(format!(
Err(Exceptions::writer_with(format!(
r#"Internal error: failed to encode "{}"#,
self.stringToEncode
.iter()
@@ -1023,7 +1023,7 @@ impl RXingResultNode {
bits,
self.encoders
.getCharset(self.charsetEncoderIndex)
.ok_or(Exceptions::writer)?,
.ok_or(Exceptions::WRITER)?,
)?;
}
Ok(())

View File

@@ -101,7 +101,7 @@ pub fn encode_with_hints(
if has_encoding_hint {
if let Some(EncodeHintValue::CharacterSet(v)) = hints.get(&EncodeHintType::CHARACTER_SET) {
encoding =
Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writer)?)
Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::WRITER)?)
}
}
@@ -179,7 +179,7 @@ pub fn encode_with_hints(
version = Version::getVersionForNumber(versionNumber)?;
let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version);
if !willFit(bitsNeeded, version, &ec_level) {
return Err(Exceptions::writerWith("Data too big for requested version"));
return Err(Exceptions::writer_with("Data too big for requested version"));
}
} else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -384,7 +384,7 @@ fn chooseVersion(numInputBits: u32, ecLevel: &ErrorCorrectionLevel) -> Result<Ve
return Ok(version);
}
}
Err(Exceptions::writerWith(format!(
Err(Exceptions::writer_with(format!(
"data too big {numInputBits}/{ecLevel:?}"
)))
}
@@ -412,7 +412,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<()> {
let capacity = num_data_bytes * 8;
if bits.getSize() > capacity as usize {
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"data bits cannot fit in the QR Code{capacity} > "
)));
}
@@ -440,7 +440,7 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<()> {
bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?;
}
if bits.getSize() != capacity as usize {
return Err(Exceptions::writerWith("Bits size does not equal capacity"));
return Err(Exceptions::writer_with("Bits size does not equal capacity"));
}
Ok(())
}
@@ -459,7 +459,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32)> {
if block_id >= num_rsblocks {
return Err(Exceptions::writerWith("Block ID too large"));
return Err(Exceptions::writer_with("Block ID too large"));
}
// numRsBlocksInGroup2 = 196 % 5 = 1
let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks;
@@ -480,18 +480,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// Sanity checks.
// 26 = 26
if num_ec_bytes_in_group1 != numEcBytesInGroup2 {
return Err(Exceptions::writerWith("EC bytes mismatch"));
return Err(Exceptions::writer_with("EC bytes mismatch"));
}
// 5 = 4 + 1.
if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 {
return Err(Exceptions::writerWith("RS blocks mismatch"));
return Err(Exceptions::writer_with("RS blocks mismatch"));
}
// 196 = (13 + 26) * 4 + (14 + 26) * 1
if num_total_bytes
!= ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) * num_rs_blocks_in_group1)
+ ((num_data_bytes_in_group2 + numEcBytesInGroup2) * num_rs_blocks_in_group2)
{
return Err(Exceptions::writerWith("total bytes mismatch"));
return Err(Exceptions::writer_with("total bytes mismatch"));
}
Ok(if block_id < num_rs_blocks_in_group1 {
@@ -513,7 +513,7 @@ pub fn interleaveWithECBytes(
) -> Result<BitArray> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::writerWith(
return Err(Exceptions::writer_with(
"Number of bits and data bytes does not match",
));
}
@@ -548,7 +548,7 @@ pub fn interleaveWithECBytes(
data_bytes_offset += numDataBytesInBlock as usize;
}
if num_data_bytes != data_bytes_offset as u32 {
return Err(Exceptions::writerWith("Data bytes does not match offset"));
return Err(Exceptions::writer_with("Data bytes does not match offset"));
}
let mut result = BitArray::new();
@@ -573,7 +573,7 @@ pub fn interleaveWithECBytes(
}
if num_total_bytes != result.getSizeInBytes() as u32 {
// Should be same.
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"Interleaving error: {} and {} differ.",
num_total_bytes,
result.getSizeInBytes()
@@ -620,7 +620,7 @@ pub fn appendLengthInfo(
) -> Result<()> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::writerWith(format!(
return Err(Exceptions::writer_with(format!(
"{} is bigger than {}",
num_letters,
((1 << numBits) - 1)
@@ -643,7 +643,7 @@ pub fn appendBytes(
Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits),
Mode::BYTE => append8BitBytes(content, bits, encoding),
Mode::KANJI => appendKanjiBytes(content, bits),
_ => Err(Exceptions::writerWith(format!("Invalid mode: {mode:?}"))),
_ => Err(Exceptions::writer_with(format!("Invalid mode: {mode:?}"))),
}
}
@@ -651,18 +651,18 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let length = content.len();
let mut i = 0;
while i < length {
let num1 = content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? 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 {
// Encode three numeric letters in ten bits.
let num2 = content
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBounds)? as u8
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8
- b'0';
let num3 = content
.chars()
.nth(i + 2)
.ok_or(Exceptions::indexOutOfBounds)? as u8
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8
- b'0';
bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?;
i += 3;
@@ -671,7 +671,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let num2 = content
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBounds)? as u8
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u8
- b'0';
bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?;
i += 2;
@@ -689,19 +689,19 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()>
let mut i = 0;
while i < length {
let code1 =
getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32);
getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32);
if code1 == -1 {
return Err(Exceptions::writer);
return Err(Exceptions::WRITER);
}
if i + 1 < length {
let code2 = getAlphanumericCode(
content
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBounds)? as u32,
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? as u32,
);
if code2 == -1 {
return Err(Exceptions::writer);
return Err(Exceptions::WRITER);
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?;
@@ -718,7 +718,7 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()>
pub fn append8BitBytes(content: &str, bits: &mut BitArray, encoding: EncodingRef) -> Result<()> {
let bytes = encoding
.encode(content, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::writerWith(format!("error {e}")))?;
.map_err(|e| Exceptions::writer_with(format!("error {e}")))?;
for b in bytes {
bits.appendBits(b as u32, 8)?;
}
@@ -730,9 +730,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let bytes = sjis
.encode(content, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::writerWith(format!("error {e}")))?;
.map_err(|e| Exceptions::writer_with(format!("error {e}")))?;
if bytes.len() % 2 != 0 {
return Err(Exceptions::writerWith("Kanji byte size not even"));
return Err(Exceptions::writer_with("Kanji byte size not even"));
}
let max_i = bytes.len() - 1; // bytes.length must be even
let mut i = 0;
@@ -747,7 +747,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> {
subtracted = code as i32 - 0xc140;
}
if subtracted == -1 {
return Err(Exceptions::writerWith("Invalid byte sequence"));
return Err(Exceptions::writer_with("Invalid byte sequence"));
}
let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded as u32, 13)?;