Merge branch 'main' into pr/point_refactor

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

View File

@@ -47,7 +47,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::notFound);
}
let newTopLeft;
@@ -56,20 +56,20 @@ 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::illegalState)?;
newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?;
newTopLeft = point(0.0, newTopRight.y);
newBottomLeft = point(0.0, newBottomRight.y);
} else if rightUnspecified {
newTopLeft = topLeft.ok_or(Exceptions::IllegalStateException(None))?;
newBottomLeft = bottomLeft.ok_or(Exceptions::IllegalStateException(None))?;
newTopLeft = topLeft.ok_or(Exceptions::illegalState)?;
newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?;
newTopRight = point(image.getWidth() as f32 - 1.0, newTopLeft.y);
newBottomRight = point(image.getWidth() as f32 - 1.0, newBottomLeft.y);
} 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::illegalState)?;
newTopRight = topRight.ok_or(Exceptions::illegalState)?;
newBottomLeft = bottomLeft.ok_or(Exceptions::illegalState)?;
newBottomRight = bottomRight.ok_or(Exceptions::illegalState)?;
}
Ok(BoundingBox {
@@ -104,19 +104,13 @@ impl BoundingBox {
rightBox: Option<BoundingBox>,
) -> Result<BoundingBox> {
if leftBox.is_none() {
return Ok(rightBox
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.clone());
return Ok(rightBox.as_ref().ok_or(Exceptions::illegalState)?.clone());
}
if rightBox.is_none() {
return Ok(leftBox
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.clone());
return Ok(leftBox.as_ref().ok_or(Exceptions::illegalState)?.clone());
}
let leftBox = leftBox.ok_or(Exceptions::IllegalStateException(None))?;
let rightBox = rightBox.ok_or(Exceptions::IllegalStateException(None))?;
let leftBox = leftBox.ok_or(Exceptions::illegalState)?;
let rightBox = rightBox.ok_or(Exceptions::illegalState)?;
BoundingBox::new(
leftBox.image,

View File

@@ -121,9 +121,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult> {
codeIndex = byteCompaction(code, codewords, codeIndex, &mut result)?
}
MODE_SHIFT_TO_BYTE_COMPACTION_MODE => {
result.append_char(
char::from_u32(codewords[codeIndex]).ok_or(Exceptions::ParseException(None))?,
);
result.append_char(char::from_u32(codewords[codeIndex]).ok_or(Exceptions::parse)?);
codeIndex += 1;
}
NUMERIC_COMPACTION_MODE_LATCH => {
@@ -149,7 +147,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult> {
BEGIN_MACRO_PDF417_OPTIONAL_FIELD | MACRO_PDF417_TERMINATOR =>
// Should not see these outside a macro block
{
return Err(Exceptions::FormatException(None))
return Err(Exceptions::format)
}
_ => {
// Default to text compaction. During testing numerous barcodes
@@ -164,7 +162,7 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult> {
result = result.build_result();
if result.is_empty() && resultMetadata.getFileId().is_empty() {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
let mut decoderRXingResult = DecoderRXingResult::new(
@@ -186,7 +184,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::format);
}
let mut segmentIndexArray = [0; NUMBER_OF_SEQUENCE_CODEWORDS];
for seq in segmentIndexArray
@@ -204,7 +202,7 @@ pub fn decodeMacroBlock(
resultMetadata.setSegmentIndex(parsed_int);
} else {
// too large; bad input?
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
// Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec
@@ -221,7 +219,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::format);
}
resultMetadata.setFileId(fileId);
@@ -258,7 +256,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::format);
};
resultMetadata.setSegmentCount(parsed_segment_count);
}
@@ -267,7 +265,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::format);
};
resultMetadata.setTimestamp(parsed_timestamp);
}
@@ -276,7 +274,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::format);
};
resultMetadata.setChecksum(parsed_checksum);
}
@@ -285,18 +283,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::format);
};
resultMetadata.setFileSize(parsed_file_size);
}
_ => return Err(Exceptions::FormatException(None)),
_ => return Err(Exceptions::format),
}
}
MACRO_PDF417_TERMINATOR => {
codeIndex += 1;
resultMetadata.setLastSegment(true);
}
_ => return Err(Exceptions::FormatException(None)),
_ => return Err(Exceptions::format),
}
}
@@ -388,7 +386,7 @@ fn textCompaction(
result,
subMode,
)
.ok_or(Exceptions::IllegalStateException(None))?;
.ok_or(Exceptions::illegalState)?;
result.appendECI(codewords[codeIndex])?;
codeIndex += 1;
textCompactionData = vec![0; (codewords[0] as usize - codeIndex) * 2];
@@ -774,14 +772,12 @@ fn decodeBase900toBase10(codewords: &[u32], count: usize) -> Result<String> {
.to_biguint()
.ok_or(Exceptions::ArithmeticException(None))?;
for i in 0..count {
result += &EXP900[count - i - 1]
* (codewords[i]
.to_biguint()
.ok_or(Exceptions::ArithmeticException(None))?);
result +=
&EXP900[count - i - 1] * (codewords[i].to_biguint().ok_or(Exceptions::arithmetic)?);
}
let resultString = result.to_string();
if !resultString.starts_with('1') {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
Ok(resultString[1..].to_owned())
}

View File

@@ -100,7 +100,7 @@ pub fn decode(received: &mut [u32], numECCodewords: u32, erasures: &mut [u32]) -
// 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::checksumWith(file!()));
}
received[position as usize] =
field.subtract(received[position as usize], errorMagnitudes[i]);
@@ -137,7 +137,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::checksumWith(file!()));
}
r = rLastLast;
let mut q = ModulusPoly::getZero(field); //field.getZero();
@@ -159,7 +159,7 @@ fn runEuclideanAlgorithm(
let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 {
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksumWith(file!()));
}
let inverse = field.inverse(sigmaTildeAtZero)?;
@@ -184,7 +184,7 @@ fn findErrorLocations(errorLocator: Rc<ModulusPoly>, field: &ModulusGF) -> Resul
i += 1;
}
if e != numErrors {
return Err(Exceptions::ChecksumException(Some(file!().to_string())));
return Err(Exceptions::checksumWith(file!()));
}
Ok(result)
}

View File

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

View File

@@ -34,7 +34,7 @@ pub struct ModulusPoly {
impl ModulusPoly {
pub fn new(field: &'static ModulusGF, coefficients: Vec<u32>) -> Result<ModulusPoly> {
if coefficients.is_empty() {
return Err(Exceptions::IllegalArgumentException(None));
return Err(Exceptions::illegalArgument);
}
let orig_coefs = coefficients.clone();
let mut coefficients = coefficients;
@@ -124,9 +124,9 @@ impl ModulusPoly {
pub fn add(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"ModulusPolys do not have same ModulusGF field",
));
}
if self.isZero() {
return Ok(other);
@@ -158,9 +158,9 @@ impl ModulusPoly {
pub fn subtract(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>> {
if self.field != other.field {
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"ModulusPolys do not have same ModulusGF field",
));
}
if other.isZero() {
return Ok(Rc::new(self.clone()));
@@ -170,9 +170,9 @@ impl ModulusPoly {
pub fn multiply(&self, other: Rc<ModulusPoly>) -> Result<Rc<ModulusPoly>> {
if !(self.field == other.field) {
return Err(Exceptions::IllegalArgumentException(Some(
"ModulusPolys do not have same ModulusGF field".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"ModulusPolys do not have same ModulusGF field",
));
}
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::notFound);
}
// 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::illegalState)? 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::notFound);
}
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::checksum);
}
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::checksum);
}
}
}
tries -= 1;
}
Err(Exceptions::ChecksumException(None))
Err(Exceptions::checksum)
}
fn createBarcodeMatrix(detectionRXingResult: &mut DetectionRXingResult) -> Vec<Vec<BarcodeValue>> {
@@ -845,7 +845,7 @@ fn decodeCodewords(
erasures: &mut [u32],
) -> Result<DecoderRXingResult> {
if codewords.is_empty() {
return Err(Exceptions::FormatException(None));
return Err(Exceptions::format);
}
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::checksum);
}
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::format);
}
// 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::format);
}
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::format);
}
}
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::notFound)?;
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::formatWith(format!(
"Compaction must be 0-3 (inclusivie). Found: {value}"
))))
)))
}
}

View File

@@ -162,7 +162,7 @@ impl PDF417 {
pattern = CODEWORD_TABLE[cluster][fullCodewords
.chars()
.nth(idx)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
.ok_or(Exceptions::indexOutOfBounds)?
as usize];
Self::encodeChar(pattern, 17, logic.getCurrentRowMut());
idx += 1;
@@ -223,17 +223,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::writerWith(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::parse)?);
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::parse)?);
//PAD characters
}
let dataCodewords = sb;
@@ -312,9 +312,7 @@ impl PDF417 {
}
}
dimension.ok_or(Exceptions::WriterException(Some(
"Unable to fit message in columns".to_owned(),
)))
dimension.ok_or(Exceptions::writerWith("Unable to fit message in columns"))
}
/**

View File

@@ -120,9 +120,9 @@ static EC_COEFFICIENTS: Lazy<[Vec<u32>; 9]> = Lazy::new(|| {
*/
pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result<u32> {
if errorCorrectionLevel > 8 {
return Err(Exceptions::IllegalArgumentException(Some(
"Error correction level must be between 0 and 8!".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Error correction level must be between 0 and 8!",
));
}
Ok(1 << (errorCorrectionLevel + 1))
}
@@ -136,9 +136,7 @@ pub fn getErrorCorrectionCodewordCount(errorCorrectionLevel: u32) -> Result<u32>
*/
pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result<u32> {
if n == 0 {
Err(Exceptions::IllegalArgumentException(Some(
"n must be > 0".to_owned(),
)))
Err(Exceptions::illegalArgumentWith("n must be > 0"))
} else if n <= 40 {
Ok(2)
} else if n <= 160 {
@@ -148,9 +146,7 @@ pub fn getRecommendedMinimumErrorCorrectionLevel(n: u32) -> Result<u32> {
} else if n <= 863 {
Ok(5)
} else {
Err(Exceptions::WriterException(Some(
"No recommendation possible".to_owned(),
)))
Err(Exceptions::writerWith("No recommendation possible"))
}
}
@@ -169,7 +165,7 @@ pub fn generateErrorCorrection(dataCodewords: &str, errorCorrectionLevel: u32) -
let t1 = (dataCodewords
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))? as u32
.ok_or(Exceptions::indexOutOfBounds)? as u32
+ e[e.len() - 1] as u32)
% 929;
let mut t2;
@@ -178,20 +174,18 @@ pub fn generateErrorCorrection(dataCodewords: &str, errorCorrectionLevel: u32) -
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::parse)?;
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::parse)?;
}
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::parse)?;
}
sb.push(e[j as usize]);

View File

@@ -179,15 +179,13 @@ pub fn encodeHighLevel(
) -> Result<String> {
let mut encoding = encoding;
if msg.is_empty() {
return Err(Exceptions::WriterException(Some(
"Empty message not allowed".to_owned(),
)));
return Err(Exceptions::writerWith("Empty message not allowed"));
}
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::writerWith(format!("Non-encodable character detected: {} (Unicode: {}). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET.",ch as u32,ch)));
}
}
}
@@ -202,14 +200,11 @@ pub fn encodeHighLevel(
if encoding.is_none() {
encoding = Some(DEFAULT_ENCODING);
} else if DEFAULT_ENCODING.name()
!= encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.name()
!= encoding.as_ref().ok_or(Exceptions::illegalState)?.name()
{
if let Some(eci) = CharacterSetECI::getCharacterSetECI(
encoding.ok_or(Exceptions::IllegalStateException(None))?,
) {
if let Some(eci) =
CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::illegalState)?)
{
encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?;
}
}
@@ -230,7 +225,7 @@ pub fn encodeHighLevel(
Compaction::BYTE => {
let msgBytes = encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalState)?
.encode(&input.to_string(), encoding::EncoderTrap::Strict)
.unwrap_or_default(); //input.to_string().getBytes(encoding);
encodeBinary(
@@ -242,7 +237,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::parse)?);
encodeNumeric(&input, p, len as u32, &mut sb)?;
}
_ => {
@@ -257,9 +252,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::parse)?);
encodingMode = NUMERIC_COMPACTION;
textSubMode = SUBMODE_ALPHA; //Reset after latch
encodeNumeric(&input, p, n, &mut sb)?;
@@ -268,10 +261,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::parse)?);
encodingMode = TEXT_COMPACTION;
textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch
}
@@ -295,7 +285,7 @@ pub fn encodeHighLevel(
.collect::<String>();
if let Ok(enc_str) = encoding
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.ok_or(Exceptions::illegalState)?
.encode(&str, encoding::EncoderTrap::Strict)
{
Some(enc_str)
@@ -311,9 +301,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::illegalState)?,
0,
1,
TEXT_COMPACTION,
@@ -326,14 +314,9 @@ 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::illegalState)?,
0,
bytes
.as_ref()
.ok_or(Exceptions::IllegalStateException(None))?
.len() as u32,
bytes.as_ref().ok_or(Exceptions::illegalState)?.len() as u32,
encodingMode,
&mut sb,
)?;
@@ -384,10 +367,7 @@ fn encodeText<T: ECIInput + ?Sized>(
if ch == ' ' {
tmp.push(26 as char); //space
} else {
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::parse)?);
}
} else if isAlphaLower(ch) {
submode = SUBMODE_LOWER;
@@ -401,7 +381,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::parse)?,
);
}
}
@@ -411,17 +391,11 @@ fn encodeText<T: ECIInput + ?Sized>(
if ch == ' ' {
tmp.push(26 as char); //space
} else {
tmp.push(
char::from_u32(ch as u32 - 97)
.ok_or(Exceptions::ParseException(None))?,
);
tmp.push(char::from_u32(ch as u32 - 97).ok_or(Exceptions::parse)?);
}
} 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::parse)?);
//space cannot happen here, it is also in "Lower"
} else if isMixed(ch) {
submode = SUBMODE_MIXED;
@@ -431,7 +405,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::parse)?,
);
}
}
@@ -439,8 +413,7 @@ fn encodeText<T: ECIInput + ?Sized>(
SUBMODE_MIXED => {
if isMixed(ch) {
tmp.push(
char::from_u32(MIXED[ch as usize] as u32)
.ok_or(Exceptions::ParseException(None))?,
char::from_u32(MIXED[ch as usize] as u32).ok_or(Exceptions::parse)?,
);
} else if isAlphaUpper(ch) {
submode = SUBMODE_ALPHA;
@@ -462,7 +435,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::parse)?,
);
}
}
@@ -472,7 +445,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::parse)?,
);
} else {
submode = SUBMODE_ALPHA;
@@ -493,24 +466,16 @@ fn encodeText<T: ECIInput + ?Sized>(
let odd = (i % 2) != 0;
if odd {
h = char::from_u32(
(h as u32 * 30)
+ tmp
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
as u32,
(h as u32 * 30) + tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)? as u32,
)
.ok_or(Exceptions::ParseException(None))?;
.ok_or(Exceptions::parse)?;
sb.push(h);
} else {
h = tmp
.chars()
.nth(i)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?;
h = tmp.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?;
}
}
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::parse)?);
//ps
}
Ok(submode)
@@ -598,11 +563,11 @@ fn encodeBinary(
sb: &mut String,
) -> Result<()> {
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::parse)?);
} 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::parse)?);
} 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::parse)?);
}
let mut idx = startpos;
@@ -616,7 +581,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::parse)?;
t /= 900;
}
sb.push_str(&chars.into_iter().rev().collect::<String>());
@@ -640,8 +605,8 @@ fn encodeNumeric<T: ECIInput + ?Sized>(
) -> Result<()> {
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;
@@ -658,17 +623,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::parseWith(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::parseWith(format!("erorr converting {bigint} to u32: {e}"))
})?)
.ok_or(Exceptions::ParseException(None))?,
.ok_or(Exceptions::parse)?,
);
bigint /= &NUM900;
@@ -814,15 +777,13 @@ fn determineConsecutiveBinaryCount<T: ECIInput + ?Sized + 'static>(
if !can_encode {
if TypeId::of::<T>() != TypeId::of::<NoECIInput>() {
return Err(Exceptions::IllegalStateException(Some(
"expected NoECIInput type".to_owned(),
)));
return Err(Exceptions::illegalStateWith("expected NoECIInput type"));
}
let ch = input.charAt(idx)?;
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"Non-encodable character detected: {} (Unicode: {})",
ch, ch as u32
))));
)));
}
}
idx += 1;
@@ -832,19 +793,19 @@ fn determineConsecutiveBinaryCount<T: ECIInput + ?Sized + 'static>(
fn encodingECI(eci: i32, sb: &mut String) -> Result<()> {
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::parse)?);
sb.push(char::from_u32(eci as u32).ok_or(Exceptions::parse)?);
} 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::parse)?);
sb.push(char::from_u32((eci / 900 - 1) as u32).ok_or(Exceptions::parse)?);
sb.push(char::from_u32((eci % 900) as u32).ok_or(Exceptions::parse)?);
} 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::parse)?);
sb.push(char::from_u32((810900 - eci) as u32).ok_or(Exceptions::parse)?);
} else {
return Err(Exceptions::WriterException(Some(format!(
return Err(Exceptions::writerWith(format!(
"ECI number not in valid range from 0..811799, but was {eci}"
))));
)));
}
Ok(())
}
@@ -859,7 +820,7 @@ impl ECIInput for NoECIInput {
self.0
.chars()
.nth(index)
.ok_or(Exceptions::IndexOutOfBoundsException(None))
.ok_or(Exceptions::indexOutOfBounds)
}
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>> {

View File

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

View File

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