refactor to use common result type

This commit is contained in:
Vukašin Stepanović
2023-02-14 22:56:03 +00:00
parent 145cf704fe
commit 8ee616d96b
160 changed files with 829 additions and 901 deletions

View File

@@ -15,8 +15,8 @@
*/
use crate::{
common::Result,
qrcode::decoder::{ErrorCorrectionLevel, Version},
Exceptions,
};
/**
@@ -37,7 +37,7 @@ fn testVersionForNumber() {
}
}
fn checkVersion(version: Result<&Version, Exceptions>, number: u32, dimension: u32) {
fn checkVersion(version: Result<&Version>, number: u32, dimension: u32) {
assert!(version.is_ok());
let version = version.unwrap();
assert_eq!(number, version.getVersionNumber());

View File

@@ -14,7 +14,10 @@
* limitations under the License.
*/
use crate::{common::BitMatrix, Exceptions};
use crate::{
common::{BitMatrix, Result},
Exceptions,
};
use super::{DataMask, FormatInformation, Version, VersionRef};
@@ -33,7 +36,7 @@ impl BitMatrixParser {
* @param bitMatrix {@link BitMatrix} to parse
* @throws FormatException if dimension is not >= 21 and 1 mod 4
*/
pub fn new(bit_matrix: BitMatrix) -> Result<Self, Exceptions> {
pub fn new(bit_matrix: BitMatrix) -> Result<Self> {
let dimension = bit_matrix.getHeight();
if dimension < 21 || (dimension & 0x03) != 1 {
Err(Exceptions::FormatException(Some(format!(
@@ -56,7 +59,7 @@ impl BitMatrixParser {
* @throws FormatException if both format information locations cannot be parsed as
* the valid encoding of format information
*/
pub fn readFormatInformation(&mut self) -> Result<&FormatInformation, Exceptions> {
pub fn readFormatInformation(&mut self) -> Result<&FormatInformation> {
if self.parsedFormatInfo.is_some() {
return self
.parsedFormatInfo
@@ -104,7 +107,7 @@ impl BitMatrixParser {
* @throws FormatException if both version information locations cannot be parsed as
* the valid encoding of version information
*/
pub fn readVersion(&mut self) -> Result<VersionRef, Exceptions> {
pub fn readVersion(&mut self) -> Result<VersionRef> {
if let Some(pv) = self.parsedVersion {
return Ok(pv);
}
@@ -171,7 +174,7 @@ impl BitMatrixParser {
* @return bytes encoded within the QR Code
* @throws FormatException if the exact number of bytes expected is not read
*/
pub fn readCodewords(&mut self) -> Result<Vec<u8>, Exceptions> {
pub fn readCodewords(&mut self) -> Result<Vec<u8>> {
let version = self.readVersion()?;
// Get the data mask for the format used in this QR Code. This will exclude
@@ -235,7 +238,7 @@ impl BitMatrixParser {
/**
* Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
*/
pub fn remask(&mut self) -> Result<(), Exceptions> {
pub fn remask(&mut self) -> Result<()> {
if let Some(pfi) = &self.parsedFormatInfo {
let dataMask: DataMask = pfi.getDataMask().try_into()?;
let dimension = self.bitMatrix.getHeight();

View File

@@ -14,6 +14,7 @@
* limitations under the License.
*/
use crate::common::Result;
use crate::Exceptions;
use super::{ErrorCorrectionLevel, VersionRef};
@@ -53,7 +54,7 @@ impl DataBlock {
rawCodewords: &[u8],
version: VersionRef,
ecLevel: ErrorCorrectionLevel,
) -> Result<Vec<Self>, Exceptions> {
) -> Result<Vec<Self>> {
if rawCodewords.len() as u32 != version.getTotalCodewords() {
return Err(Exceptions::IllegalArgumentException(None));
}

View File

@@ -15,7 +15,7 @@
*/
use crate::{
common::{BitSource, CharacterSetECI, DecoderRXingResult, StringUtils},
common::{BitSource, CharacterSetECI, DecoderRXingResult, Result, StringUtils},
DecodingHintDictionary, Exceptions,
};
@@ -44,7 +44,7 @@ pub fn decode(
version: VersionRef,
ecLevel: ErrorCorrectionLevel,
hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> {
) -> Result<DecoderRXingResult> {
let mut bits = BitSource::new(bytes.to_owned());
let mut result = String::with_capacity(50);
let mut byteSegments = vec![vec![0u8; 0]; 0];
@@ -174,11 +174,7 @@ pub fn decode(
/**
* See specification GBT 18284-2000
*/
fn decodeHanziSegment(
bits: &mut BitSource,
result: &mut String,
count: usize,
) -> Result<(), Exceptions> {
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));
@@ -224,7 +220,7 @@ fn decodeKanjiSegment(
count: usize,
currentCharacterSetECI: Option<CharacterSetECI>,
hints: &DecodingHintDictionary,
) -> Result<(), Exceptions> {
) -> Result<()> {
// Don't crash trying to read more bits than we have available.
if count * 13 > bits.available() {
return Err(Exceptions::FormatException(None));
@@ -292,7 +288,7 @@ fn decodeByteSegment(
currentCharacterSetECI: Option<CharacterSetECI>,
byteSegments: &mut Vec<Vec<u8>>,
hints: &DecodingHintDictionary,
) -> Result<(), Exceptions> {
) -> Result<()> {
// Don't crash trying to read more bits than we have available.
if 8 * count > bits.available() {
return Err(Exceptions::FormatException(None));
@@ -359,7 +355,7 @@ fn decodeByteSegment(
Ok(())
}
fn toAlphaNumericChar(value: u32) -> Result<char, Exceptions> {
fn toAlphaNumericChar(value: u32) -> Result<char> {
if value as usize >= ALPHANUMERIC_CHARS.len() {
return Err(Exceptions::FormatException(None));
}
@@ -375,7 +371,7 @@ fn decodeAlphanumericSegment(
result: &mut String,
count: usize,
fc1InEffect: bool,
) -> Result<(), Exceptions> {
) -> Result<()> {
// Read two characters at a time
let start = result.len();
let mut count = count;
@@ -425,11 +421,7 @@ fn decodeAlphanumericSegment(
Ok(())
}
fn decodeNumericSegment(
bits: &mut BitSource,
result: &mut String,
count: usize,
) -> Result<(), Exceptions> {
fn decodeNumericSegment(bits: &mut BitSource, result: &mut String, count: usize) -> Result<()> {
let mut count = count;
// Read three digits at a time
while count >= 3 {
@@ -472,7 +464,7 @@ fn decodeNumericSegment(
Ok(())
}
fn parseECIValue(bits: &mut BitSource) -> Result<u32, Exceptions> {
fn parseECIValue(bits: &mut BitSource) -> Result<u32> {
let firstByte = bits.readBits(8)?;
if (firstByte & 0x80) == 0 {
// just one byte

View File

@@ -16,6 +16,7 @@
use std::str::FromStr;
use crate::common::Result;
use crate::Exceptions;
/**
@@ -41,7 +42,7 @@ impl ErrorCorrectionLevel {
* @param bits int containing the two bits encoding a QR Code's error correction level
* @return ErrorCorrectionLevel representing the encoded error correction level
*/
pub fn forBits(bits: u8) -> Result<Self, Exceptions> {
pub fn forBits(bits: u8) -> Result<Self> {
match bits {
0 => Ok(Self::M),
1 => Ok(Self::L),

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
use crate::Exceptions;
use crate::common::Result;
use super::ErrorCorrectionLevel;
@@ -73,7 +73,7 @@ pub struct FormatInformation {
}
impl FormatInformation {
fn new(format_info: u8) -> Result<Self, Exceptions> {
fn new(format_info: u8) -> Result<Self> {
// Bits 3,4
let errorCorrectionLevel = ErrorCorrectionLevel::forBits((format_info >> 3) & 0x03)?;
// Bottom 3 bits

View File

@@ -14,6 +14,7 @@
* limitations under the License.
*/
use crate::common::Result;
use crate::Exceptions;
use super::Version;
@@ -52,7 +53,7 @@ impl Mode {
* @return Mode encoded by these bits
* @throws IllegalArgumentException if bits do not correspond to a known mode
*/
pub fn forBits(bits: u8) -> Result<Self, Exceptions> {
pub fn forBits(bits: u8) -> Result<Self> {
match bits {
0x0 => Ok(Self::TERMINATOR),
0x1 => Ok(Self::NUMERIC),

View File

@@ -27,7 +27,7 @@ use once_cell::sync::Lazy;
use crate::{
common::{
reedsolomon::get_predefined_genericgf, reedsolomon::PredefinedGenericGF,
reedsolomon::ReedSolomonDecoder, BitMatrix, DecoderRXingResult,
reedsolomon::ReedSolomonDecoder, BitMatrix, DecoderRXingResult, Result,
},
DecodingHintDictionary, Exceptions,
};
@@ -41,7 +41,7 @@ static RS_DECODER: Lazy<ReedSolomonDecoder> = Lazy::new(|| {
))
});
pub fn decode_bool_array(image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> {
pub fn decode_bool_array(image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult> {
decode_bool_array_with_hints(image, &HashMap::new())
}
@@ -58,11 +58,11 @@ pub fn decode_bool_array(image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, E
pub fn decode_bool_array_with_hints(
image: &Vec<Vec<bool>>,
hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> {
) -> Result<DecoderRXingResult> {
decode_bitmatrix_with_hints(&BitMatrix::parse_bools(image), hints)
}
pub fn decode_bitmatrix(bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> {
pub fn decode_bitmatrix(bits: &BitMatrix) -> Result<DecoderRXingResult> {
decode_bitmatrix_with_hints(bits, &HashMap::new())
}
@@ -78,7 +78,7 @@ pub fn decode_bitmatrix(bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptio
pub fn decode_bitmatrix_with_hints(
bits: &BitMatrix,
hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> {
) -> Result<DecoderRXingResult> {
// Construct a parser and read version, error-correction level
let mut parser = BitMatrixParser::new(bits.clone())?;
let mut fe = None;
@@ -92,7 +92,7 @@ pub fn decode_bitmatrix_with_hints(
},
}
let mut trying = || -> Result<DecoderRXingResult, Exceptions> {
let mut trying = || -> Result<DecoderRXingResult> {
// Revert the bit matrix
parser.remask()?;
@@ -140,7 +140,7 @@ pub fn decode_bitmatrix_with_hints(
fn decode_bitmatrix_parser_with_hints(
parser: &mut BitMatrixParser,
hints: &DecodingHintDictionary,
) -> Result<DecoderRXingResult, Exceptions> {
) -> Result<DecoderRXingResult> {
let version = parser.readVersion()?;
let ecLevel = parser.readFormatInformation()?.getErrorCorrectionLevel();
@@ -180,7 +180,7 @@ fn decode_bitmatrix_parser_with_hints(
* @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails
*/
fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<(), Exceptions> {
fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<()> {
let numCodewords = codewordBytes.len();
// First read into an array of ints
let mut codewordsInts = vec![0u8; numCodewords];

View File

@@ -16,7 +16,10 @@
use std::fmt;
use crate::{common::BitMatrix, Exceptions};
use crate::{
common::{BitMatrix, Result},
Exceptions,
};
use super::{ErrorCorrectionLevel, FormatInformation};
@@ -97,9 +100,7 @@ impl Version {
* @return Version for a QR Code of that dimension
* @throws FormatException if dimension is not 1 mod 4
*/
pub fn getProvisionalVersionForDimension(
dimension: u32,
) -> Result<&'static Version, Exceptions> {
pub fn getProvisionalVersionForDimension(dimension: u32) -> Result<&'static Version> {
if dimension % 4 != 1 {
return Err(Exceptions::FormatException(Some(
"dimension incorrect".to_owned(),
@@ -108,7 +109,7 @@ impl Version {
Self::getVersionForNumber((dimension - 17) / 4)
}
pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version, Exceptions> {
pub fn getVersionForNumber(versionNumber: u32) -> Result<&'static Version> {
if !(1..=40).contains(&versionNumber) {
return Err(Exceptions::IllegalArgumentException(Some(
"version out of spec".to_owned(),
@@ -117,7 +118,7 @@ impl Version {
Ok(&VERSIONS[versionNumber as usize - 1])
}
pub fn decodeVersionInformation(versionBits: u32) -> Result<&'static Version, Exceptions> {
pub fn decodeVersionInformation(versionBits: u32) -> Result<&'static Version> {
let mut bestDifference = u32::MAX;
let mut bestVersion = 0;
for i in 0..VERSION_DECODE_INFO.len() as u32 {
@@ -146,7 +147,7 @@ impl Version {
/**
* See ISO 18004:2006 Annex E
*/
pub fn buildFunctionPattern(&self) -> Result<BitMatrix, Exceptions> {
pub fn buildFunctionPattern(&self) -> Result<BitMatrix> {
let dimension = self.getDimensionForVersion();
let mut bitMatrix = BitMatrix::with_single_dimension(dimension)?;

View File

@@ -14,7 +14,10 @@
* limitations under the License.
*/
use crate::{common::BitMatrix, Exceptions, RXingResultPointCallback};
use crate::{
common::{BitMatrix, Result},
Exceptions, RXingResultPointCallback,
};
use super::AlignmentPattern;
@@ -84,7 +87,7 @@ impl AlignmentPatternFinder {
* @return {@link AlignmentPattern} if found
* @throws NotFoundException if not found
*/
pub fn find(&mut self) -> Result<AlignmentPattern, Exceptions> {
pub fn find(&mut self) -> Result<AlignmentPattern> {
let startX = self.startX;
let height = self.height;
let maxJ = startX + self.width;

View File

@@ -15,8 +15,9 @@
*/
use crate::{
common::BitMatrix, result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary,
Exceptions, RXingResultPointCallback, ResultPoint,
common::{BitMatrix, Result},
result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
RXingResultPointCallback, ResultPoint,
};
use super::{FinderPattern, FinderPatternInfo};
@@ -71,10 +72,7 @@ impl<'a> FinderPatternFinder<'_> {
&self.possibleCenters
}
pub fn find(
&mut self,
hints: &DecodingHintDictionary,
) -> Result<FinderPatternInfo, Exceptions> {
pub fn find(&mut self, hints: &DecodingHintDictionary) -> Result<FinderPatternInfo> {
let tryHarder = matches!(
hints.get(&DecodeHintType::TRY_HARDER),
Some(DecodeHintValue::TryHarder(true))
@@ -692,7 +690,7 @@ impl<'a> FinderPatternFinder<'_> {
* those have similar module size and form a shape closer to a isosceles right triangle.
* @throws NotFoundException if 3 such finder patterns do not exist
*/
fn selectBestPatterns(&mut self) -> Result<[FinderPattern; 3], Exceptions> {
fn selectBestPatterns(&mut self) -> Result<[FinderPattern; 3]> {
let startSize = self.possibleCenters.len();
if startSize < 3 {
// Couldn't find enough finder patterns

View File

@@ -19,6 +19,7 @@ use std::collections::HashMap;
use crate::{
common::{
detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler, PerspectiveTransform,
Result,
},
qrcode::decoder::Version,
result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
@@ -64,7 +65,7 @@ impl<'a> Detector<'_> {
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/
pub fn detect(&mut self) -> Result<QRCodeDetectorResult, Exceptions> {
pub fn detect(&mut self) -> Result<QRCodeDetectorResult> {
self.detect_with_hints(&HashMap::new())
}
@@ -79,7 +80,7 @@ impl<'a> Detector<'_> {
pub fn detect_with_hints(
&mut self,
hints: &DecodingHintDictionary,
) -> Result<QRCodeDetectorResult, Exceptions> {
) -> Result<QRCodeDetectorResult> {
self.resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) =
hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK)
{
@@ -98,7 +99,7 @@ impl<'a> Detector<'_> {
pub fn processFinderPatternInfo(
&self,
info: FinderPatternInfo,
) -> Result<QRCodeDetectorResult, Exceptions> {
) -> Result<QRCodeDetectorResult> {
let topLeft = info.getTopLeft();
let topRight = info.getTopRight();
let bottomLeft = info.getBottomLeft();
@@ -218,7 +219,7 @@ impl<'a> Detector<'_> {
image: &BitMatrix,
transform: &PerspectiveTransform,
dimension: u32,
) -> Result<BitMatrix, Exceptions> {
) -> Result<BitMatrix> {
let sampler = DefaultGridSampler::default();
sampler.sample_grid(image, dimension, dimension, transform)
}
@@ -232,7 +233,7 @@ impl<'a> Detector<'_> {
topRight: &T,
bottomLeft: &T,
moduleSize: f32,
) -> Result<u32, Exceptions> {
) -> Result<u32> {
let tltrCentersDimension =
MathUtils::round(result_point_utils::distance(topLeft, topRight) / moduleSize);
let tlblCentersDimension =
@@ -421,7 +422,7 @@ impl<'a> Detector<'_> {
estAlignmentX: u32,
estAlignmentY: u32,
allowanceFactor: f32,
) -> Result<AlignmentPattern, Exceptions> {
) -> Result<AlignmentPattern> {
// Look for an alignment pattern (3 modules in size) around where it
// should be
let allowance = (allowanceFactor * overallEstModuleSize) as u32;

View File

@@ -14,6 +14,7 @@
* limitations under the License.
*/
use crate::common::Result;
use crate::Exceptions;
use super::ByteMatrix;
@@ -154,7 +155,7 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 {
* Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
* pattern conditions.
*/
pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result<bool, Exceptions> {
pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result<bool> {
let intermediate = match maskPattern {
0 => (y + x) & 0x1,
1 => y & 0x1,

View File

@@ -15,7 +15,7 @@
*/
use crate::{
common::BitArray,
common::{BitArray, Result},
qrcode::decoder::{ErrorCorrectionLevel, Version},
Exceptions,
};
@@ -131,7 +131,7 @@ pub fn buildMatrix(
version: &Version,
maskPattern: i32,
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
) -> Result<()> {
clearMatrix(matrix);
embedBasicPatterns(version, matrix)?;
// Type information appear with any version.
@@ -149,7 +149,7 @@ pub fn buildMatrix(
// - Timing patterns
// - Dark dot at the left bottom corner
// - Position adjustment patterns, if need be
pub fn embedBasicPatterns(version: &Version, matrix: &mut ByteMatrix) -> Result<(), Exceptions> {
pub fn embedBasicPatterns(version: &Version, matrix: &mut ByteMatrix) -> Result<()> {
// Let's get started with embedding big squares at corners.
embedPositionDetectionPatternsAndSeparators(matrix)?;
// Then, embed the dark dot at the left bottom corner.
@@ -167,7 +167,7 @@ pub fn embedTypeInfo(
ecLevel: &ErrorCorrectionLevel,
maskPattern: i32,
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
) -> Result<()> {
let mut typeInfoBits = BitArray::new();
makeTypeInfoBits(ecLevel, maskPattern as u32, &mut typeInfoBits)?;
@@ -204,7 +204,7 @@ pub fn embedTypeInfo(
// Embed version information if need be. On success, modify the matrix and return true.
// See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Result<(), Exceptions> {
pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Result<()> {
if version.getVersionNumber() < 7 {
// Version info is necessary if version >= 7.
return Ok(()); // Don't need version info.
@@ -230,11 +230,7 @@ pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Resu
// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
// For debugging purposes, it skips masking process if "getMaskPattern" is -1.
// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
pub fn embedDataBits(
dataBits: &BitArray,
maskPattern: i32,
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMatrix) -> Result<()> {
let mut bitIndex = 0;
let mut direction: i32 = -1;
// Start from the right bottom cell.
@@ -321,7 +317,7 @@ pub fn findMSBSet(value: u32) -> u32 {
//
// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
// operations. We don't care if coefficients are positive or negative.
pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32, Exceptions> {
pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32> {
if poly == 0 {
return Err(Exceptions::IllegalArgumentException(Some(
"0 polynomial".to_owned(),
@@ -347,7 +343,7 @@ pub fn makeTypeInfoBits(
ecLevel: &ErrorCorrectionLevel,
maskPattern: u32,
bits: &mut BitArray,
) -> Result<(), Exceptions> {
) -> Result<()> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::WriterException(Some(
"Invalid mask pattern".to_owned(),
@@ -375,7 +371,7 @@ pub fn makeTypeInfoBits(
// Make bit vector of version information. On success, store the result in "bits" and return true.
// See 8.10 of JISX0510:2004 (p.45) for details.
pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()> {
bits.appendBits(version.getVersionNumber(), 6)?;
let bchCode = calculateBCHCode(version.getVersionNumber(), VERSION_INFO_POLY)?;
bits.appendBits(bchCode, 12)?;
@@ -413,7 +409,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<(), Exceptions> {
pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<()> {
if matrix.get(8, matrix.getHeight() - 8) == 0 {
return Err(Exceptions::WriterException(None));
}
@@ -425,7 +421,7 @@ pub fn embedHorizontalSeparationPattern(
xStart: u32,
yStart: u32,
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
) -> Result<()> {
for x in 0..8 {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::WriterException(None));
@@ -439,7 +435,7 @@ pub fn embedVerticalSeparationPattern(
xStart: u32,
yStart: u32,
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
) -> Result<()> {
for y in 0..7 {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::WriterException(None));
@@ -466,9 +462,7 @@ pub fn embedPositionDetectionPattern(xStart: u32, yStart: u32, matrix: &mut Byte
}
// Embed position detection patterns and surrounding vertical/horizontal separators.
pub fn embedPositionDetectionPatternsAndSeparators(
matrix: &mut ByteMatrix,
) -> Result<(), Exceptions> {
pub fn embedPositionDetectionPatternsAndSeparators(matrix: &mut ByteMatrix) -> Result<()> {
// Embed three big squares at corners.
let pdpWidth = POSITION_DETECTION_PATTERN[0].len() as u32;
// Left top corner.

View File

@@ -19,7 +19,7 @@ use std::{fmt, rc::Rc};
use encoding::EncodingRef;
use crate::{
common::{BitArray, ECIEncoderSet},
common::{BitArray, ECIEncoderSet, Result},
qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef},
Exceptions,
};
@@ -145,11 +145,11 @@ impl MinimalEncoder {
priorityCharset: Option<EncodingRef>,
isGS1: bool,
ecLevel: ErrorCorrectionLevel,
) -> Result<RXingResultList, Exceptions> {
) -> Result<RXingResultList> {
MinimalEncoder::new(stringToEncode, priorityCharset, isGS1, ecLevel).encode(version)
}
pub fn encode(&self, version: Option<VersionRef>) -> Result<RXingResultList, Exceptions> {
pub fn encode(&self, version: Option<VersionRef>) -> Result<RXingResultList> {
if let Some(version) = version {
// compute minimal encoding for a given version
let result = self.encodeSpecificVersion(version)?;
@@ -202,7 +202,7 @@ impl MinimalEncoder {
}
}
pub fn getVersion(versionSize: VersionSize) -> Result<VersionRef, Exceptions> {
pub fn getVersion(versionSize: VersionSize) -> Result<VersionRef> {
match versionSize {
VersionSize::SMALL => Version::getVersionForNumber(9),
VersionSize::MEDIUM => Version::getVersionForNumber(26),
@@ -243,7 +243,7 @@ impl MinimalEncoder {
}
}
pub fn getCompactedOrdinal(mode: Option<Mode>) -> Result<u32, Exceptions> {
pub fn getCompactedOrdinal(mode: Option<Mode>) -> Result<u32> {
match mode {
Some(Mode::NUMERIC) => Ok(2),
Some(Mode::ALPHANUMERIC) => Ok(1),
@@ -260,7 +260,7 @@ impl MinimalEncoder {
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
position: usize,
edge: Option<Rc<Edge>>,
) -> Result<(), Exceptions> {
) -> Result<()> {
let vertexIndex = position
+ edge
.as_ref()
@@ -295,7 +295,7 @@ impl MinimalEncoder {
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
from: usize,
previous: Option<Rc<Edge>>,
) -> Result<(), Exceptions> {
) -> Result<()> {
let mut start = 0;
let mut end = self.encoders.len();
let priorityEncoderIndex = self.encoders.getPriorityEncoderIndex();
@@ -452,10 +452,7 @@ impl MinimalEncoder {
Ok(())
}
pub fn encodeSpecificVersion(
&self,
version: VersionRef,
) -> Result<RXingResultList, Exceptions> {
pub fn encodeSpecificVersion(&self, version: VersionRef) -> Result<RXingResultList> {
// @SuppressWarnings("checkstyle:lineLength")
/* A vertex represents a tuple of a position in the input, a mode and a character encoding where position 0
* denotes the position left of the first character, 1 the position left of the second character and so on.
@@ -869,7 +866,7 @@ impl RXingResultList {
/**
* appends the bits
*/
pub fn getBits(&self, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn getBits(&self, bits: &mut BitArray) -> Result<()> {
for resultNode in &self.list {
resultNode.getBits(bits)?;
}
@@ -1008,7 +1005,7 @@ impl RXingResultNode {
/**
* appends the bits
*/
fn getBits(&self, bits: &mut BitArray) -> Result<(), Exceptions> {
fn getBits(&self, bits: &mut BitArray) -> Result<()> {
bits.appendBits(self.mode.getBits() as u32, 4)?;
if self.characterLength > 0 {
let length = self.getCharacterCountIndicator();

View File

@@ -27,7 +27,7 @@ use unicode_segmentation::UnicodeSegmentation;
use crate::{
common::{
reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonEncoder},
BitArray, CharacterSetECI,
BitArray, CharacterSetECI, Result,
},
qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef},
EncodeHintType, EncodeHintValue, EncodingHintDictionary, Exceptions,
@@ -66,7 +66,7 @@ pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 {
* @throws WriterException if encoding can't succeed, because of for example invalid content
* or configuration
*/
pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result<QRCode, Exceptions> {
pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result<QRCode> {
encode_with_hints(content, ecLevel, &HashMap::new())
}
@@ -74,7 +74,7 @@ pub fn encode_with_hints(
content: &str,
ec_level: ErrorCorrectionLevel,
hints: &EncodingHintDictionary,
) -> Result<QRCode, Exceptions> {
) -> Result<QRCode> {
let version;
let mut header_and_data_bits;
let mode;
@@ -264,7 +264,7 @@ fn recommendVersion(
mode: Mode,
header_bits: &BitArray,
data_bits: &BitArray,
) -> Result<VersionRef, Exceptions> {
) -> Result<VersionRef> {
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
@@ -365,7 +365,7 @@ fn chooseMaskPattern(
ec_level: &ErrorCorrectionLevel,
version: VersionRef,
matrix: &mut ByteMatrix,
) -> Result<u32, Exceptions> {
) -> Result<u32> {
let mut min_penalty = u32::MAX; // Lower penalty is better.
let mut best_mask_pattern = -1;
// We try all mask patterns to choose the best one.
@@ -381,10 +381,7 @@ fn chooseMaskPattern(
Ok(best_mask_pattern as u32)
}
fn chooseVersion(
numInputBits: u32,
ecLevel: &ErrorCorrectionLevel,
) -> Result<VersionRef, Exceptions> {
fn chooseVersion(numInputBits: u32, ecLevel: &ErrorCorrectionLevel) -> Result<VersionRef> {
for versionNum in 1..=40 {
let version = Version::getVersionForNumber(versionNum)?;
if willFit(numInputBits, version, ecLevel) {
@@ -416,7 +413,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
/**
* Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
*/
pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> {
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!(
@@ -466,7 +463,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
block_id: u32,
// numDataBytesInBlock: &mut [u32],
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32), Exceptions> {
) -> Result<(u32, u32)> {
if block_id >= num_rsblocks {
return Err(Exceptions::WriterException(Some(
"Block ID too large".to_owned(),
@@ -527,7 +524,7 @@ pub fn interleaveWithECBytes(
num_total_bytes: u32,
num_data_bytes: u32,
num_rsblocks: u32,
) -> Result<BitArray, Exceptions> {
) -> Result<BitArray> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::WriterException(Some(
@@ -602,10 +599,7 @@ pub fn interleaveWithECBytes(
Ok(result)
}
pub fn generateECBytes(
dataBytes: &[u8],
num_ec_bytes_in_block: usize,
) -> Result<Vec<u8>, Exceptions> {
pub fn generateECBytes(dataBytes: &[u8], num_ec_bytes_in_block: usize) -> Result<Vec<u8>> {
let num_data_bytes = dataBytes.len();
let mut to_encode = vec![0; num_data_bytes + num_ec_bytes_in_block];
for i in 0..num_data_bytes {
@@ -627,7 +621,7 @@ pub fn generateECBytes(
/**
* Append mode info. On success, store the result in "bits".
*/
pub fn appendModeInfo(mode: Mode, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn appendModeInfo(mode: Mode, bits: &mut BitArray) -> Result<()> {
bits.appendBits(mode.getBits() as u32, 4)
}
@@ -639,7 +633,7 @@ pub fn appendLengthInfo(
version: VersionRef,
mode: Mode,
bits: &mut BitArray,
) -> Result<(), Exceptions> {
) -> Result<()> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::WriterException(Some(format!(
@@ -659,7 +653,7 @@ pub fn appendBytes(
mode: Mode,
bits: &mut BitArray,
encoding: EncodingRef,
) -> Result<(), Exceptions> {
) -> Result<()> {
match mode {
Mode::NUMERIC => appendNumericBytes(content, bits),
Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits),
@@ -671,7 +665,7 @@ pub fn appendBytes(
}
}
pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let length = content.len();
let mut i = 0;
while i < length {
@@ -712,7 +706,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce
Ok(())
}
pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let length = content.len();
let mut i = 0;
while i < length {
@@ -747,11 +741,7 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(),
Ok(())
}
pub fn append8BitBytes(
content: &str,
bits: &mut BitArray,
encoding: EncodingRef,
) -> Result<(), Exceptions> {
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}"))))?;
@@ -761,7 +751,7 @@ pub fn append8BitBytes(
Ok(())
}
pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Exceptions> {
pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<()> {
let sjis = &SHIFT_JIS_CHARSET;
let bytes = sjis
@@ -797,7 +787,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
Ok(())
}
fn appendECI(eci: &CharacterSetECI, bits: &mut BitArray) -> Result<(), Exceptions> {
fn appendECI(eci: &CharacterSetECI, bits: &mut BitArray) -> Result<()> {
bits.appendBits(Mode::ECI.getBits() as u32, 4)?;
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.getValueSelf(), 8)

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap;
use crate::{
common::{BitMatrix, DecoderRXingResult, DetectorRXingResult},
common::{BitMatrix, DecoderRXingResult, DetectorRXingResult, Result},
BarcodeFormat, DecodeHintType, DecodeHintValue, Exceptions, RXingResult,
RXingResultMetadataType, RXingResultMetadataValue, RXingResultPoint, Reader,
};
@@ -48,10 +48,7 @@ impl Reader for QRCodeReader {
* @throws FormatException if a QR code cannot be decoded
* @throws ChecksumException if error correction fails
*/
fn decode(
&mut self,
image: &mut crate::BinaryBitmap,
) -> Result<crate::RXingResult, crate::Exceptions> {
fn decode(&mut self, image: &mut crate::BinaryBitmap) -> Result<crate::RXingResult> {
self.decode_with_hints(image, &HashMap::new())
}
@@ -59,7 +56,7 @@ impl Reader for QRCodeReader {
&mut self,
image: &mut crate::BinaryBitmap,
hints: &crate::DecodingHintDictionary,
) -> Result<crate::RXingResult, crate::Exceptions> {
) -> Result<crate::RXingResult> {
let decoderRXingResult: DecoderRXingResult;
let mut points: Vec<RXingResultPoint>;
if matches!(
@@ -149,7 +146,7 @@ impl QRCodeReader {
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix> {
let leftTopBlack = image.getTopLeftOnBit();
let rightBottomBlack = image.getBottomRightOnBit();
if leftTopBlack.is_none() || rightBottomBlack.is_none() {
@@ -233,7 +230,7 @@ impl QRCodeReader {
Ok(bits)
}
fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result<f32, Exceptions> {
fn moduleSize(leftTopBlack: &[u32], image: &BitMatrix) -> Result<f32> {
let height = image.getHeight();
let width = image.getWidth();
let mut x = leftTopBlack[0];

View File

@@ -17,7 +17,8 @@
use std::collections::HashMap;
use crate::{
common::BitMatrix, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
common::{BitMatrix, Result},
BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
};
use super::{
@@ -45,7 +46,7 @@ impl Writer for QRCodeWriter {
format: &crate::BarcodeFormat,
width: i32,
height: i32,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
) -> Result<crate::common::BitMatrix> {
self.encode_with_hints(contents, format, width, height, &HashMap::new())
}
@@ -56,7 +57,7 @@ impl Writer for QRCodeWriter {
width: i32,
height: i32,
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
) -> Result<crate::common::BitMatrix> {
if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(
"found empty contents".to_owned(),
@@ -107,7 +108,7 @@ impl QRCodeWriter {
width: i32,
height: i32,
quietZone: i32,
) -> Result<BitMatrix, Exceptions> {
) -> Result<BitMatrix> {
let input = code.getMatrix();
if input.is_none() {
return Err(Exceptions::IllegalStateException(Some(