Merge branch 'main' into pr/exception_helpers

This commit is contained in:
Vukašin Stepanović
2023-02-16 07:15:51 +00:00
161 changed files with 900 additions and 933 deletions

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::illegalArgumentWith("0 polynomial"));
}
@@ -345,7 +341,7 @@ pub fn makeTypeInfoBits(
ecLevel: &ErrorCorrectionLevel,
maskPattern: u32,
bits: &mut BitArray,
) -> Result<(), Exceptions> {
) -> Result<()> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::writerWith("Invalid mask pattern"));
}
@@ -371,7 +367,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)?;
@@ -409,7 +405,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::writer);
}
@@ -421,7 +417,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::writer);
@@ -435,7 +431,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::writer);
@@ -462,9 +458,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)?;
@@ -200,7 +200,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),
@@ -241,7 +241,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),
@@ -258,14 +258,19 @@ impl MinimalEncoder {
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
position: usize,
edge: Option<Rc<Edge>>,
) -> Result<(), Exceptions> {
let vertexIndex =
position + edge.as_ref().ok_or(Exceptions::format)?.characterLength as usize;
let modeEdges =
&mut edges[vertexIndex][edge.as_ref().ok_or(Exceptions::format)?.charsetEncoderIndex];
let modeOrdinal =
Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::format)?.mode))?
as usize;
) -> Result<()> {
let vertexIndex = position
+ edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.characterLength as usize;
let modeEdges = &mut edges[vertexIndex][edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.charsetEncoderIndex];
let modeOrdinal = Self::getCompactedOrdinal(Some(
edge.as_ref().ok_or(Exceptions::FormatException(None))?.mode,
))? as usize;
if modeEdges[modeOrdinal].is_none()
|| modeEdges[modeOrdinal]
.as_ref()
@@ -285,7 +290,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();
@@ -440,10 +445,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.
@@ -857,7 +859,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)?;
}
@@ -996,7 +998,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;
@@ -260,7 +260,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:
@@ -361,7 +361,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.
@@ -377,10 +377,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) {
@@ -412,7 +409,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::writerWith(format!(
@@ -460,7 +457,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::writerWith("Block ID too large"));
}
@@ -513,7 +510,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::writerWith(
@@ -586,10 +583,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 {
@@ -611,7 +605,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)
}
@@ -623,7 +617,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::writerWith(format!(
@@ -643,7 +637,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),
@@ -653,7 +647,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 {
@@ -690,7 +684,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 {
@@ -721,11 +715,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::writerWith(format!("error {e}")))?;
@@ -735,7 +725,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
@@ -767,7 +757,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)