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

@@ -44,7 +44,7 @@ impl BoundingBox {
let leftUnspecified = topLeft.is_none() || bottomLeft.is_none();
let rightUnspecified = topRight.is_none() || bottomRight.is_none();
if leftUnspecified && rightUnspecified {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
let newTopLeft;
@@ -53,21 +53,21 @@ impl BoundingBox {
let newBottomRight;
if leftUnspecified {
newTopRight = topRight.ok_or(Exceptions::IllegalStateException(None))?;
newBottomRight = bottomRight.ok_or(Exceptions::IllegalStateException(None))?;
newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?;
newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?;
newTopLeft = RXingResultPoint::new(0.0, newTopRight.getY());
newBottomLeft = RXingResultPoint::new(0.0, newBottomRight.getY());
} else if rightUnspecified {
newTopLeft = topLeft.ok_or(Exceptions::IllegalStateException(None))?;
newBottomLeft = bottomLeft.ok_or(Exceptions::IllegalStateException(None))?;
newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?;
newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?;
newTopRight = RXingResultPoint::new(image.getWidth() as f32 - 1.0, newTopLeft.getY());
newBottomRight =
RXingResultPoint::new(image.getWidth() as f32 - 1.0, newBottomLeft.getY());
} else {
newTopLeft = topLeft.ok_or(Exceptions::IllegalStateException(None))?;
newTopRight = topRight.ok_or(Exceptions::IllegalStateException(None))?;
newBottomLeft = bottomLeft.ok_or(Exceptions::IllegalStateException(None))?;
newBottomRight = bottomRight.ok_or(Exceptions::IllegalStateException(None))?;
newTopLeft = topLeft.ok_or(Exceptions::illegalStateEmpty())?;
newTopRight = topRight.ok_or(Exceptions::illegalStateEmpty())?;
newBottomLeft = bottomLeft.ok_or(Exceptions::illegalStateEmpty())?;
newBottomRight = bottomRight.ok_or(Exceptions::illegalStateEmpty())?;
}
Ok(BoundingBox {
@@ -104,17 +104,17 @@ impl BoundingBox {
if leftBox.is_none() {
return Ok(rightBox
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.clone());
}
if rightBox.is_none() {
return Ok(leftBox
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.clone());
}
let leftBox = leftBox.ok_or(Exceptions::IllegalStateException(None))?;
let rightBox = rightBox.ok_or(Exceptions::IllegalStateException(None))?;
let leftBox = leftBox.ok_or(Exceptions::illegalStateEmpty())?;
let rightBox = rightBox.ok_or(Exceptions::illegalStateEmpty())?;
BoundingBox::new(
leftBox.image,

View File

@@ -122,7 +122,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
result.append_char(
char::from_u32(codewords[codeIndex]).ok_or(Exceptions::ParseException(None))?,
char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parseEmpty())?,
);
codeIndex += 1;
}
@@ -149,7 +149,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
BEGIN_MACRO_PDF417_OPTIONAL_FIELD | MACRO_PDF417_TERMINATOR =>
// Should not see these outside a macro block
{
return Err(Exceptions::FormatException(None))
return Err(Exceptions::formatEmpty())
}
_ => {
// Default to text compaction. During testing numerous barcodes
@@ -164,7 +164,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
result = result.build_result();
if result.is_empty() && resultMetadata.getFileId().is_empty() {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
let mut decoderRXingResult = DecoderRXingResult::new(
@@ -186,7 +186,7 @@ pub fn decodeMacroBlock(
let mut codeIndex = codeIndex;
if codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0] as usize {
// we must have at least two bytes left for the segment index
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS];
for seq in segmentIndexArray
@@ -204,7 +204,7 @@ pub fn decodeMacroBlock(
resultMetadata.setSegmentIndex(parsed_int);
} else {
// too large; bad input?
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
// Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec
@@ -221,7 +221,7 @@ pub fn decodeMacroBlock(
}
if fileId.chars().count() == 0 {
// at least one fileId codeword is required (Annex H.2)
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
resultMetadata.setFileId(fileId);
@@ -258,7 +258,7 @@ pub fn decodeMacroBlock(
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut segmentCount)?;
segmentCount = segmentCount.build_result();
let Ok(parsed_segment_count) = segmentCount.to_string().parse() else {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
};
resultMetadata.setSegmentCount(parsed_segment_count);
}
@@ -267,7 +267,7 @@ pub fn decodeMacroBlock(
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut timestamp)?;
timestamp = timestamp.build_result();
let Ok(parsed_timestamp) = timestamp.to_string().parse() else {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
};
resultMetadata.setTimestamp(parsed_timestamp);
}
@@ -276,7 +276,7 @@ pub fn decodeMacroBlock(
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?;
checksum = checksum.build_result();
let Ok(parsed_checksum ) = checksum.to_string().parse() else {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
};
resultMetadata.setChecksum(parsed_checksum);
}
@@ -285,18 +285,18 @@ pub fn decodeMacroBlock(
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?;
fileSize = fileSize.build_result();
let Ok(parsed_file_size)= fileSize.to_string().parse() else {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
};
resultMetadata.setFileSize(parsed_file_size);
}
_ => return Err(Exceptions::FormatException(None)),
_ => return Err(Exceptions::formatEmpty()),
}
}
MACRO_PDF417_TERMINATOR => {
codeIndex += 1;
resultMetadata.setLastSegment(true);
}
_ => return Err(Exceptions::FormatException(None)),
_ => return Err(Exceptions::formatEmpty()),
}
}
@@ -388,7 +388,7 @@ fn textCompaction(
result,
subMode,
)
.ok_or(Exceptions::IllegalStateException(None))?;
.ok_or(Exceptions::illegalStateEmpty())?;
result.appendECI(codewords[codeIndex])?;
codeIndex += 1;
textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2];
@@ -770,18 +770,16 @@ fn numericCompaction(
Remove leading 1 => RXingResult is 000213298174000
*/
fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result<String, Exceptions> {
let mut result = 0
.to_biguint()
.ok_or(Exceptions::ArithmeticException(None))?;
let mut result = 0.to_biguint().ok_or(Exceptions::arithmeticEmpty())?;
for i in 0..count {
result += &EXP900[count - i - 1]
* (codewords[i]
.to_biguint()
.ok_or(Exceptions::ArithmeticException(None))?);
.ok_or(Exceptions::arithmeticEmpty())?);
}
let resultString = result.to_string();
if !resultString.starts_with('1') {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
Ok(resultString[1..].to_owned())
}

View File

@@ -103,7 +103,7 @@ pub fn decode(
// for (int i = 0; i < errorLocations.length; i++) {
let position = received.len() as isize - 1 - field.log(errorLocations[i])? as isize;
if position < 0 {
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksum(file!().to_string()));
}
received[position as usize] =
field.subtract(received[position as usize], errorMagnitudes[i]);
@@ -140,7 +140,7 @@ fn runEuclideanAlgorithm(
// Divide rLastLast by rLast, with quotient in q and remainder in r
if rLast.isZero() {
// Oops, Euclidean algorithm already terminated?
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksum(file!().to_string()));
}
r = rLastLast;
let mut q = ModulusPoly::getZero(field); //field.getZero();
@@ -162,7 +162,7 @@ fn runEuclideanAlgorithm(
let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 {
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksum(file!().to_string()));
}
let inverse = field.inverse(sigmaTildeAtZero)?;
@@ -190,7 +190,7 @@ fn findErrorLocations(
i += 1;
}
if e != numErrors {
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksum(file!().to_string()));
}
Ok(result)
}

View File

@@ -77,7 +77,7 @@ impl ModulusGF {
pub fn log(&self, a: u32) -> Result<u32, Exceptions> {
if a == 0 {
Err(Exceptions::ArithmeticException(None))
Err(Exceptions::arithmeticEmpty())
} else {
Ok(self.logTable[a as usize])
}
@@ -85,7 +85,7 @@ impl ModulusGF {
pub fn inverse(&self, a: u32) -> Result<u32, Exceptions> {
if a == 0 {
Err(Exceptions::ArithmeticException(None))
Err(Exceptions::arithmeticEmpty())
} else {
Ok(self.expTable[self.modulus as usize - self.logTable[a as usize] as usize - 1])
}

View File

@@ -36,7 +36,7 @@ impl ModulusPoly {
coefficients: Vec<u32>,
) -> Result<ModulusPoly, Exceptions> {
if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException(None));
return Err(Exceptions::illegalArgumentEmpty());
}
let orig_coefs = coefficients.clone();
let mut coefficients = coefficients;
@@ -126,9 +126,9 @@ impl ModulusPoly {
pub fn add(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
));
}
if self.isZero() {
return Ok(other);
@@ -160,9 +160,9 @@ impl ModulusPoly {
pub fn subtract(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
));
}
if other.isZero() {
return Ok(Rc::new(self.clone()));
@@ -172,9 +172,9 @@ impl ModulusPoly {
pub fn multiply(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>, Exceptions> {
if !(self.field == other.field) {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
));
}
if self.isZero() || other.isZero() {
return Ok(Self::getZero(self.field));

View File

@@ -86,7 +86,7 @@ pub fn decode(
}
detectionRXingResult = merge(&mut leftRowIndicatorColumn, &mut rightRowIndicatorColumn)?;
if detectionRXingResult.is_none() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
// detectionRXingResult = detectionRXingResult;
@@ -142,7 +142,7 @@ pub fn decode(
// for (int imageRow = boundingBox.getMinY(); imageRow <= boundingBox.getMaxY(); imageRow++) {
startColumn =
getStartColumn(&detectionRXingResult, barcodeColumn, imageRow, leftToRight)
.ok_or(Exceptions::IllegalStateException(None))? as i32;
.ok_or(Exceptions::illegalStateEmpty())? as i32;
if startColumn < 0 || startColumn > boundingBox.getMaxX() as i32 {
if previousStartColumn == -1 {
continue;
@@ -412,7 +412,7 @@ fn adjustCodewordCount(
as u32;
if numberOfCodewords.is_empty() {
if !(1..=pdf_417_common::MAX_CODEWORDS_IN_BARCODE).contains(&calculatedNumberOfCodewords) {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
} else if numberOfCodewords[0] != calculatedNumberOfCodewords
@@ -508,7 +508,7 @@ fn createDecoderRXingResultFromAmbiguousValues(
// //
// }
if ambiguousIndexCount.is_empty() {
return Err(Exceptions::ChecksumException(None));
return Err(Exceptions::checksumEmpty());
}
for i in 0..ambiguousIndexCount.len() {
// for (int i = 0; i < ambiguousIndexCount.length; i++) {
@@ -518,14 +518,14 @@ fn createDecoderRXingResultFromAmbiguousValues(
} else {
ambiguousIndexCount[i] = 0;
if i == ambiguousIndexCount.len() - 1 {
return Err(Exceptions::ChecksumException(None));
return Err(Exceptions::checksumEmpty());
}
}
}
tries -= 1;
}
Err(Exceptions::ChecksumException(None))
Err(Exceptions::checksumEmpty())
}
fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec<Vec<BarcodeValue>> {
@@ -845,7 +845,7 @@ fn decodeCodewords(
erasures: &mut [u32],
) -> Result<DecoderRXingResult, Exceptions> {
if codewords.is_empty() {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
let numECCodewords = 1 << (ecLevel + 1);
@@ -880,7 +880,7 @@ fn correctErrors(
|| numECCodewords > MAX_EC_CODEWORDS
{
// Too many errors or EC Codewords is corrupted
return Err(Exceptions::ChecksumException(None));
return Err(Exceptions::checksumEmpty());
}
ec::error_correction::decode(codewords, numECCodewords, erasures)
}
@@ -892,21 +892,21 @@ fn verifyCodewordCount(codewords: &mut [u32], numECCodewords: u32) -> Result<(),
if codewords.len() < 4 {
// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
let numberOfCodewords = codewords[0];
if numberOfCodewords > codewords.len() as u32 {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
if numberOfCodewords == 0 {
// Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if numECCodewords < codewords.len() as u32 {
codewords[0] = codewords.len() as u32 - numECCodewords;
} else {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::formatEmpty());
}
}
Ok(())

View File

@@ -78,8 +78,7 @@ pub fn detect_with_hints(
for rotation in ROTATIONS {
// for (int rotation : ROTATIONS) {
let bitMatrix = applyRotation(originalMatrix, rotation)?;
let barcodeCoordinates =
detect(multiple, &bitMatrix).ok_or(Exceptions::NotFoundException(None))?;
let barcodeCoordinates = detect(multiple, &bitMatrix).ok_or(Exceptions::notFoundEmpty())?;
if !barcodeCoordinates.is_empty() {
return Ok(PDF417DetectorRXingResult::with_rotation(
bitMatrix.into_owned(),

View File

@@ -40,8 +40,8 @@ impl TryFrom<&String> for Compaction {
_ => {}
}
}
Err(Exceptions::FormatException(Some(format!(
Err(Exceptions::format(format!(
"Compaction must be 0-3 (inclusivie). Found: {value}"
))))
)))
}
}

View File

@@ -161,7 +161,7 @@ impl PDF417 {
pattern = CODEWORD_TABLE[cluster][fullCodewords
.chars()
.nth(idx)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
as usize];
Self::encodeChar(pattern, 17, logic.getCurrentRowMut());
idx += 1;
@@ -226,17 +226,17 @@ impl PDF417 {
//2. step: construct data codewords
if sourceCodeWords + errorCorrectionCodeWords + 1 > 929 {
// +1 for symbol length CW
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"Encoded message contains too many code words, message too big ({} bytes)",
msg.chars().count()
))));
)));
}
let n = sourceCodeWords + pad + 1;
let mut sb = String::with_capacity(n as usize);
sb.push(char::from_u32(n).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(n).ok_or(Exceptions::parseEmpty())?);
sb.push_str(&highLevel);
for _i in 0..pad {
sb.push(char::from_u32(900).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(900).ok_or(Exceptions::parseEmpty())?);
//PAD characters
}
let dataCodewords = sb;
@@ -315,9 +315,9 @@ impl PDF417 {
}
}
dimension.ok_or(Exceptions::WriterException(Some(
dimension.ok_or(Exceptions::writer(
"Unable to fit message in columns".to_owned(),
)))
))
}
/**

View File

@@ -119,9 +119,9 @@ static EC_COEFFICIENTS: Lazy<[Vec<u32>; 9]> = Lazy::new(|| {
*/
pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result<u32, Exceptions> {
if errorCorrectionLevel > 8 {
return Err(Exceptions::IllegalArgumentException(Some(
return Err(Exceptions::illegalArgument(
"Error correction level must be between 0 and 8!".to_owned(),
)));
));
}
Ok(1 << (errorCorrectionLevel + 1))
}
@@ -135,9 +135,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result<u32,
*/
pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result<u32, Exceptions> {
if n == 0 {
Err(Exceptions::IllegalArgumentException(Some(
"n must be > 0".to_owned(),
)))
Err(Exceptions::illegalArgument("n must be > 0".to_owned()))
} else if n <= 40 {
Ok(2)
} else if n <= 160 {
@@ -147,9 +145,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result<u32, Exceptio
} else if n <= 863 {
Ok(5)
} else {
Err(Exceptions::WriterException(Some(
"No recommendation possible".to_owned(),
)))
Err(Exceptions::writer("No recommendation possible".to_owned()))
}
}
@@ -171,7 +167,7 @@ pub fn generateErrorCorrection(
let t1 = (dataCodewords
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32
+ e[e.len() - 1] as u32)
% 929;
let mut t2;
@@ -180,20 +176,19 @@ pub fn generateErrorCorrection(
while j >= 1 {
t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel as usize][j]) % 929;
t3 = 929 - t2;
e[j] = char::from_u32((e[j - 1] as u32 + t3) % 929)
.ok_or(Exceptions::ParseException(None))?;
e[j] = char::from_u32((e[j - 1] as u32 + t3) % 929).ok_or(Exceptions::parseEmpty())?;
j -= 1;
}
t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel as usize][0]) % 929;
t3 = 929 - t2;
e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::ParseException(None))?;
e[0] = char::from_u32(t3 % 929).ok_or(Exceptions::parseEmpty())?;
}
let mut sb = String::with_capacity(k as usize);
let mut j = k as isize - 1;
while j >= 0 {
if e[j as usize] as u32 != 0 {
e[j as usize] = char::from_u32(929 - e[j as usize] as u32)
.ok_or(Exceptions::ParseException(None))?;
e[j as usize] =
char::from_u32(929 - e[j as usize] as u32).ok_or(Exceptions::parseEmpty())?;
}
sb.push(e[j as usize]);

View File

@@ -179,15 +179,13 @@ pub fn encodeHighLevel(
) -> Result<String, Exceptions> {
let mut encoding = encoding;
if msg.is_empty() {
return Err(Exceptions::WriterException(Some(
"Empty message not allowed".to_owned(),
)));
return Err(Exceptions::writer("Empty message not allowed".to_owned()));
}
if encoding.is_none() && !autoECI {
for ch in msg.chars() {
if ch as u32 > 255 {
return Err(Exceptions::WriterException(Some(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch))));
return Err(Exceptions::writer(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch)));
}
}
}
@@ -204,11 +202,11 @@ pub fn encodeHighLevel(
} else if DEFAULT_ENCODING.name()
!= encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.name()
{
if let Some(eci) = CharacterSetECI::getCharacterSetECI(
encoding.ok_or(Exceptions::IllegalStateException(None))?,
encoding.ok_or(Exceptions::illegalStateEmpty())?,
) {
encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?;
}
@@ -230,7 +228,7 @@ pub fn encodeHighLevel(
Compaction::BYTE => {
let msgBytes = encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.encode(&input.to_string(), encoding::EncoderTrap::Strict)
.unwrap_or_default(); //input.to_string().getBytes(encoding);
encodeBinary(
@@ -242,7 +240,7 @@ pub fn encodeHighLevel(
)?;
}
Compaction::NUMERIC => {
sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parseEmpty())?);
encodeNumeric(&input, p, len as u32, &mut sb)?;
}
_ => {
@@ -257,9 +255,7 @@ pub fn encodeHighLevel(
}
let n = determineConsecutiveDigitCount(&input, p)?;
if n >= 13 {
sb.push(
char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::ParseException(None))?,
);
sb.push(char::from_u32(LATCH_TO_NUMERIC).ok_or(Exceptions::parseEmpty())?);
encodingMode = NUMERIC_COMPACTION;
textSubMode = SUBMODE_ALPHA; //Reset after latch
encodeNumeric(&input, p, n, &mut sb)?;
@@ -268,10 +264,7 @@ pub fn encodeHighLevel(
let t = determineConsecutiveTextCount(&input, p)?;
if t >= 5 || n == len as u32 {
if encodingMode != TEXT_COMPACTION {
sb.push(
char::from_u32(LATCH_TO_TEXT)
.ok_or(Exceptions::ParseException(None))?,
);
sb.push(char::from_u32(LATCH_TO_TEXT).ok_or(Exceptions::parseEmpty())?);
encodingMode = TEXT_COMPACTION;
textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch
}
@@ -295,7 +288,7 @@ pub fn encodeHighLevel(
.collect::<String>();
if let Ok(enc_str) = encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.encode(&str, encoding::EncoderTrap::Strict)
{
Some(enc_str)
@@ -311,9 +304,7 @@ pub fn encodeHighLevel(
encodeMultiECIBinary(&input, p, 1, TEXT_COMPACTION, &mut sb)?;
} else {
encodeBinary(
bytes
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?,
bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?,
0,
1,
TEXT_COMPACTION,
@@ -326,14 +317,10 @@ pub fn encodeHighLevel(
encodeMultiECIBinary(&input, p, p + b, encodingMode, &mut sb)?;
} else {
encodeBinary(
bytes
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?,
bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?,
0,
bytes
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.len() as u32,
bytes.as_ref().ok_or(Exceptions::illegalStateEmpty())?.len()
as u32,
encodingMode,
&mut sb,
)?;
@@ -385,8 +372,7 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(26 as char); //space
} else {
tmp.push(
char::from_u32(ch as u32 - 65)
.ok_or(Exceptions::ParseException(None))?,
char::from_u32(ch as u32 - 65).ok_or(Exceptions::parseEmpty())?,
);
}
} else if isAlphaLower(ch) {
@@ -401,7 +387,7 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(29 as char); //ps
tmp.push(
char::from_u32(PUNCTUATION[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
}
}
@@ -412,16 +398,12 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(26 as char); //space
} else {
tmp.push(
char::from_u32(ch as u32 - 97)
.ok_or(Exceptions::ParseException(None))?,
char::from_u32(ch as u32 - 97).ok_or(Exceptions::parseEmpty())?,
);
}
} else if isAlphaUpper(ch) {
tmp.push(27 as char); //as
tmp.push(
char::from_u32(ch as u32 - 65)
.ok_or(Exceptions::ParseException(None))?,
);
tmp.push(char::from_u32(ch as u32 - 65).ok_or(Exceptions::parseEmpty())?);
//space cannot happen here, it is also in "Lower"
} else if isMixed(ch) {
submode = SUBMODE_MIXED;
@@ -431,7 +413,7 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(29 as char); //ps
tmp.push(
char::from_u32(PUNCTUATION[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
}
}
@@ -440,7 +422,7 @@ fn encodeText<T: ECIInput + ?Sized>(
if isMixed(ch) {
tmp.push(
char::from_u32(MIXED[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
} else if isAlphaUpper(ch) {
submode = SUBMODE_ALPHA;
@@ -462,7 +444,7 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(29 as char); //ps
tmp.push(
char::from_u32(PUNCTUATION[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
}
}
@@ -472,7 +454,7 @@ fn encodeText<T: ECIInput + ?Sized>(
if isPunctuation(ch) {
tmp.push(
char::from_u32(PUNCTUATION[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
} else {
submode = SUBMODE_ALPHA;
@@ -497,20 +479,19 @@ fn encodeText<T: ECIInput + ?Sized>(
+ tmp
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
as u32,
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32,
)
.ok_or(Exceptions::ParseException(None))?;
.ok_or(Exceptions::parseEmpty())?;
sb.push(h);
} else {
h = tmp
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?;
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
}
}
if (len % 2) != 0 {
sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32((h as u32 * 30) + 29).ok_or(Exceptions::parseEmpty())?);
//ps
}
Ok(submode)
@@ -602,11 +583,11 @@ fn encodeBinary(
sb: &mut String,
) -> Result<(), Exceptions> {
if count == 1 && startmode == TEXT_COMPACTION {
sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(SHIFT_TO_BYTE).ok_or(Exceptions::parseEmpty())?);
} else if (count % 6) == 0 {
sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(LATCH_TO_BYTE).ok_or(Exceptions::parseEmpty())?);
} else {
sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(LATCH_TO_BYTE_PADDED).ok_or(Exceptions::parseEmpty())?);
}
let mut idx = startpos;
@@ -620,7 +601,7 @@ fn encodeBinary(
t += bytes[idx as usize + i as usize] as i64;
}
for ch in &mut chars {
*ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::ParseException(None))?;
*ch = char::from_u32((t % 900) as u32).ok_or(Exceptions::parseEmpty())?;
t /= 900;
}
sb.push_str(&chars.into_iter().rev().collect::<String>());
@@ -644,8 +625,8 @@ fn encodeNumeric<T: ECIInput + ?Sized>(
) -> Result<(), Exceptions> {
let mut idx = 0;
let mut tmp = String::with_capacity(count as usize / 3 + 1);
let NUM900: num::BigUint = num::BigUint::from(900_u16); //.ok_or(Exceptions::ParseException(None))?;
let NUM0: num::BigUint = num::BigUint::from(0_u8); //.ok_or(Exceptions::ParseException(None))?;
let NUM900: num::BigUint = num::BigUint::from(900_u16); //.ok_or(Exceptions::parseEmpty())?;
let NUM0: num::BigUint = num::BigUint::from(0_u8); //.ok_or(Exceptions::parseEmpty())?;
// let num900: u128 = 900;
// const NUM0: u128 = 0;
@@ -662,17 +643,15 @@ fn encodeNumeric<T: ECIInput + ?Sized>(
.iter()
.collect::<String>()
);
// let mut bigint: u128 = part.parse().map_err(|_| Exceptions::ParseException(None))?;
// let mut bigint: u128 = part.parse().map_err(|_| Exceptions::parseEmpty())?;
let mut bigint = num::BigUint::from_str(&part)
.map_err(|e| Exceptions::ParseException(Some(format!("issue parsing {part}: {e}"))))?; // part.parse().map_err(|_| Exceptions::ParseException(None))?;
.map_err(|e| Exceptions::parse(format!("issue parsing {part}: {e}")))?; // part.parse().map_err(|_| Exceptions::parseEmpty())?;
loop {
tmp.push(
char::from_u32((&bigint % &NUM900).try_into().map_err(|e| {
Exceptions::ParseException(Some(format!(
"erorr converting {bigint} to u32: {e}"
)))
Exceptions::parse(format!("erorr converting {bigint} to u32: {e}"))
})?)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parseEmpty())?,
);
bigint /= &NUM900;
@@ -818,15 +797,15 @@ fn determineConsecutiveBinaryCount<T: ECIInput + ?Sized + 'static>(
if !can_encode {
if TypeId::of::<T>() != TypeId::of::<NoECIInput>() {
return Err(Exceptions::IllegalStateException(Some(
return Err(Exceptions::illegalState(
"expected NoECIInput type".to_owned(),
)));
));
}
let ch = input.charAt(idx)?;
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"Non-encodable character detected: {} (Unicode: {})",
ch, ch as u32
))));
)));
}
}
idx += 1;
@@ -836,19 +815,19 @@ fn determineConsecutiveBinaryCount<T: ECIInput + ?Sized + 'static>(
fn encodingECI(eci: i32, sb: &mut String) -> Result<(), Exceptions> {
if (0..900).contains(&eci) {
sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(eci as u32).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(ECI_CHARSET).ok_or(Exceptions::parseEmpty())?);
sb.push(char::from_u32(eci as u32).ok_or(Exceptions::parseEmpty())?);
} else if eci < 810900 {
sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(ECI_GENERAL_PURPOSE).ok_or(Exceptions::parseEmpty())?);
sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::parseEmpty())?);
sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::parseEmpty())?);
} else if eci < 811800 {
sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::ParseException(None))?);
sb.push(char::from_u32(ECI_USER_DEFINED).ok_or(Exceptions::parseEmpty())?);
sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::parseEmpty())?);
} else {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writer(format!(
"ECI number not in valid range from 0..811799, but was {eci}"
))));
)));
}
Ok(())
}
@@ -863,7 +842,7 @@ impl ECIInput for NoECIInput {
self.0
.chars()
.nth(index)
.ok_or(Exceptions::IndexOutOfBoundsException(None))
.ok_or(Exceptions::indexOutOfBoundsEmpty())
}
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> {

View File

@@ -57,7 +57,7 @@ impl Reader for PDF417Reader {
) -> Result<crate::RXingResult, crate::Exceptions> {
let result = Self::decode(image, hints, false)?;
if result.is_empty() {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFoundEmpty());
}
Ok(result[0].clone())
}
@@ -127,7 +127,7 @@ impl PDF417Reader {
pdf417RXingResultMetadata
.clone()
.downcast::<PDF417RXingResultMetadata>()
.map_err(|_| Exceptions::IllegalStateException(None))?,
.map_err(|_| Exceptions::illegalStateEmpty())?,
);
result.putMetadata(RXingResultMetadataType::PDF417_EXTRA_METADATA, data);
}

View File

@@ -59,9 +59,9 @@ impl Writer for PDF417Writer {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if format != &BarcodeFormat::PDF_417 {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgument(format!(
"Can only encode PDF_417, but got {format}"
))));
)));
}
let mut encoder = PDF417::new();
@@ -149,7 +149,7 @@ impl PDF417Writer {
let mut originalScale = encoder
.getBarcodeMatrix()
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.getScaledMatrix(1, aspectRatio);
let mut rotated = false;
if (height > width) != (originalScale[0].len() < originalScale.len()) {
@@ -165,17 +165,16 @@ impl PDF417Writer {
let mut scaledMatrix = encoder
.getBarcodeMatrix()
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalStateEmpty())?
.getScaledMatrix(scale, scale * aspectRatio);
if rotated {
scaledMatrix = Self::rotateArray(&scaledMatrix);
}
return Self::bitMatrixFromBitArray(&scaledMatrix, margin)
.ok_or(Exceptions::IllegalStateException(None));
.ok_or(Exceptions::illegalStateEmpty());
}
Self::bitMatrixFromBitArray(&originalScale, margin)
.ok_or(Exceptions::IllegalStateException(None))
Self::bitMatrixFromBitArray(&originalScale, margin).ok_or(Exceptions::illegalStateEmpty())
}
/**