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

@@ -39,7 +39,7 @@ impl BitMatrixParser {
pub fn new(bit_matrix: BitMatrix) -> Result<Self> {
let dimension = bit_matrix.getHeight();
if dimension < 21 || (dimension & 0x03) != 1 {
Err(Exceptions::formatWith(format!(
Err(Exceptions::format_with(format!(
"{dimension} < 21 || ({dimension} % 0x03) != 1"
)))
} else {
@@ -61,7 +61,7 @@ impl BitMatrixParser {
*/
pub fn readFormatInformation(&mut self) -> Result<&FormatInformation> {
if self.parsedFormatInfo.is_some() {
return self.parsedFormatInfo.as_ref().ok_or(Exceptions::parse);
return self.parsedFormatInfo.as_ref().ok_or(Exceptions::PARSE);
}
// Read top-left format info bits
@@ -92,7 +92,7 @@ impl BitMatrixParser {
self.parsedFormatInfo =
FormatInformation::decodeFormatInformation(formatInfoBits1, formatInfoBits2);
self.parsedFormatInfo.as_ref().ok_or(Exceptions::format)
self.parsedFormatInfo.as_ref().ok_or(Exceptions::FORMAT)
}
/**
@@ -144,7 +144,7 @@ impl BitMatrixParser {
return Ok(theParsedVersion);
}
}
Err(Exceptions::format)
Err(Exceptions::FORMAT)
}
fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 {
@@ -225,7 +225,7 @@ impl BitMatrixParser {
}
if resultOffset != version.getTotalCodewords() as usize {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
Ok(result)
}

View File

@@ -56,7 +56,7 @@ impl DataBlock {
ecLevel: ErrorCorrectionLevel,
) -> Result<Vec<Self>> {
if rawCodewords.len() as u32 != version.getTotalCodewords() {
return Err(Exceptions::illegalArgument);
return Err(Exceptions::ILLEGAL_ARGUMENT);
}
// Figure out the number and size of data blocks used by this version and

View File

@@ -228,7 +228,7 @@ impl TryFrom<u8> for DataMask {
5 => Ok(DataMask::DATA_MASK_101),
6 => Ok(DataMask::DATA_MASK_110),
7 => Ok(DataMask::DATA_MASK_111),
_ => Err(Exceptions::illegalArgumentWith(format!(
_ => Err(Exceptions::illegal_argument_with(format!(
"{value} is not between 0 and 7"
))),
}

View File

@@ -78,7 +78,7 @@ pub fn decode(
}
Mode::STRUCTURED_APPEND => {
if bits.available() < 16 {
return Err(Exceptions::formatWith(format!(
return Err(Exceptions::format_with(format!(
"Mode::Structured append expected bits.available() < 16, found bits of {}",
bits.available()
)));
@@ -93,7 +93,7 @@ pub fn decode(
let value = parseECIValue(&mut bits)?;
currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value).ok();
if currentCharacterSetECI.is_none() {
return Err(Exceptions::formatWith(format!(
return Err(Exceptions::format_with(format!(
"Value of {value} not valid"
)));
}
@@ -132,7 +132,7 @@ pub fn decode(
currentCharacterSetECI,
hints,
)?,
_ => return Err(Exceptions::format),
_ => return Err(Exceptions::FORMAT),
}
}
}
@@ -177,7 +177,7 @@ pub fn decode(
fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -> Result<()> {
// Don't crash trying to read more bits than we have available.
if count * 13 > bits.available() {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -204,10 +204,10 @@ fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -
}
let gb_encoder =
encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalState)?;
encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::ILLEGAL_STATE)?;
let encode_string = gb_encoder
.decode(&buffer, encoding::DecoderTrap::Strict)
.map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?;
.map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?;
result.push_str(&encode_string);
Ok(())
}
@@ -221,7 +221,7 @@ fn decodeKanjiSegment(
) -> Result<()> {
// Don't crash trying to read more bits than we have available.
if count * 13 > bits.available() {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -250,7 +250,7 @@ fn decodeKanjiSegment(
let encoder = {
let _ = currentCharacterSetECI;
let _ = hints;
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)?
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::FORMAT)?
};
#[cfg(feature = "allow_forced_iso_ied_18004_compliance")]
@@ -263,12 +263,12 @@ fn decodeKanjiSegment(
encoding::all::ISO_8859_1
}
} else {
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)?
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::FORMAT)?
};
let encode_string = encoder
.decode(&buffer, encoding::DecoderTrap::Strict)
.map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?;
.map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?;
result.push_str(&encode_string);
@@ -285,7 +285,7 @@ fn decodeByteSegment(
) -> Result<()> {
// Don't crash trying to read more bits than we have available.
if 8 * count > bits.available() {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let mut readBytes = vec![0u8; count];
@@ -301,7 +301,7 @@ fn decodeByteSegment(
// give a hint.
{
#[cfg(not(feature = "allow_forced_iso_ied_18004_compliance"))]
StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalState)?
StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::ILLEGAL_STATE)?
}
#[cfg(feature = "allow_forced_iso_ied_18004_compliance")]
@@ -316,14 +316,14 @@ fn decodeByteSegment(
CharacterSetECI::getCharset(
currentCharacterSetECI
.as_ref()
.ok_or(Exceptions::illegalState)?,
.ok_or(Exceptions::ILLEGAL_STATE)?,
)
};
let encode_string = if currentCharacterSetECI.is_some()
&& currentCharacterSetECI
.as_ref()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
== &CharacterSetECI::Cp437
{
{
@@ -336,7 +336,7 @@ fn decodeByteSegment(
encoding
.decode(&readBytes, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::parseWith(format!("unable to decode buffer {readBytes:?}: {e}"))
Exceptions::parse_with(format!("unable to decode buffer {readBytes:?}: {e}"))
})?
};
@@ -348,13 +348,13 @@ fn decodeByteSegment(
fn toAlphaNumericChar(value: u32) -> Result<char> {
if value as usize >= ALPHANUMERIC_CHARS.len() {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
ALPHANUMERIC_CHARS
.chars()
.nth(value as usize)
.ok_or(Exceptions::format)
.ok_or(Exceptions::FORMAT)
}
fn decodeAlphanumericSegment(
@@ -368,7 +368,7 @@ fn decodeAlphanumericSegment(
let mut count = count;
while count > 1 {
if bits.available() < 11 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let nextTwoCharsBits = bits.readBits(11)?;
result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?);
@@ -378,7 +378,7 @@ fn decodeAlphanumericSegment(
if count == 1 {
// special case: one character left
if bits.available() < 6 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
result.push(toAlphaNumericChar(bits.readBits(6)?)?);
}
@@ -386,12 +386,12 @@ fn decodeAlphanumericSegment(
if fc1InEffect {
// We need to massage the result a bit if in an FNC1 mode:
for i in start..result.len() {
if result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? == '%' {
if result.chars().nth(i).ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)? == '%' {
if i < result.len() - 1
&& result
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBounds)?
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?
== '%'
{
// %% is rendered as %
@@ -413,11 +413,11 @@ fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize)
while count >= 3 {
// Each 10 bits encodes three digits
if bits.available() < 10 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let threeDigitsBits = bits.readBits(10)?;
if threeDigitsBits >= 1000 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
result.push(toAlphaNumericChar(threeDigitsBits / 100)?);
result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?);
@@ -427,22 +427,22 @@ fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize)
if count == 2 {
// Two digits left over to read, encoded in 7 bits
if bits.available() < 7 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let twoDigitsBits = bits.readBits(7)?;
if twoDigitsBits >= 100 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
result.push(toAlphaNumericChar(twoDigitsBits / 10)?);
result.push(toAlphaNumericChar(twoDigitsBits % 10)?);
} else if count == 1 {
// One digit left over to read
if bits.available() < 4 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
let digitBits = bits.readBits(4)?;
if digitBits >= 10 {
return Err(Exceptions::format);
return Err(Exceptions::FORMAT);
}
result.push(toAlphaNumericChar(digitBits)?);
}
@@ -467,5 +467,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result<u32> {
return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes);
}
Err(Exceptions::format)
Err(Exceptions::FORMAT)
}

View File

@@ -48,7 +48,7 @@ impl ErrorCorrectionLevel {
1 => Ok(Self::L),
2 => Ok(Self::H),
3 => Ok(Self::Q),
_ => Err(Exceptions::illegalArgumentWith(format!(
_ => Err(Exceptions::illegal_argument_with(format!(
"{bits} is not a valid bit selection"
))),
}
@@ -110,7 +110,7 @@ impl FromStr for ErrorCorrectionLevel {
return number_possible.try_into();
}
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"could not parse {s} into an ec level"
)));
}

View File

@@ -69,7 +69,7 @@ impl Mode {
{
Ok(Self::HANZI)
}
_ => Err(Exceptions::illegalArgumentWith(format!(
_ => Err(Exceptions::illegal_argument_with(format!(
"{bits} is not valid"
))),
}

View File

@@ -129,7 +129,7 @@ pub fn decode_bitmatrix_with_hints(
if let Some(fe) = fe {
Err(fe)
} else {
Err(ce.unwrap_or(Exceptions::checksum))
Err(ce.unwrap_or(Exceptions::CHECKSUM))
}
}
_ => Err(er),

View File

@@ -102,14 +102,14 @@ impl Version {
*/
pub fn getProvisionalVersionForDimension(dimension: u32) -> Result<&'static Version> {
if dimension % 4 != 1 {
return Err(Exceptions::formatWith("dimension incorrect"));
return Err(Exceptions::format_with("dimension incorrect"));
}
Self::getVersionForNumber((dimension - 17) / 4)
}
pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version> {
if !(1..=40).contains(&versionNumber) {
return Err(Exceptions::illegalArgumentWith("version out of spec"));
return Err(Exceptions::illegal_argument_with("version out of spec"));
}
Ok(&VERSIONS[versionNumber as usize - 1])
}
@@ -137,7 +137,7 @@ impl Version {
return Self::getVersionForNumber(bestVersion);
}
// If we didn't find a close enough match, fail
Err(Exceptions::notFound)
Err(Exceptions::NOT_FOUND)
}
/**

View File

@@ -164,9 +164,9 @@ impl AlignmentPatternFinder {
Ok(*(self
.possibleCenters
.get(0)
.ok_or(Exceptions::indexOutOfBounds))?)
.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS))?)
} else {
Err(Exceptions::notFound)
Err(Exceptions::NOT_FOUND)
}
}

View File

@@ -695,7 +695,7 @@ impl<'a> FinderPatternFinder<'_> {
let startSize = self.possibleCenters.len();
if startSize < 3 {
// Couldn't find enough finder patterns
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
self.possibleCenters
@@ -712,19 +712,19 @@ impl<'a> FinderPatternFinder<'_> {
for i in 0..self.possibleCenters.len() {
let Some(fpi) = self.possibleCenters.get(i) else {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
};
let minModuleSize = fpi.getEstimatedModuleSize();
for j in (i + 1)..(self.possibleCenters.len() - 1) {
let Some(fpj) = self.possibleCenters.get(j) else {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
};
let squares0 = Self::squaredDistance(fpi, fpj);
for k in (j + 1)..(self.possibleCenters.len()) {
let Some(fpk) = self.possibleCenters.get(k) else {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
};
let maxModuleSize = fpk.getEstimatedModuleSize();
if maxModuleSize > minModuleSize * 1.4 {
@@ -776,16 +776,16 @@ impl<'a> FinderPatternFinder<'_> {
}
if distortion == f64::MAX {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
if bestPatterns[0].is_none() {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
let p1 = bestPatterns[0].ok_or(Exceptions::notFound)?;
let p2 = bestPatterns[1].ok_or(Exceptions::notFound)?;
let p3 = bestPatterns[2].ok_or(Exceptions::notFound)?;
let p1 = bestPatterns[0].ok_or(Exceptions::NOT_FOUND)?;
let p2 = bestPatterns[1].ok_or(Exceptions::NOT_FOUND)?;
let p3 = bestPatterns[2].ok_or(Exceptions::NOT_FOUND)?;
Ok([p1, p2, p3])
}

View File

@@ -103,7 +103,7 @@ impl<'a> Detector<'_> {
let moduleSize = self.calculateModuleSize(topLeft, topRight, bottomLeft);
if moduleSize < 1.0 {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
let dimension = Self::computeDimension(topLeft, topRight, bottomLeft, moduleSize)?;
let provisionalVersion = Version::getProvisionalVersionForDimension(dimension)?;
@@ -145,7 +145,7 @@ impl<'a> Detector<'_> {
alignmentPattern.as_ref(),
dimension,
)
.ok_or(Exceptions::notFound)?;
.ok_or(Exceptions::NOT_FOUND)?;
let bits = Detector::sampleGrid(self.image, &transform, dimension)?;
@@ -156,7 +156,7 @@ impl<'a> Detector<'_> {
];
if alignmentPattern.is_some() {
points.push(alignmentPattern.ok_or(Exceptions::notFound)?.into())
points.push(alignmentPattern.ok_or(Exceptions::NOT_FOUND)?.into())
}
Ok(QRCodeDetectorResult::new(bits, points))
@@ -240,7 +240,7 @@ impl<'a> Detector<'_> {
match dimension & 0x03 {
0 => dimension += 1,
2 => dimension -= 1,
3 => return Err(Exceptions::notFound),
3 => return Err(Exceptions::NOT_FOUND),
_ => {}
}
Ok(dimension as u32)
@@ -436,13 +436,13 @@ impl<'a> Detector<'_> {
let alignmentAreaLeftX = 0.max(estAlignmentX as i32 - allowance as i32) as u32;
let alignmentAreaRightX = (self.image.getWidth() - 1).min(estAlignmentX + allowance);
if ((alignmentAreaRightX - alignmentAreaLeftX) as f32) < overallEstModuleSize * 3.0 {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
let alignmentAreaTopY = 0.max(estAlignmentY as i32 - allowance as i32) as u32;
let alignmentAreaBottomY = (self.image.getHeight() - 1).min(estAlignmentY + allowance);
if alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize as u32 * 3 {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
let mut alignmentFinder = AlignmentPatternFinder::new(

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)?;

View File

@@ -80,7 +80,7 @@ impl Reader for QRCodeReader {
// if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) {
other
.downcast_ref::<QRCodeDecoderMetaData>()
.ok_or(Exceptions::illegalState)?
.ok_or(Exceptions::ILLEGAL_STATE)?
.applyMirroredCorrection(&mut points);
}
}
@@ -150,11 +150,11 @@ impl QRCodeReader {
let leftTopBlack = image.getTopLeftOnBit();
let rightBottomBlack = image.getBottomRightOnBit();
if leftTopBlack.is_none() || rightBottomBlack.is_none() {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBounds)?;
let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBounds)?;
let leftTopBlack = leftTopBlack.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::INDEX_OUT_OF_BOUNDS)?;
let moduleSize = Self::moduleSize(&leftTopBlack, image)?;
@@ -165,7 +165,7 @@ impl QRCodeReader {
// Sanity check!
if left >= right || top >= bottom {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
if bottom - top != right - left {
@@ -174,17 +174,17 @@ impl QRCodeReader {
right = left + (bottom - top);
if right >= image.getWidth() as i32 {
// Abort if that would not make sense -- off image
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
}
let matrixWidth = ((right as f32 - left as f32 + 1.0) / moduleSize).round() as u32;
let matrixHeight = ((bottom as f32 - top as f32 + 1.0) / moduleSize).round() as u32;
if matrixWidth == 0 || matrixHeight == 0 {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
if matrixHeight != matrixWidth {
// Only possibly decode square regions
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
// Push in the "border" by half the module width so that we start
@@ -202,7 +202,7 @@ impl QRCodeReader {
if nudgedTooFarRight > 0 {
if nudgedTooFarRight > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
left -= nudgedTooFarRight;
}
@@ -211,7 +211,7 @@ impl QRCodeReader {
if nudgedTooFarDown > 0 {
if nudgedTooFarDown > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
top -= nudgedTooFarDown;
}
@@ -248,7 +248,7 @@ impl QRCodeReader {
y += 1;
}
if x == width || y == height {
return Err(Exceptions::notFound);
return Err(Exceptions::NOT_FOUND);
}
Ok((x - leftTopBlack[0]) as f32 / 7.0)
}

View File

@@ -59,18 +59,18 @@ impl Writer for QRCodeWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix> {
if contents.is_empty() {
return Err(Exceptions::illegalArgumentWith("found empty contents"));
return Err(Exceptions::illegal_argument_with("found empty contents"));
}
if format != &BarcodeFormat::QR_CODE {
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"can only encode QR_CODE, but got {format:?}"
)));
// throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
}
if width < 0 || height < 0 {
return Err(Exceptions::illegalArgumentWith(format!(
return Err(Exceptions::illegal_argument_with(format!(
"requested dimensions are too small: {width}x{height}"
)));
}
@@ -87,7 +87,7 @@ impl Writer for QRCodeWriter {
if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) {
margin
.parse::<i32>()
.map_err(|e| Exceptions::parseWith(format!("could not parse {margin}: {e}")))?
.map_err(|e| Exceptions::parse_with(format!("could not parse {margin}: {e}")))?
} else {
QUIET_ZONE_SIZE
};
@@ -109,10 +109,10 @@ impl QRCodeWriter {
) -> Result<BitMatrix> {
let input = code.getMatrix();
if input.is_none() {
return Err(Exceptions::illegalStateWith("matrix is empty"));
return Err(Exceptions::illegal_state_with("matrix is empty"));
}
let input = input.as_ref().ok_or(Exceptions::illegalState)?;
let input = input.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?;
let inputWidth = input.getWidth() as i32;
let inputHeight = input.getHeight() as i32;