refactor to use exception helper factories

This commit is contained in:
Vukašin Stepanović
2023-02-15 10:46:13 +00:00
parent 3e27279dc8
commit 722ce78fd0
132 changed files with 966 additions and 1132 deletions

View File

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

View File

@@ -278,11 +278,11 @@ pub fn embedDataBits(
}
// All bits should be consumed.
if bitIndex != dataBits.getSize() {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"Not all bits consumed: {}/{}",
bitIndex,
dataBits.getSize()
))));
)));
}
Ok(())
}
@@ -323,9 +323,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, Exceptions> {
if poly == 0 {
return Err(Exceptions::IllegalArgumentException(Some(
"0 polynomial".to_owned(),
)));
return Err(Exceptions::illegalArgument("0 polynomial".to_owned()));
}
let mut value = value;
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
@@ -349,9 +347,7 @@ pub fn makeTypeInfoBits(
bits: &mut BitArray,
) -> Result<(), Exceptions> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::WriterException(Some(
"Invalid mask pattern".to_owned(),
)));
return Err(Exceptions::writer("Invalid mask pattern".to_owned()));
}
let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
bits.appendBits(typeInfo, 5)?;
@@ -365,10 +361,10 @@ pub fn makeTypeInfoBits(
if bits.getSize() != 15 {
// Just in case.
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"should not happen but we got: {}",
bits.getSize()
))));
)));
}
Ok(())
}
@@ -382,10 +378,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::writer(format!(
"should not happen but we got: {}",
bits.getSize()
))));
)));
}
Ok(())
}
@@ -415,7 +411,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> {
if matrix.get(8, matrix.getHeight() - 8) == 0 {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writerEmpty());
}
matrix.set(8, matrix.getHeight() - 8, 1);
Ok(())
@@ -428,7 +424,7 @@ pub fn embedHorizontalSeparationPattern(
) -> Result<(), Exceptions> {
for x in 0..8 {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writerEmpty());
}
matrix.set(xStart + x, yStart, 0);
}
@@ -442,7 +438,7 @@ pub fn embedVerticalSeparationPattern(
) -> Result<(), Exceptions> {
for y in 0..7 {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writerEmpty());
}
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::writer(format!(
"Data too big for version {version}"
))));
)));
}
Ok(result)
} else {
@@ -186,9 +186,9 @@ impl MinimalEncoder {
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::WriterException(Some(
return Err(Exceptions::writer(
"Data too big for any version".to_owned(),
)));
));
}
Ok(results[smallestRXingResult as usize].clone())
}
@@ -249,9 +249,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::illegalArgument(format!(
"Illegal mode {mode:?}"
)))),
))),
}
}
@@ -264,23 +264,23 @@ impl MinimalEncoder {
let vertexIndex = position
+ edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
.characterLength as usize;
let modeEdges = &mut edges[vertexIndex][edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
.charsetEncoderIndex];
let modeOrdinal = Self::getCompactedOrdinal(Some(
edge.as_ref().ok_or(Exceptions::FormatException(None))?.mode,
))? as usize;
let modeOrdinal =
Self::getCompactedOrdinal(Some(edge.as_ref().ok_or(Exceptions::formatEmpty())?.mode))?
as usize;
if modeEdges[modeOrdinal].is_none()
|| modeEdges[modeOrdinal]
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
.cachedTotalSize
> edge
.as_ref()
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
.cachedTotalSize
{
modeEdges[modeOrdinal] = edge;
@@ -304,12 +304,12 @@ impl MinimalEncoder {
.encoders
.canEncode(
&self.stringToEncode[from],
priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?,
priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?,
)
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
{
start = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))?;
end = priorityEncoderIndex.ok_or(Exceptions::FormatException(None))? + 1;
start = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())?;
end = priorityEncoderIndex.ok_or(Exceptions::formatEmpty())? + 1;
}
for i in start..end {
@@ -318,10 +318,10 @@ impl MinimalEncoder {
.canEncode(
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
i,
)
.ok_or(Exceptions::FormatException(None))?
.ok_or(Exceptions::formatEmpty())?
{
self.addEdge(
edges,
@@ -337,7 +337,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writerEmpty())?,
)),
)?;
}
@@ -347,7 +347,7 @@ impl MinimalEncoder {
&Mode::KANJI,
self.stringToEncode
.get(from)
.ok_or(Exceptions::FormatException(None))?,
.ok_or(Exceptions::formatEmpty())?,
) {
self.addEdge(
edges,
@@ -363,7 +363,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writerEmpty())?,
)),
)?;
}
@@ -373,7 +373,7 @@ impl MinimalEncoder {
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
) {
self.addEdge(
edges,
@@ -388,7 +388,7 @@ impl MinimalEncoder {
&Mode::ALPHANUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
)
{
1
@@ -400,7 +400,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writerEmpty())?,
)),
)?;
}
@@ -409,7 +409,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
) {
self.addEdge(
edges,
@@ -424,7 +424,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
)
{
1
@@ -433,7 +433,7 @@ impl MinimalEncoder {
&Mode::NUMERIC,
self.stringToEncode
.get(from + 2)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?,
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
)
{
2
@@ -445,7 +445,7 @@ impl MinimalEncoder {
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writerEmpty())?,
)),
)?;
}
@@ -608,22 +608,22 @@ impl MinimalEncoder {
version,
edges[inputLength][minJ][minK]
.as_ref()
.ok_or(Exceptions::WriterException(None))?
.ok_or(Exceptions::writerEmpty())?
.clone(),
self.isGS1,
&self.ecLevel,
self.encoders.clone(),
self.stringToEncode.clone(),
)
.ok_or(Exceptions::WriterException(None))?)
.ok_or(Exceptions::writerEmpty())?)
} else {
Err(Exceptions::WriterException(Some(format!(
Err(Exceptions::writer(format!(
r#"Internal error: failed to encode "{}"#,
self.stringToEncode
.iter()
.map(String::from)
.collect::<String>()
))))
)))
}
}
}
@@ -1033,7 +1033,7 @@ impl RXingResultNode {
bits,
self.encoders
.getCharset(self.charsetEncoderIndex)
.ok_or(Exceptions::WriterException(None))?,
.ok_or(Exceptions::writerEmpty())?,
)?;
}
Ok(())

View File

@@ -101,8 +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::WriterException(None))?,
encoding::label::encoding_from_whatwg_label(v).ok_or(Exceptions::writerEmpty())?,
)
}
}
@@ -181,9 +180,9 @@ 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(
return Err(Exceptions::writer(
"Data too big for requested version".to_owned(),
)));
));
}
} else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -391,9 +390,9 @@ fn chooseVersion(
return Ok(version);
}
}
Err(Exceptions::WriterException(Some(format!(
Err(Exceptions::writer(format!(
"data too big {numInputBits}/{ecLevel:?}"
))))
)))
}
/**
@@ -419,9 +418,9 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> {
let capacity = num_data_bytes * 8;
if bits.getSize() > capacity as usize {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(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 {
@@ -447,9 +446,9 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc
bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?;
}
if bits.getSize() != capacity as usize {
return Err(Exceptions::WriterException(Some(
return Err(Exceptions::writer(
"Bits size does not equal capacity".to_owned(),
)));
));
}
Ok(())
}
@@ -468,9 +467,7 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32), Exceptions> {
if block_id >= num_rsblocks {
return Err(Exceptions::WriterException(Some(
"Block ID too large".to_owned(),
)));
return Err(Exceptions::writer("Block ID too large".to_owned()));
}
// numRsBlocksInGroup2 = 196 % 5 = 1
let num_rs_blocks_in_group2 = num_total_bytes % num_rsblocks;
@@ -491,24 +488,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::writer("EC bytes mismatch".to_owned()));
}
// 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::writer("RS blocks mismatch".to_owned()));
}
// 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::writer("total bytes mismatch".to_owned()));
}
Ok(if block_id < num_rs_blocks_in_group1 {
@@ -530,9 +521,9 @@ pub fn interleaveWithECBytes(
) -> Result<BitArray, Exceptions> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::WriterException(Some(
return Err(Exceptions::writer(
"Number of bits and data bytes does not match".to_owned(),
)));
));
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
@@ -565,9 +556,9 @@ pub fn interleaveWithECBytes(
data_bytes_offset += numDataBytesInBlock as usize;
}
if num_data_bytes != data_bytes_offset as u32 {
return Err(Exceptions::WriterException(Some(
return Err(Exceptions::writer(
"Data bytes does not match offset".to_owned(),
)));
));
}
let mut result = BitArray::new();
@@ -592,11 +583,11 @@ pub fn interleaveWithECBytes(
}
if num_total_bytes != result.getSizeInBytes() as u32 {
// Should be same.
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"Interleaving error: {} and {} differ.",
num_total_bytes,
result.getSizeInBytes()
))));
)));
}
Ok(result)
@@ -642,11 +633,11 @@ pub fn appendLengthInfo(
) -> Result<(), Exceptions> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"{} is bigger than {}",
num_letters,
((1 << numBits) - 1)
))));
)));
}
bits.appendBits(num_letters, numBits as usize)
}
@@ -665,9 +656,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::writer(format!("Invalid mode: {mode:?}"))),
}
}
@@ -678,19 +667,19 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce
let num1 = content
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBoundsEmpty())? 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::indexOutOfBoundsEmpty())? as u8
- b'0';
let num3 = content
.chars()
.nth(i + 2)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8
- b'0';
bits.appendBits(num1 as u32 * 100 + num2 as u32 * 10 + num3 as u32, 10)?;
i += 3;
@@ -699,7 +688,7 @@ pub fn appendNumericBytes(content: &str, bits: &mut BitArray) -> Result<(), Exce
let num2 = content
.chars()
.nth(i + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u8
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u8
- b'0';
bits.appendBits(num1 as u32 * 10 + num2 as u32, 7)?;
i += 2;
@@ -720,20 +709,20 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(),
content
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32,
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32,
);
if code1 == -1 {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writerEmpty());
}
if i + 1 < length {
let code2 = getAlphanumericCode(
content
.chars()
.nth(i + 1)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32,
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32,
);
if code2 == -1 {
return Err(Exceptions::WriterException(None));
return Err(Exceptions::writerEmpty());
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?;
@@ -754,7 +743,7 @@ pub fn append8BitBytes(
) -> Result<(), Exceptions> {
let bytes = encoding
.encode(content, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?;
.map_err(|e| Exceptions::writer(format!("error {e}")))?;
for b in bytes {
bits.appendBits(b as u32, 8)?;
}
@@ -766,11 +755,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
let bytes = sjis
.encode(content, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::WriterException(Some(format!("error {e}"))))?;
.map_err(|e| Exceptions::writer(format!("error {e}")))?;
if bytes.len() % 2 != 0 {
return Err(Exceptions::WriterException(Some(
"Kanji byte size not even".to_owned(),
)));
return Err(Exceptions::writer("Kanji byte size not even".to_owned()));
}
let max_i = bytes.len() - 1; // bytes.length must be even
let mut i = 0;
@@ -785,9 +772,7 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
subtracted = code as i32 - 0xc140;
}
if subtracted == -1 {
return Err(Exceptions::WriterException(Some(
"Invalid byte sequence".to_owned(),
)));
return Err(Exceptions::writer("Invalid byte sequence".to_owned()));
}
let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded as u32, 13)?;