Merge branch 'main' into pr/point_refactor

This commit is contained in:
Vukašin Stepanović
2023-02-16 16:43:24 +00:00
132 changed files with 1048 additions and 1329 deletions

View File

@@ -39,9 +39,9 @@ impl BitMatrixParser {
pub fn new(bit_matrix: BitMatrix) -> Result<Self> {
let dimension = bit_matrix.getHeight();
if dimension < 21 || (dimension & 0x03) != 1 {
Err(Exceptions::FormatException(Some(format!(
Err(Exceptions::formatWith(format!(
"{dimension} < 21 || ({dimension} % 0x03) != 1"
))))
)))
} else {
Ok(Self {
bitMatrix: bit_matrix,
@@ -61,10 +61,7 @@ impl BitMatrixParser {
*/
pub fn readFormatInformation(&mut self) -> Result<&FormatInformation> {
if self.parsedFormatInfo.is_some() {
return self
.parsedFormatInfo
.as_ref()
.ok_or(Exceptions::ParseException(None));
return self.parsedFormatInfo.as_ref().ok_or(Exceptions::parse);
}
// Read top-left format info bits
@@ -95,9 +92,7 @@ impl BitMatrixParser {
self.parsedFormatInfo =
FormatInformation::decodeFormatInformation(formatInfoBits1, formatInfoBits2);
self.parsedFormatInfo
.as_ref()
.ok_or(Exceptions::FormatException(None))
self.parsedFormatInfo.as_ref().ok_or(Exceptions::format)
}
/**
@@ -149,7 +144,7 @@ impl BitMatrixParser {
return Ok(theParsedVersion);
}
}
Err(Exceptions::FormatException(None))
Err(Exceptions::format)
}
fn copyBit(&self, i: u32, j: u32, versionBits: u32) -> u32 {
@@ -230,7 +225,7 @@ impl BitMatrixParser {
}
if resultOffset != version.getTotalCodewords() as usize {
return Err(Exceptions::FormatException(None));
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::IllegalArgumentException(None));
return Err(Exceptions::illegalArgument);
}
// Figure out the number and size of data blocks used by this version and

View File

@@ -228,9 +228,9 @@ 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::IllegalArgumentException(Some(format!(
_ => Err(Exceptions::illegalArgumentWith(format!(
"{value} is not between 0 and 7"
)))),
))),
}
}
}

View File

@@ -78,10 +78,10 @@ pub fn decode(
}
Mode::STRUCTURED_APPEND => {
if bits.available() < 16 {
return Err(Exceptions::FormatException(Some(format!(
return Err(Exceptions::formatWith(format!(
"Mode::Structured append expected bits.available() < 16, found bits of {}",
bits.available()
))));
)));
}
// sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
@@ -93,9 +93,9 @@ pub fn decode(
let value = parseECIValue(&mut bits)?;
currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue(value).ok();
if currentCharacterSetECI.is_none() {
return Err(Exceptions::FormatException(Some(format!(
return Err(Exceptions::formatWith(format!(
"Value of {value} not valid"
))));
)));
}
}
Mode::HANZI => {
@@ -132,7 +132,7 @@ pub fn decode(
currentCharacterSetECI,
hints,
)?,
_ => return Err(Exceptions::FormatException(None)),
_ => 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::FormatException(None));
return Err(Exceptions::format);
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -203,13 +203,11 @@ fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -
count -= 1;
}
let gb_encoder = encoding::label::encoding_from_whatwg_label("GBK")
.ok_or(Exceptions::IllegalStateException(None))?;
let gb_encoder =
encoding::label::encoding_from_whatwg_label("GBK").ok_or(Exceptions::illegalState)?;
let encode_string = gb_encoder
.decode(&buffer, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::ParseException(Some(format!("unable to decode buffer {buffer:?}: {e}")))
})?;
.map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?;
result.push_str(&encode_string);
Ok(())
}
@@ -223,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::FormatException(None));
return Err(Exceptions::format);
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
@@ -252,8 +250,7 @@ fn decodeKanjiSegment(
let encoder = {
let _ = currentCharacterSetECI;
let _ = hints;
encoding::label::encoding_from_whatwg_label("SJIS")
.ok_or(Exceptions::FormatException(None))?
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)?
};
#[cfg(feature = "allow_forced_iso_ied_18004_compliance")]
@@ -266,15 +263,12 @@ fn decodeKanjiSegment(
encoding::all::ISO_8859_1
}
} else {
encoding::label::encoding_from_whatwg_label("SJIS")
.ok_or(Exceptions::FormatException(None))?
encoding::label::encoding_from_whatwg_label("SJIS").ok_or(Exceptions::format)?
};
let encode_string = encoder
.decode(&buffer, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::ParseException(Some(format!("unable to decode buffer {buffer:?}: {e}")))
})?;
.map_err(|e| Exceptions::parseWith(format!("unable to decode buffer {buffer:?}: {e}")))?;
result.push_str(&encode_string);
@@ -291,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::FormatException(None));
return Err(Exceptions::format);
}
let mut readBytes = vec![0u8; count];
@@ -307,8 +301,7 @@ fn decodeByteSegment(
// give a hint.
{
#[cfg(not(feature = "allow_forced_iso_ied_18004_compliance"))]
StringUtils::guessCharset(&readBytes, hints)
.ok_or(Exceptions::IllegalStateException(None))?
StringUtils::guessCharset(&readBytes, hints).ok_or(Exceptions::illegalState)?
}
#[cfg(feature = "allow_forced_iso_ied_18004_compliance")]
@@ -323,14 +316,14 @@ fn decodeByteSegment(
CharacterSetECI::getCharset(
currentCharacterSetECI
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?,
.ok_or(Exceptions::illegalState)?,
)
};
let encode_string = if currentCharacterSetECI.is_some()
&& currentCharacterSetECI
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalState)?
== &CharacterSetECI::Cp437
{
{
@@ -343,9 +336,7 @@ fn decodeByteSegment(
encoding
.decode(&readBytes, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::ParseException(Some(format!(
"unable to decode buffer {readBytes:?}: {e}"
)))
Exceptions::parseWith(format!("unable to decode buffer {readBytes:?}: {e}"))
})?
};
@@ -357,13 +348,13 @@ fn decodeByteSegment(
fn toAlphaNumericChar(value: u32) -> Result<char> {
if value as usize >= ALPHANUMERIC_CHARS.len() {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
ALPHANUMERIC_CHARS
.chars()
.nth(value as usize)
.ok_or(Exceptions::FormatException(None))
.ok_or(Exceptions::format)
}
fn decodeAlphanumericSegment(
@@ -377,7 +368,7 @@ fn decodeAlphanumericSegment(
let mut count = count;
while count > 1 {
if bits.available() < 11 {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
let nextTwoCharsBits = bits.readBits(11)?;
result.push(toAlphaNumericChar(nextTwoCharsBits / 45)?);
@@ -387,7 +378,7 @@ fn decodeAlphanumericSegment(
if count == 1 {
// special case: one character left
if bits.available() < 6 {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
result.push(toAlphaNumericChar(bits.readBits(6)?)?);
}
@@ -395,17 +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::IndexOutOfBoundsException(None))?
== '%'
{
if result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? == '%' {
if i < result.len() - 1
&& result
.chars()
.nth(i + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
.ok_or(Exceptions::indexOutOfBounds)?
== '%'
{
// %% is rendered as %
@@ -427,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::FormatException(None));
return Err(Exceptions::format);
}
let threeDigitsBits = bits.readBits(10)?;
if threeDigitsBits >= 1000 {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
result.push(toAlphaNumericChar(threeDigitsBits / 100)?);
result.push(toAlphaNumericChar((threeDigitsBits / 10) % 10)?);
@@ -441,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::FormatException(None));
return Err(Exceptions::format);
}
let twoDigitsBits = bits.readBits(7)?;
if twoDigitsBits >= 100 {
return Err(Exceptions::FormatException(None));
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::FormatException(None));
return Err(Exceptions::format);
}
let digitBits = bits.readBits(4)?;
if digitBits >= 10 {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
result.push(toAlphaNumericChar(digitBits)?);
}
@@ -481,5 +467,5 @@ fn parseECIValue(bits: &mut BitSource) -> Result<u32> {
return Ok(((firstByte & 0x1F) << 16) | secondThirdBytes);
}
Err(Exceptions::FormatException(None))
Err(Exceptions::format)
}

View File

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

View File

@@ -69,9 +69,9 @@ impl Mode {
{
Ok(Self::HANZI)
}
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
_ => Err(Exceptions::illegalArgumentWith(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::ChecksumException(None)))
Err(ce.unwrap_or(Exceptions::checksum))
}
}
_ => Err(er),

View File

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

View File

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

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::NotFoundException(None));
return Err(Exceptions::notFound);
}
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::NotFoundException(None));
return Err(Exceptions::notFound);
};
let minModuleSize = fpi.getEstimatedModuleSize();
for j in (i + 1)..(self.possibleCenters.len() - 1) {
let Some(fpj) = self.possibleCenters.get(j) else {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
};
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::NotFoundException(None));
return Err(Exceptions::notFound);
};
let maxModuleSize = fpk.getEstimatedModuleSize();
if maxModuleSize > minModuleSize * 1.4 {
@@ -776,16 +776,16 @@ impl<'a> FinderPatternFinder<'_> {
}
if distortion == f64::MAX {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
if bestPatterns[0].is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
let p1 = bestPatterns[0].ok_or(Exceptions::NotFoundException(None))?;
let p2 = bestPatterns[1].ok_or(Exceptions::NotFoundException(None))?;
let p3 = bestPatterns[2].ok_or(Exceptions::NotFoundException(None))?;
let p1 = bestPatterns[0].ok_or(Exceptions::notFound)?;
let p2 = bestPatterns[1].ok_or(Exceptions::notFound)?;
let p3 = bestPatterns[2].ok_or(Exceptions::notFound)?;
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::NotFoundException(None));
return Err(Exceptions::notFound);
}
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::NotFoundException(None))?;
.ok_or(Exceptions::notFound)?;
let bits = Detector::sampleGrid(self.image, &transform, dimension)?;
@@ -156,11 +156,7 @@ impl<'a> Detector<'_> {
];
if alignmentPattern.is_some() {
points.push(
alignmentPattern
.ok_or(Exceptions::NotFoundException(None))?
.into(),
)
points.push(alignmentPattern.ok_or(Exceptions::notFound)?.into())
}
Ok(QRCodeDetectorResult::new(bits, points))
@@ -244,7 +240,7 @@ impl<'a> Detector<'_> {
match dimension & 0x03 {
0 => dimension += 1,
2 => dimension -= 1,
3 => return Err(Exceptions::NotFoundException(None)),
3 => return Err(Exceptions::notFound),
_ => {}
}
Ok(dimension as u32)
@@ -440,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::NotFoundException(None));
return Err(Exceptions::notFound);
}
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::NotFoundException(None));
return Err(Exceptions::notFound);
}
let mut alignmentFinder = AlignmentPatternFinder::new(

View File

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

View File

@@ -274,11 +274,11 @@ pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMat
}
// All bits should be consumed.
if bitIndex != dataBits.getSize() {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"Not all bits consumed: {}/{}",
bitIndex,
dataBits.getSize()
))));
)));
}
Ok(())
}
@@ -319,9 +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::IllegalArgumentException(Some(
"0 polynomial".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith("0 polynomial"));
}
let mut value = value;
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
@@ -345,9 +343,7 @@ pub fn makeTypeInfoBits(
bits: &mut BitArray,
) -> Result<()> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::WriterException(Some(
"Invalid mask pattern".to_owned(),
)));
return Err(Exceptions::writerWith("Invalid mask pattern"));
}
let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
bits.appendBits(typeInfo, 5)?;
@@ -361,10 +357,10 @@ pub fn makeTypeInfoBits(
if bits.getSize() != 15 {
// Just in case.
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"should not happen but we got: {}",
bits.getSize()
))));
)));
}
Ok(())
}
@@ -378,10 +374,10 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()>
if bits.getSize() != 18 {
// Just in case.
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"should not happen but we got: {}",
bits.getSize()
))));
)));
}
Ok(())
}
@@ -411,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::WriterException(None));
return Err(Exceptions::writer);
}
matrix.set(8, matrix.getHeight() - 8, 1);
Ok(())
@@ -424,7 +420,7 @@ pub fn embedHorizontalSeparationPattern(
) -> Result<()> {
for x in 0..8 {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writer);
}
matrix.set(xStart + x, yStart, 0);
}
@@ -438,7 +434,7 @@ pub fn embedVerticalSeparationPattern(
) -> Result<()> {
for y in 0..7 {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writer);
}
matrix.set(xStart, yStart + y, 0);
}

View File

@@ -158,9 +158,9 @@ impl MinimalEncoder {
Self::getVersion(Self::getVersionSize(result.getVersion()))?,
&self.ecLevel,
) {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"Data too big for version {version}"
))));
)));
}
Ok(result)
} else {
@@ -186,9 +186,7 @@ impl MinimalEncoder {
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::WriterException(Some(
"Data too big for any version".to_owned(),
)));
return Err(Exceptions::writerWith("Data too big for any version"));
}
Ok(results[smallestRXingResult as usize].clone())
}
@@ -249,9 +247,9 @@ impl MinimalEncoder {
Some(Mode::ALPHANUMERIC) => Ok(1),
Some(Mode::BYTE) => Ok(3),
Some(Mode::KANJI) | None => Ok(0),
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
_ => Err(Exceptions::illegalArgumentWith(format!(
"Illegal mode {mode:?}"
)))),
))),
}
}
@@ -276,12 +274,9 @@ impl MinimalEncoder {
if modeEdges[modeOrdinal].is_none()
|| modeEdges[modeOrdinal]
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::format)?
.cachedTotalSize
> edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.cachedTotalSize
> edge.as_ref().ok_or(Exceptions::format)?.cachedTotalSize
{
modeEdges[modeOrdinal] = edge;
}
@@ -304,12 +299,12 @@ impl MinimalEncoder {
.encoders
.canEncode(
&self.stringToEncode[from],
priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?,
priorityEncoderIndex.ok_or(Exceptions::format)?,
)
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::format)?
{
start = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?;
end = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))? + 1;
start = priorityEncoderIndex.ok_or(Exceptions::format)?;
end = priorityEncoderIndex.ok_or(Exceptions::format)? + 1;
}
for i in start..end {
@@ -318,10 +313,10 @@ impl MinimalEncoder {
.canEncode(
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
i,
)
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::format)?
{
self.addEdge(
edges,
@@ -337,7 +332,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writer)?,
)),
)?;
}
@@ -345,9 +340,7 @@ impl MinimalEncoder {
if self.canEncode(
&Mode::KANJI,
self.stringToEncode
.get(from)
.ok_or(Exceptions::FormatException(None))?,
self.stringToEncode.get(from).ok_or(Exceptions::format)?,
) {
self.addEdge(
edges,
@@ -363,7 +356,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writer)?,
)),
)?;
}
@@ -373,7 +366,7 @@ impl MinimalEncoder {
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
) {
self.addEdge(
edges,
@@ -388,7 +381,7 @@ impl MinimalEncoder {
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
)
{
1
@@ -400,7 +393,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writer)?,
)),
)?;
}
@@ -409,7 +402,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
) {
self.addEdge(
edges,
@@ -424,7 +417,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
)
{
1
@@ -433,7 +426,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from + 2)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBounds)?,
)
{
2
@@ -445,7 +438,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writer)?,
)),
)?;
}
@@ -605,22 +598,22 @@ impl MinimalEncoder {
version,
edges[inputLength][minJ][minK]
.as_ref()
.ok_or(Exceptions::WriterException(None))?
.ok_or(Exceptions::writer)?
.clone(),
self.isGS1,
&self.ecLevel,
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?)
.ok_or(Exceptions::writer)?)
} else {
Err(Exceptions::WriterException(Some(format!(
Err(Exceptions::writerWith(format!(
r#"Internal error: failed to encode "{}"#,
self.stringToEncode
.iter()
.map(String::from)
.collect::<String>()
))))
)))
}
}
}
@@ -1030,7 +1023,7 @@ impl RXingResultNode {
bits,
self.encoders
.getCharset(self.charsetEncoderIndex)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writer)?,
)?;
}
Ok(())

View File

@@ -100,10 +100,8 @@ pub fn encode_with_hints(
let mut has_encoding_hint = hints.contains_key(&EncodeHintType::CHARACTER_SET);
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::WriterException(None))?,
)
encoding =
Some(encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writer)?)
}
}
@@ -181,9 +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::WriterException(Some(
"Data too big for requested version".to_owned(),
)));
return Err(Exceptions::writerWith("Data too big for requested version"));
}
} else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -388,9 +384,9 @@ fn chooseVersion(numInputBits: u32, ecLevel: &ErrorCorrectionLevel) -> Result<Ve
return Ok(version);
}
}
Err(Exceptions::WriterException(Some(format!(
Err(Exceptions::writerWith(format!(
"data too big {numInputBits}/{ecLevel:?}"
))))
)))
}
/**
@@ -416,9 +412,9 @@ 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::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"data bits cannot fit in the QR Code{capacity} > "
))));
)));
}
// Append Mode.TERMINATE if there is enough space (value is 0000)
for _i in 0..4 {
@@ -444,9 +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::WriterException(Some(
"Bits size does not equal capacity".to_owned(),
)));
return Err(Exceptions::writerWith("Bits size does not equal capacity"));
}
Ok(())
}
@@ -465,9 +459,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32)> {
if block_id >= num_rsblocks {
return Err(Exceptions::WriterException(Some(
"Block ID too large".to_owned(),
)));
return Err(Exceptions::writerWith("Block ID too large"));
}
// numRsBlocksInGroup2 = 196 % 5 = 1
let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks;
@@ -488,24 +480,18 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// Sanity checks.
// 26 = 26
if num_ec_bytes_in_group1 != numEcBytesInGroup2 {
return Err(Exceptions::WriterException(Some(
"EC bytes mismatch".to_owned(),
)));
return Err(Exceptions::writerWith("EC bytes mismatch"));
}
// 5 = 4 + 1.
if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 {
return Err(Exceptions::WriterException(Some(
"RS blocks mismatch".to_owned(),
)));
return Err(Exceptions::writerWith("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::WriterException(Some(
"total bytes mismatch".to_owned(),
)));
return Err(Exceptions::writerWith("total bytes mismatch"));
}
Ok(if block_id < num_rs_blocks_in_group1 {
@@ -527,9 +513,9 @@ pub fn interleaveWithECBytes(
) -> Result<BitArray> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::WriterException(Some(
"Number of bits and data bytes does not match".to_owned(),
)));
return Err(Exceptions::writerWith(
"Number of bits and data bytes does not match",
));
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
@@ -562,9 +548,7 @@ pub fn interleaveWithECBytes(
data_bytes_offset += numDataBytesInBlock as usize;
}
if num_data_bytes != data_bytes_offset as u32 {
return Err(Exceptions::WriterException(Some(
"Data bytes does not match offset".to_owned(),
)));
return Err(Exceptions::writerWith("Data bytes does not match offset"));
}
let mut result = BitArray::new();
@@ -589,11 +573,11 @@ pub fn interleaveWithECBytes(
}
if num_total_bytes != result.getSizeInBytes() as u32 {
// Should be same.
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"Interleaving error: {} and {} differ.",
num_total_bytes,
result.getSizeInBytes()
))));
)));
}
Ok(result)
@@ -636,11 +620,11 @@ pub fn appendLengthInfo(
) -> Result<()> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"{} is bigger than {}",
num_letters,
((1 << numBits) - 1)
))));
)));
}
bits.appendBits(num_letters, numBits as usize)
}
@@ -659,9 +643,7 @@ pub fn appendBytes(
Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits),
Mode::BYTE => append8BitBytes(content, bits, encoding),
Mode::KANJI => appendKanjiBytes(content, bits),
_ => Err(Exceptions::WriterException(Some(format!(
"Invalid mode: {mode:?}"
)))),
_ => Err(Exceptions::writerWith(format!("Invalid mode: {mode:?}"))),
}
}
@@ -669,22 +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::IndexOutOfBoundsException(None))? as u8
- b'0';
let num1 = content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? 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::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBounds)? as u8
- b'0';
let num3 = content
.chars()
.nth(i + 2)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBounds)? as u8
- b'0';
bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?;
i += 3;
@@ -693,7 +671,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let num2 = content
.chars()
.nth(i + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBounds)? as u8
- b'0';
bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?;
i += 2;
@@ -710,24 +688,20 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()>
let length = content.len();
let mut i = 0;
while i < length {
let code1 = getAlphanumericCode(
content
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32,
);
let code1 =
getAlphanumericCode(content.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32);
if code1 == -1 {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writer);
}
if i + 1 < length {
let code2 = getAlphanumericCode(
content
.chars()
.nth(i + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32,
.ok_or(Exceptions::indexOutOfBounds)? as u32,
);
if code2 == -1 {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writer);
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?;
@@ -744,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::WriterException(Some(format!("error {e}"))))?;
.map_err(|e| Exceptions::writerWith(format!("error {e}")))?;
for b in bytes {
bits.appendBits(b as u32, 8)?;
}
@@ -756,11 +730,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let bytes = sjis
.encode(content, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?;
.map_err(|e| Exceptions::writerWith(format!("error {e}")))?;
if bytes.len() % 2 != 0 {
return Err(Exceptions::WriterException(Some(
"Kanji byte size not even".to_owned(),
)));
return Err(Exceptions::writerWith("Kanji byte size not even"));
}
let max_i = bytes.len() - 1; // bytes.length must be even
let mut i = 0;
@@ -775,9 +747,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> {
subtracted = code as i32 - 0xc140;
}
if subtracted == -1 {
return Err(Exceptions::WriterException(Some(
"Invalid byte sequence".to_owned(),
)));
return Err(Exceptions::writerWith("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::IllegalStateException(None))?
.ok_or(Exceptions::illegalState)?
.applyMirroredCorrection(&mut points);
}
}
@@ -150,12 +150,11 @@ impl QRCodeReader {
let leftTopBlack = image.getTopLeftOnBit();
let rightBottomBlack = image.getBottomRightOnBit();
if leftTopBlack.is_none() || rightBottomBlack.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
let leftTopBlack = leftTopBlack.ok_or(Exceptions::IndexOutOfBoundsException(None))?;
let rightBottomBlack =
rightBottomBlack.ok_or(Exceptions::IndexOutOfBoundsException(None))?;
let leftTopBlack = leftTopBlack.ok_or(Exceptions::indexOutOfBounds)?;
let rightBottomBlack = rightBottomBlack.ok_or(Exceptions::indexOutOfBounds)?;
let moduleSize = Self::moduleSize(&leftTopBlack, image)?;
@@ -166,7 +165,7 @@ impl QRCodeReader {
// Sanity check!
if left >= right || top >= bottom {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
if bottom - top != right - left {
@@ -175,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::NotFoundException(None));
return Err(Exceptions::notFound);
}
}
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::NotFoundException(None));
return Err(Exceptions::notFound);
}
if matrixHeight != matrixWidth {
// Only possibly decode square regions
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
// Push in the "border" by half the module width so that we start
@@ -203,7 +202,7 @@ impl QRCodeReader {
if nudgedTooFarRight > 0 {
if nudgedTooFarRight > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
left -= nudgedTooFarRight;
}
@@ -212,7 +211,7 @@ impl QRCodeReader {
if nudgedTooFarDown > 0 {
if nudgedTooFarDown > nudge as i32 {
// Neither way fits; abort
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
top -= nudgedTooFarDown;
}
@@ -249,7 +248,7 @@ impl QRCodeReader {
y += 1;
}
if x == width || y == height {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}
Ok((x - leftTopBlack[0]) as f32 / 7.0)
}

View File

@@ -59,22 +59,20 @@ impl Writer for QRCodeWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix> {
if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(
"found empty contents".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith("found empty contents"));
}
if format != &BarcodeFormat::QR_CODE {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgumentWith(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::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"requested dimensions are too small: {width}x{height}"
))));
)));
}
let errorCorrectionLevel = if let Some(EncodeHintValue::ErrorCorrection(ec_level)) =
@@ -87,9 +85,9 @@ impl Writer for QRCodeWriter {
let quietZone =
if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) {
margin.parse::<i32>().map_err(|e| {
Exceptions::ParseException(Some(format!("could not parse {margin}: {e}")))
})?
margin
.parse::<i32>()
.map_err(|e| Exceptions::parseWith(format!("could not parse {margin}: {e}")))?
} else {
QUIET_ZONE_SIZE
};
@@ -111,14 +109,10 @@ impl QRCodeWriter {
) -> Result<BitMatrix> {
let input = code.getMatrix();
if input.is_none() {
return Err(Exceptions::IllegalStateException(Some(
"matrix is empty".to_owned(),
)));
return Err(Exceptions::illegalStateWith("matrix is empty"));
}
let input = input
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?;
let input = input.as_ref().ok_or(Exceptions::illegalState)?;
let inputWidth = input.getWidth() as i32;
let inputHeight = input.getHeight() as i32;