rename helper methods

This commit is contained in:
Vukašin Stepanović
2023-02-15 12:52:59 +00:00
parent bfcdb397ad
commit 935519ced5
133 changed files with 858 additions and 1044 deletions

View File

@@ -61,7 +61,7 @@ impl Reader for AztecReader {
} else if let Ok(det) = detector.detect(true) {
det
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
};
let points = detectorRXingResult.getPoints();

View File

@@ -59,7 +59,7 @@ impl Writer for AztecWriter {
if cset_name.to_lowercase() != "iso-8859-1" {
charset = Some(
encoding::label::encoding_from_whatwg_label(cset_name)
.ok_or(Exceptions::illegalArgumentEmpty())?,
.ok_or(Exceptions::illegalArgument)?,
);
}
}
@@ -95,7 +95,7 @@ fn encode(
layers: i32,
) -> Result<BitMatrix, Exceptions> {
if format != BarcodeFormat::AZTEC {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"can only encode AZTEC, but got {format:?}"
)));
}

View File

@@ -164,13 +164,13 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
result.push_str(
&encdr
.decode(&decoded_bytes, encoding::DecoderTrap::Strict)
.map_err(|a| Exceptions::illegalState(a))?,
.map_err(|a| Exceptions::illegalStateWith(a))?,
);
decoded_bytes.clear();
match n {
0 => result.push(29 as char), // translate FNC1 as ASCII 29
7 => return Err(Exceptions::format("FLG(7) is reserved and illegal")), // FLG(7) is reserved and illegal
7 => return Err(Exceptions::formatWith("FLG(7) is reserved and illegal")), // FLG(7) is reserved and illegal
_ => {
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode
let mut eci = 0;
@@ -182,7 +182,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
let next_digit = read_code(corrected_bits, index, 4);
index += 4;
if !(2..=11).contains(&next_digit) {
return Err(Exceptions::format("Not a decimal digit"));
return Err(Exceptions::formatWith("Not a decimal digit"));
// Not a decimal digit
}
eci = eci * 10 + (next_digit - 2);
@@ -190,7 +190,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
}
let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci);
if charset_eci.is_err() {
return Err(Exceptions::format("Charset must exist"));
return Err(Exceptions::formatWith("Charset must exist"));
}
encdr = CharacterSetECI::getCharset(&charset_eci?);
}
@@ -203,17 +203,8 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
// That's including when that mode is a shift.
// Our test case dlusbs.png for issue #642 exercises that.
latch_table = shift_table; // Latch the current mode, so as to return to Upper after U/S B/S
shift_table = getTable(
str.chars()
.nth(5)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
);
if str
.chars()
.nth(6)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
== 'L'
{
shift_table = getTable(str.chars().nth(5).ok_or(Exceptions::indexOutOfBounds)?);
if str.chars().nth(6).ok_or(Exceptions::indexOutOfBounds)? == 'L' {
latch_table = shift_table;
}
} else {
@@ -234,7 +225,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) {
result.push_str(&str);
} else {
return Err(Exceptions::illegalState("bad encoding"));
return Err(Exceptions::illegalStateWith("bad encoding"));
}
// result.push_str(decodedBytes.toString(encoding.name()));
//} catch (UnsupportedEncodingException uee) {
@@ -286,7 +277,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> {
Table::Mixed => Ok(MIXED_TABLE[code as usize]),
Table::Digit => Ok(DIGIT_TABLE[code as usize]),
Table::Punct => Ok(PUNCT_TABLE[code as usize]),
_ => Err(Exceptions::illegalState("Bad table")),
_ => Err(Exceptions::illegalStateWith("Bad table")),
}
// switch (table) {
// case UPPER:
@@ -347,7 +338,7 @@ fn correct_bits(
let num_data_codewords = ddata.getNbDatablocks();
let num_codewords = rawbits.len() / codeword_size;
if num_codewords < num_data_codewords as usize {
return Err(Exceptions::format(format!(
return Err(Exceptions::formatWith(format!(
"numCodewords {num_codewords}< numDataCodewords{num_data_codewords}"
)));
}
@@ -380,7 +371,7 @@ fn correct_bits(
// for (int i = 0; i < numDataCodewords; i++) {
// let data_word = data_words[i];
if data_word == &0 || data_word == &mask {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
//throw FormatException.getFormatInstance();
} else if data_word == &1 || data_word == &(mask - 1) {
stuffed_bits += 1;

View File

@@ -127,7 +127,7 @@ impl<'a> Detector<'_> {
|| !self.is_valid(&bulls_eye_corners[2])
|| !self.is_valid(&bulls_eye_corners[3])
{
return Err(Exceptions::notFound("no valid points"));
return Err(Exceptions::notFoundWith("no valid points"));
}
let length = 2 * self.nb_center_layers;
// Get the bits around the bull's eye
@@ -208,7 +208,7 @@ impl<'a> Detector<'_> {
return Ok(shift);
}
}
Err(Exceptions::notFound("rotation failure"))
Err(Exceptions::notFoundWith("rotation failure"))
}
/**
@@ -320,7 +320,7 @@ impl<'a> Detector<'_> {
}
if self.nb_center_layers != 5 && self.nb_center_layers != 7 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
self.compact = self.nb_center_layers == 5;

View File

@@ -53,7 +53,7 @@ pub const WORD_SIZE: [u32; 33] = [
pub fn encode_simple(data: &str) -> Result<AztecCode, Exceptions> {
let Ok(bytes) = encoding::all::ISO_8859_1
.encode(data, encoding::EncoderTrap::Replace) else {
return Err(Exceptions::illegalArgument(format!("'{data}' cannot be encoded as ISO_8859_1")));
return Err(Exceptions::illegalArgumentWith(format!("'{data}' cannot be encoded as ISO_8859_1")));
};
encode_bytes_simple(&bytes)
}
@@ -75,7 +75,7 @@ pub fn encode(
if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) {
encode_bytes(&bytes, minECCPercent, userSpecifiedLayers)
} else {
Err(Exceptions::illegalArgument(format!(
Err(Exceptions::illegalArgumentWith(format!(
"'{data}' cannot be encoded as ISO_8859_1"
)))
}
@@ -102,7 +102,7 @@ pub fn encode_with_charset(
if let Ok(bytes) = charset.encode(data, encoding::EncoderTrap::Strict) {
encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset)
} else {
Err(Exceptions::illegalArgument(format!(
Err(Exceptions::illegalArgumentWith(format!(
"'{data}' cannot be encoded as ISO_8859_1"
)))
}
@@ -178,7 +178,7 @@ pub fn encode_bytes_with_charset(
MAX_NB_BITS
})
{
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Illegal value {user_specified_layers} for layers"
)));
}
@@ -187,13 +187,13 @@ pub fn encode_bytes_with_charset(
let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size);
stuffed_bits = stuffBits(&bits, word_size as usize)?;
if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Data to large for user specified layer",
));
}
if compact && stuffed_bits.getSize() as u32 > word_size * 64 {
// Compact format only allows 64 data words, though C4 can hold more words than that
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Data to large for user specified layer",
));
}
@@ -207,7 +207,7 @@ pub fn encode_bytes_with_charset(
loop {
// for (int i = 0; ; i++) {
if i > MAX_NB_BITS {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Data too large for an Aztec code",
));
}
@@ -482,7 +482,7 @@ fn getGF(wordSize: usize) -> Result<GenericGFRef, Exceptions> {
8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)),
10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)),
12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)),
_ => Err(Exceptions::illegalArgument(format!(
_ => Err(Exceptions::illegalArgumentWith(format!(
"Unsupported word size {wordSize}"
))),
}

View File

@@ -248,7 +248,9 @@ impl HighLevelEncoder {
initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?;
}
} else {
return Err(Exceptions::illegalArgument("No ECI code for character set"));
return Err(Exceptions::illegalArgumentWith(
"No ECI code for character set",
));
}
// if self.charset != null {
// CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset);

View File

@@ -80,7 +80,7 @@ impl State {
token.add(0, 3); // 0: FNC1
} else */
if eci > 999999 {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"ECI code must be between 0 and 999999",
));
// throw new IllegalArgumentException("ECI code must be between 0 and 999999");
@@ -88,7 +88,7 @@ impl State {
let Ok(eci_digits) = encoding::all::ISO_8859_1
.encode(&format!("{eci}"), encoding::EncoderTrap::Strict)
else {
return Err(Exceptions::illegalArgumentEmpty())
return Err(Exceptions::illegalArgument)
};
// let eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1);
token.add(eci_digits.len() as i32, 3); // 1-6: number of ECI digits

View File

@@ -31,7 +31,7 @@ impl TokenType {
match self {
TokenType::Simple(a) => a.appendTo(bit_array, text),
TokenType::BinaryShift(a) => a.appendTo(bit_array, text),
TokenType::Empty => Err(Exceptions::illegalState(
TokenType::Empty => Err(Exceptions::illegalStateWith(
"cannot appendTo on Empty final item",
)),
}

View File

@@ -120,17 +120,17 @@ impl AddressBookParsedRXingResult {
geo: Vec<String>,
) -> Result<Self, Exceptions> {
if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Phone numbers and types lengths differ",
));
}
if emails.len() != email_types.len() && !email_types.is_empty() {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Emails and types lengths differ",
));
}
if addresses.len() != address_types.len() && !address_types.is_empty() {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Addresses and types lengths differ",
));
}

View File

@@ -166,7 +166,7 @@ impl CalendarParsedRXingResult {
*/
fn parseDate(when: String) -> Result<i64, Exceptions> {
if !DATE_TIME.is_match(&when) {
return Err(Exceptions::parse(when));
return Err(Exceptions::parseWith(when));
}
if when.len() == 8 {
// Show only year/month/day
@@ -177,20 +177,14 @@ impl CalendarParsedRXingResult {
// http://code.google.com/p/android/issues/detail?id=8330
return match Utc.datetime_from_str(&format!("{}T000000Z", &when,), date_format_string) {
Ok(dtm) => Ok(dtm.timestamp()),
Err(e) => Err(Exceptions::parse(e.to_string())),
Err(e) => Err(Exceptions::parseWith(e.to_string())),
};
}
// The when string can be local time, or UTC if it ends with a Z
if when.len() == 16
&& when
.chars()
.nth(15)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
== 'Z'
{
if when.len() == 16 && when.chars().nth(15).ok_or(Exceptions::indexOutOfBounds)? == 'Z' {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") {
Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()),
Err(e) => Err(Exceptions::parse(format!("couldn't parse string: {e}"))),
Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))),
};
}
// Try once more, with weird tz formatting
@@ -200,14 +194,14 @@ impl CalendarParsedRXingResult {
let tz_parsed: Tz = match tz_part.parse() {
Ok(time_zone) => time_zone,
Err(e) => {
return Err(Exceptions::parse(format!(
return Err(Exceptions::parseWith(format!(
"couldn't parse timezone '{tz_part}': {e}"
)))
}
};
return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()),
Err(e) => Err(Exceptions::parse(format!("couldn't parse string: {e}"))),
Err(e) => Err(Exceptions::parseWith(format!("couldn't parse string: {e}"))),
};
}
@@ -215,7 +209,9 @@ impl CalendarParsedRXingResult {
if when.len() == 15 {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.timestamp()),
Err(e) => Err(Exceptions::parse(format!("couldn't parse local time: {e}"))),
Err(e) => Err(Exceptions::parseWith(format!(
"couldn't parse local time: {e}"
))),
};
}
Self::parseDateTimeString(&when)
@@ -252,7 +248,7 @@ impl CalendarParsedRXingResult {
let z = parseable
.as_str()
.parse::<i64>()
.map_err(|e| Exceptions::parse(e.to_string()))?;
.map_err(|e| Exceptions::parseWith(e.to_string()))?;
durationMS += unit * z;
}
}
@@ -277,7 +273,7 @@ impl CalendarParsedRXingResult {
if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") {
Ok(dtm.timestamp())
} else {
Err(Exceptions::parse(format!(
Err(Exceptions::parseWith(format!(
"Couldn't parse {dateTimeString}"
)))
}

View File

@@ -300,7 +300,7 @@ pub fn urlDecode(encoded: &str) -> Result<String, Exceptions> {
if let Ok(decoded) = decode(encoded) {
Ok(decoded.to_string())
} else {
Err(Exceptions::illegalState("UnsupportedEncodingException"))
Err(Exceptions::illegalStateWith("UnsupportedEncodingException"))
}
}

View File

@@ -71,16 +71,9 @@ fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
let mut sum = 0;
for i in 0..vin.len() {
sum += vin_position_weight(i + 1)? as u32
* vin_char_value(
vin.chars()
.nth(i)
.ok_or(Exceptions::illegalArgumentEmpty())?,
)?;
* vin_char_value(vin.chars().nth(i).ok_or(Exceptions::illegalArgument)?)?;
}
let check_to_char = vin
.chars()
.nth(8)
.ok_or(Exceptions::illegalArgumentEmpty())?;
let check_to_char = vin.chars().nth(8).ok_or(Exceptions::illegalArgument)?;
let expected_check_char = check_char((sum % 11) as u8)?;
Ok(check_to_char == expected_check_char)
}
@@ -91,7 +84,7 @@ fn vin_char_value(c: char) -> Result<u32, Exceptions> {
'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1),
'S'..='Z' => Ok((c as u8 as u32 - b'S' as u32) + 2),
'0'..='9' => Ok(c as u8 as u32 - b'0' as u32),
_ => Err(Exceptions::illegalArgument("vin char out of range")),
_ => Err(Exceptions::illegalArgumentWith("vin char out of range")),
}
}
@@ -101,7 +94,7 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
8 => Ok(10),
9 => Ok(0),
10..=17 => Ok(19 - position),
_ => Err(Exceptions::illegalArgument(
_ => Err(Exceptions::illegalArgumentWith(
"vin position weight out of bounds",
)),
}
@@ -111,7 +104,7 @@ fn check_char(remainder: u8) -> Result<char, Exceptions> {
match remainder {
0..=9 => Ok((b'0' + remainder) as char),
10 => Ok('X'),
_ => Err(Exceptions::illegalArgument("remainder too high")),
_ => Err(Exceptions::illegalArgumentWith("remainder too high")),
}
}
@@ -124,7 +117,7 @@ fn model_year(c: char) -> Result<u32, Exceptions> {
'V'..='Y' => Ok((c as u8 as u32 - b'V' as u32) + 1997),
'1'..='9' => Ok((c as u8 as u32 - b'1' as u32) + 2001),
'A'..='D' => Ok((c as u8 as u32 - b'A' as u32) + 2010),
_ => Err(Exceptions::illegalArgument(
_ => Err(Exceptions::illegalArgumentWith(
"model year argument out of range",
)),
}

View File

@@ -168,7 +168,7 @@ impl BitArray {
pub fn setRange(&mut self, start: usize, end: usize) -> Result<(), Exceptions> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::illegalArgumentEmpty());
return Err(Exceptions::illegalArgument);
}
if end == start {
return Ok(());
@@ -211,7 +211,7 @@ impl BitArray {
pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool, Exceptions> {
let mut end = end;
if end < start || end > self.size {
return Err(Exceptions::illegalArgumentEmpty());
return Err(Exceptions::illegalArgument);
}
if end == start {
return Ok(true); // empty range matches
@@ -253,7 +253,7 @@ impl BitArray {
*/
pub fn appendBits(&mut self, value: u32, num_bits: usize) -> Result<(), Exceptions> {
if num_bits > 32 {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"num bits must be between 0 and 32",
));
}
@@ -286,7 +286,7 @@ impl BitArray {
pub fn xor(&mut self, other: &BitArray) -> Result<(), Exceptions> {
if self.size != other.size {
return Err(Exceptions::illegalArgument("Sizes don't match"));
return Err(Exceptions::illegalArgumentWith("Sizes don't match"));
}
for i in 0..self.bits.len() {
//for (int i = 0; i < bits.length; i++) {

View File

@@ -65,7 +65,7 @@ impl BitMatrix {
*/
pub fn new(width: u32, height: u32) -> Result<Self, Exceptions> {
if width < 1 || height < 1 {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Both dimensions must be greater than 0",
));
}
@@ -137,12 +137,12 @@ impl BitMatrix {
if string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
== '\n'
|| string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
== '\r'
{
if bitsPos > rowStartPos {
@@ -151,7 +151,7 @@ impl BitMatrix {
first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::illegalArgument("row lengths do not match"));
return Err(Exceptions::illegalArgumentWith("row lengths do not match"));
}
rowStartPos = bitsPos;
nRows += 1;
@@ -166,7 +166,7 @@ impl BitMatrix {
bits[bitsPos] = false;
bitsPos += 1;
} else {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"illegal character encountered: {}",
string_representation[pos..].to_owned()
)));
@@ -180,7 +180,7 @@ impl BitMatrix {
// first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::illegalArgument("row lengths do not match"));
return Err(Exceptions::illegalArgumentWith("row lengths do not match"));
}
nRows += 1;
}
@@ -307,7 +307,7 @@ impl BitMatrix {
pub fn xor(&mut self, mask: &BitMatrix) -> Result<(), Exceptions> {
if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size
{
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"input matrix dimensions do not match",
));
}
@@ -359,14 +359,14 @@ impl BitMatrix {
// ));
// }
if height < 1 || width < 1 {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"height and width must be at least 1",
));
}
let right = left + width;
let bottom = top + height;
if bottom > self.height || right > self.width {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"the region must fit inside the matrix",
));
}
@@ -440,7 +440,7 @@ impl BitMatrix {
self.rotate180();
Ok(())
}
_ => Err(Exceptions::illegalArgument(
_ => Err(Exceptions::illegalArgumentWith(
"degrees must be a multiple of 0, 90, 180, or 270",
)),
}

View File

@@ -70,7 +70,7 @@ impl BitSource {
*/
pub fn readBits(&mut self, numBits: usize) -> Result<u32, Exceptions> {
if !(1..=32).contains(&numBits) || numBits > self.available() {
return Err(Exceptions::illegalArgument(numBits.to_string()));
return Err(Exceptions::illegalArgumentWith(numBits.to_string()));
}
let mut result: u32 = 0;

View File

@@ -244,7 +244,7 @@ impl CharacterSetECI {
28 => Ok(CharacterSetECI::Big5),
29 => Ok(CharacterSetECI::GB18030),
30 => Ok(CharacterSetECI::EUC_KR),
_ => Err(Exceptions::notFound("Bad ECI Value")),
_ => Err(Exceptions::notFoundWith("Bad ECI Value")),
}
}

View File

@@ -67,7 +67,7 @@ impl GridSampler for DefaultGridSampler {
transform: &PerspectiveTransform,
) -> Result<BitMatrix, Exceptions> {
if dimensionX == 0 || dimensionY == 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut bits = BitMatrix::new(dimensionX, dimensionY)?;
let mut points = vec![0.0; 2 * dimensionX as usize];
@@ -98,7 +98,7 @@ impl GridSampler for DefaultGridSampler {
// }
if image
.try_get(points[x] as u32, points[x + 1] as u32)
.ok_or(Exceptions::notFound(
.ok_or(Exceptions::notFoundWith(
"index out of bounds, see documentation in file for explanation",
))?
{

View File

@@ -200,13 +200,13 @@ impl<'a> MonochromeRectangleDetector<'_> {
}
}
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
lastRange_z = range;
y += deltaY;
x += deltaX
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**

View File

@@ -77,7 +77,7 @@ impl<'a> WhiteRectangleDetector<'_> {
|| downInit >= image.getHeight() as i32
|| rightInit >= image.getWidth() as i32
{
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(WhiteRectangleDetector {
@@ -223,7 +223,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if z.is_none() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut t: Option<RXingResultPoint> = None;
@@ -241,7 +241,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if t.is_none() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut x: Option<RXingResultPoint> = None;
@@ -259,7 +259,7 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if x.is_none() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut y: Option<RXingResultPoint> = None;
@@ -277,12 +277,12 @@ impl<'a> WhiteRectangleDetector<'_> {
}
if y.is_none() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(self.center_edges(&y.unwrap(), &z.unwrap(), &x.unwrap(), &t.unwrap()))
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -233,7 +233,7 @@ impl GlobalHistogramBinarizer {
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
if secondPeak - firstPeak <= numBuckets / 16 {
return Err(Exceptions::notFound(
return Err(Exceptions::notFoundWith(
"secondPeak - firstPeak <= numBuckets / 16 ",
));
}

View File

@@ -145,7 +145,7 @@ pub trait GridSampler {
let x = points[offset] as i32;
let y = points[offset + 1] as i32;
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
nudged = false;
if x == -1 {
@@ -172,7 +172,7 @@ pub trait GridSampler {
let x = points[offset as usize] as i32;
let y = points[offset as usize + 1] as i32;
if x < -1 || x > width as i32 || y < -1 || y > height as i32 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
nudged = false;
if x == -1 {

View File

@@ -67,10 +67,10 @@ impl ECIInput for MinimalECIInput {
*/
fn charAt(&self, index: usize) -> Result<char, Exceptions> {
if index >= self.length() {
return Err(Exceptions::indexOutOfBounds(index.to_string()));
return Err(Exceptions::indexOutOfBoundsWith(index.to_string()));
}
if self.isECI(index as u32)? {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"value at {index} is not a character but an ECI"
)));
}
@@ -103,13 +103,13 @@ impl ECIInput for MinimalECIInput {
*/
fn subSequence(&self, start: usize, end: usize) -> Result<Vec<char>, Exceptions> {
if start > end || end > self.length() {
return Err(Exceptions::indexOutOfBoundsEmpty());
return Err(Exceptions::indexOutOfBounds);
}
let mut result = String::new();
for i in start..end {
// for (int i = start; i < end; i++) {
if self.isECI(i as u32)? {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"value at {i} is not a character but an ECI"
)));
}
@@ -131,7 +131,7 @@ impl ECIInput for MinimalECIInput {
*/
fn isECI(&self, index: u32) -> Result<bool, Exceptions> {
if index >= self.length() as u32 {
return Err(Exceptions::indexOutOfBoundsEmpty());
return Err(Exceptions::indexOutOfBounds);
}
Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX)
}
@@ -156,10 +156,10 @@ impl ECIInput for MinimalECIInput {
*/
fn getECIValue(&self, index: usize) -> Result<i32, Exceptions> {
if index >= self.length() {
return Err(Exceptions::indexOutOfBoundsEmpty());
return Err(Exceptions::indexOutOfBounds);
}
if !self.isECI(index as u32)? {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"value at {index} is not an ECI but a character"
)));
}
@@ -248,7 +248,7 @@ impl MinimalECIInput {
*/
pub fn isFNC1(&self, index: usize) -> Result<bool, Exceptions> {
if index >= self.length() {
return Err(Exceptions::indexOutOfBoundsEmpty());
return Err(Exceptions::indexOutOfBounds);
}
Ok(self.bytes[index] == 1000)
}

View File

@@ -19,7 +19,7 @@ impl OtsuLevelBinarizer {
fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result<BitMatrix, Exceptions> {
let image_buffer = {
let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.getWidth() as u32, source.getHeight() as u32, source.getMatrix()) else {
return Err(Exceptions::illegalArgumentEmpty())
return Err(Exceptions::illegalArgument)
};
buff
};

View File

@@ -133,7 +133,7 @@ impl GenericGF {
*/
pub fn log(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 {
return Err(Exceptions::illegalArgumentEmpty());
return Err(Exceptions::illegalArgument);
}
// let pos: usize = a.try_into().unwrap();
Ok(self.logTable[a as usize])
@@ -144,7 +144,7 @@ impl GenericGF {
*/
pub fn inverse(&self, a: i32) -> Result<i32, Exceptions> {
if a == 0 {
return Err(Exceptions::arithmeticEmpty());
return Err(Exceptions::arithmetic);
}
let log_t_loc: usize = a as usize;
let loc: usize = ((self.size as i32) - self.logTable[log_t_loc] - 1) as usize;

View File

@@ -49,7 +49,9 @@ impl GenericGFPoly {
*/
pub fn new(field: GenericGFRef, coefficients: &[i32]) -> Result<Self, Exceptions> {
if coefficients.is_empty() {
return Err(Exceptions::illegalArgument("coefficients cannot be empty"));
return Err(Exceptions::illegalArgumentWith(
"coefficients cannot be empty",
));
}
Ok(Self {
field,
@@ -138,7 +140,7 @@ impl GenericGFPoly {
pub fn addOrSubtract(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"GenericGFPolys do not have same GenericGF field",
));
}
@@ -175,7 +177,7 @@ impl GenericGFPoly {
pub fn multiply(&self, other: &GenericGFPoly) -> Result<GenericGFPoly, Exceptions> {
if self.field != other.field {
//if (!field.equals(other.field)) {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"GenericGFPolys do not have same GenericGF field",
));
}
@@ -250,12 +252,12 @@ impl GenericGFPoly {
other: &GenericGFPoly,
) -> Result<(GenericGFPoly, GenericGFPoly), Exceptions> {
if self.field != other.field {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"GenericGFPolys do not have same GenericGF field",
));
}
if other.isZero() {
return Err(Exceptions::illegalArgument("Divide by 0"));
return Err(Exceptions::illegalArgumentWith("Divide by 0"));
}
let mut quotient = self.getZero();
@@ -264,7 +266,7 @@ impl GenericGFPoly {
let denominator_leading_term = other.getCoefficient(other.getDegree());
let inverse_denominator_leading_term = match self.field.inverse(denominator_leading_term) {
Ok(val) => val,
Err(_issue) => return Err(Exceptions::illegalArgument("arithmetic issue")),
Err(_issue) => return Err(Exceptions::illegalArgumentWith("arithmetic issue")),
};
while remainder.getDegree() >= other.getDegree() && !remainder.isZero() {

View File

@@ -77,7 +77,7 @@ impl ReedSolomonDecoder {
return Ok(0);
}
let Ok(syndrome) = GenericGFPoly::new(self.field, &syndromeCoefficients) else {
return Err(Exceptions::reedSolomonEmpty());
return Err(Exceptions::reedSolomon);
};
let sigmaOmega = self.runEuclideanAlgorithm(
&GenericGF::buildMonomial(self.field, twoS as usize, 1),
@@ -92,11 +92,11 @@ impl ReedSolomonDecoder {
//for (int i = 0; i < errorLocations.length; i++) {
let log_value = self.field.log(errorLocations[i] as i32)?;
if log_value > received.len() as i32 - 1 {
return Err(Exceptions::reedSolomon("Bad error location"));
return Err(Exceptions::reedSolomonWith("Bad error location"));
}
let position: isize = received.len() as isize - 1 - log_value as isize;
if position < 0 {
return Err(Exceptions::reedSolomon("Bad error location"));
return Err(Exceptions::reedSolomonWith("Bad error location"));
}
received[position as usize] =
GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]);
@@ -134,7 +134,7 @@ impl ReedSolomonDecoder {
// Divide rLastLast by rLast, with quotient in q and remainder in r
if rLast.isZero() {
// Oops, Euclidean algorithm already terminated?
return Err(Exceptions::reedSolomon("r_{i-1} was zero"));
return Err(Exceptions::reedSolomonWith("r_{i-1} was zero"));
}
r = rLastLast;
let mut q = r.getZero();
@@ -152,7 +152,7 @@ impl ReedSolomonDecoder {
t = (q.multiply(&tLast)?).addOrSubtract(&tLastLast)?;
if r.getDegree() >= rLast.getDegree() {
return Err(Exceptions::reedSolomon(format!(
return Err(Exceptions::reedSolomonWith(format!(
"Division algorithm failed to reduce polynomial? r: {r}, rLast: {rLast}"
)));
}
@@ -160,12 +160,12 @@ impl ReedSolomonDecoder {
let sigmaTildeAtZero = t.getCoefficient(0);
if sigmaTildeAtZero == 0 {
return Err(Exceptions::reedSolomon("sigmaTilde(0) was zero"));
return Err(Exceptions::reedSolomonWith("sigmaTilde(0) was zero"));
}
let inverse = match self.field.inverse(sigmaTildeAtZero) {
Ok(res) => res,
Err(_err) => return Err(Exceptions::reedSolomon("ArithmetricException")),
Err(_err) => return Err(Exceptions::reedSolomonWith("ArithmetricException")),
};
let sigma = t.multiply_with_scalar(inverse);
let omega = r.multiply_with_scalar(inverse);
@@ -193,7 +193,7 @@ impl ReedSolomonDecoder {
}
}
if e != numErrors {
return Err(Exceptions::reedSolomon(
return Err(Exceptions::reedSolomonWith(
"Error locator degree does not match number of roots",
));
}

View File

@@ -73,11 +73,11 @@ impl ReedSolomonEncoder {
pub fn encode(&mut self, to_encode: &mut Vec<i32>, ec_bytes: usize) -> Result<(), Exceptions> {
if ec_bytes == 0 {
return Err(Exceptions::illegalArgument("No error correction bytes"));
return Err(Exceptions::illegalArgumentWith("No error correction bytes"));
}
let data_bytes = to_encode.len() - ec_bytes;
if data_bytes == 0 {
return Err(Exceptions::illegalArgument("No data bytes provided"));
return Err(Exceptions::illegalArgumentWith("No data bytes provided"));
}
let fld = self.field;
let generator = self.buildGenerator(ec_bytes);
@@ -86,9 +86,7 @@ impl ReedSolomonEncoder {
//System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);
let mut info = GenericGFPoly::new(fld, &info_coefficients)?;
info = info.multiply_by_monomial(ec_bytes, 1)?;
let remainder = &info
.divide(generator.ok_or(Exceptions::reedSolomonEmpty())?)?
.1;
let remainder = &info.divide(generator.ok_or(Exceptions::reedSolomon)?)?.1;
let coefficients = remainder.getCoefficients();
let num_zero_coefficients = ec_bytes - coefficients.len();
for i in 0..num_zero_coefficients {

View File

@@ -105,7 +105,7 @@ impl Reader for DataMatrixReader {
DECODER.decode(&bits)?
}
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
};
// decoderRXingResult = DECODER.decode(detectorRXingResult.getBits())?;
@@ -181,10 +181,10 @@ impl DataMatrixReader {
*/
fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let Some(leftTopBlack) = image.getTopLeftOnBit() else {
return Err(Exceptions::notFoundEmpty())
return Err(Exceptions::notFound)
};
let Some(rightBottomBlack) = image.getBottomRightOnBit()else {
return Err(Exceptions::notFoundEmpty())
return Err(Exceptions::notFound)
};
let moduleSize = Self::moduleSize(&leftTopBlack, image)?;
@@ -197,7 +197,7 @@ impl DataMatrixReader {
let matrixWidth = (right as i32 - left as i32 + 1) / moduleSize as i32;
let matrixHeight = (bottom as i32 - top as i32 + 1) / moduleSize as i32;
if matrixWidth <= 0 || matrixHeight <= 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
// throw NotFoundException.getNotFoundInstance();
}
@@ -234,12 +234,12 @@ impl DataMatrixReader {
x += 1;
}
if x == width {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let moduleSize = x - leftTopBlack[0];
if moduleSize == 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(moduleSize)

View File

@@ -60,17 +60,17 @@ impl Writer for DataMatrixWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if contents.is_empty() {
return Err(Exceptions::illegalArgument("Found empty contents"));
return Err(Exceptions::illegalArgumentWith("Found empty contents"));
}
if format != &BarcodeFormat::DATA_MATRIX {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Can only encode DATA_MATRIX, but got {format:?}"
)));
}
if width < 0 || height < 0 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested dimensions can't be negative: {width}x{height}"
)));
}
@@ -121,7 +121,7 @@ impl Writer for DataMatrixWriter {
if hasEncodingHint {
let Some(EncodeHintValue::CharacterSet(char_set_name)) =
hints.get(&EncodeHintType::CHARACTER_SET) else {
return Err(Exceptions::illegalArgument("charset does not exist"))
return Err(Exceptions::illegalArgumentWith("charset does not exist"))
};
charset = encoding::label::encoding_from_whatwg_label(char_set_name);
// charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
@@ -155,7 +155,7 @@ impl Writer for DataMatrixWriter {
let symbol_lookup = SymbolInfoLookup::new();
let Some(symbolInfo) = symbol_lookup.lookup_with_codewords_shape_size_fail(encoded.chars().count() as u32, *shape, &minSize, &maxSize, true)? else {
return Err(Exceptions::notFound("symbol info is bad"))
return Err(Exceptions::notFoundWith("symbol info is bad"))
};
//2. step: ECC generation

View File

@@ -34,7 +34,7 @@ impl BitMatrixParser {
pub fn new(bitMatrix: &BitMatrix) -> Result<Self, Exceptions> {
let dimension = bitMatrix.getHeight();
if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
let version = Self::readVersion(bitMatrix)?;
@@ -178,7 +178,7 @@ impl BitMatrixParser {
}
if resultOffset != self.version.getTotalCodewords() as usize {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
Ok(result)
@@ -456,7 +456,7 @@ impl BitMatrixParser {
let symbolSizeColumns = version.getSymbolSizeColumns();
if bitMatrix.getHeight() != symbolSizeRows {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Dimension of bitMatrix must match the version size",
));
}

View File

@@ -138,7 +138,7 @@ impl DataBlock {
}
if rawCodewordsOffset != rawCodewords.len() {
return Err(Exceptions::illegalArgumentEmpty());
return Err(Exceptions::illegalArgument);
}
Ok(result)

View File

@@ -158,7 +158,7 @@ pub fn decode(bytes: &[u8], is_flipped: bool) -> Result<DecoderRXingResult, Exce
isECIencoded = true; // ECI detection only, atm continue decoding as ASCII
mode = Mode::ASCII_ENCODE;
}
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
}
if !(mode != Mode::PAD_ENCODE && bits.available() > 0) {
@@ -225,14 +225,14 @@ fn decodeAsciiSegment(
loop {
let mut oneByte = bits.readBits(8)?;
match oneByte {
0 => return Err(Exceptions::formatEmpty()),
0 => return Err(Exceptions::format),
1..=128 => {
// ASCII data (ASCII value + 1)
if upperShift {
oneByte += 128;
//upperShift = false;
}
result.append_char(char::from_u32(oneByte - 1).ok_or(Exceptions::parseEmpty())?);
result.append_char(char::from_u32(oneByte - 1).ok_or(Exceptions::parse)?);
return Ok(Mode::ASCII_ENCODE);
}
129 => return Ok(Mode::PAD_ENCODE), // Pad
@@ -278,7 +278,7 @@ fn decodeAsciiSegment(
if !firstCodeword
// Must be first ISO 16022:2006 5.6.1
{
return Err(Exceptions::format(
return Err(Exceptions::formatWith(
"structured append tag must be first code word",
));
}
@@ -331,7 +331,7 @@ fn decodeAsciiSegment(
// Not to be used in ASCII encodation
// but work around encoders that end with 254, latch back to ASCII
if oneByte != 254 || bits.available() != 0 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
}
@@ -385,25 +385,22 @@ fn decodeC40Segment(
let c40char = C40_BASIC_SET_CHARS[cValue as usize];
if upperShift {
result.append_char(
char::from_u32(c40char as u32 + 128)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?,
);
upperShift = false;
} else {
result.append_char(c40char);
}
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
1 => {
if upperShift {
result.append_char(
char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::parse)?);
upperShift = false;
} else {
result.append_char(char::from_u32(cValue).ok_or(Exceptions::parseEmpty())?);
result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?);
}
shift = 0;
}
@@ -412,8 +409,7 @@ fn decodeC40Segment(
let c40char = C40_SHIFT2_SET_CHARS[cValue as usize];
if upperShift {
result.append_char(
char::from_u32(c40char as u32 + 128)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32(c40char as u32 + 128).ok_or(Exceptions::parse)?,
);
upperShift = false;
} else {
@@ -432,26 +428,22 @@ fn decodeC40Segment(
upperShift = true
}
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
}
}
shift = 0;
}
3 => {
if upperShift {
result.append_char(
char::from_u32(cValue + 224).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 224).ok_or(Exceptions::parse)?);
upperShift = false;
} else {
result.append_char(
char::from_u32(cValue + 96).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 96).ok_or(Exceptions::parse)?);
}
shift = 0;
}
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
}
}
if bits.available() == 0 {
@@ -500,25 +492,22 @@ fn decodeTextSegment(
let textChar = TEXT_BASIC_SET_CHARS[cValue as usize];
if upperShift {
result.append_char(
char::from_u32(textChar as u32 + 128)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?,
);
upperShift = false;
} else {
result.append_char(textChar);
}
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
1 => {
if upperShift {
result.append_char(
char::from_u32(cValue + 128).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 128).ok_or(Exceptions::parse)?);
upperShift = false;
} else {
result.append_char(char::from_u32(cValue).ok_or(Exceptions::parseEmpty())?);
result.append_char(char::from_u32(cValue).ok_or(Exceptions::parse)?);
}
shift = 0;
}
@@ -529,8 +518,7 @@ fn decodeTextSegment(
let textChar = TEXT_SHIFT2_SET_CHARS[cValue as usize];
if upperShift {
result.append_char(
char::from_u32(textChar as u32 + 128)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?,
);
upperShift = false;
} else {
@@ -549,7 +537,7 @@ fn decodeTextSegment(
upperShift = true
}
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
}
}
shift = 0;
@@ -559,8 +547,7 @@ fn decodeTextSegment(
let textChar = TEXT_SHIFT3_SET_CHARS[cValue as usize];
if upperShift {
result.append_char(
char::from_u32(textChar as u32 + 128)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32(textChar as u32 + 128).ok_or(Exceptions::parse)?,
);
upperShift = false;
} else {
@@ -568,11 +555,11 @@ fn decodeTextSegment(
}
shift = 0;
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
}
}
if bits.available() == 0 {
@@ -638,16 +625,12 @@ fn decodeAnsiX12Segment(
_ => {
if cValue < 14 {
// 0 - 9
result.append_char(
char::from_u32(cValue + 44).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 44).ok_or(Exceptions::parse)?);
} else if cValue < 40 {
// A - Z
result.append_char(
char::from_u32(cValue + 51).ok_or(Exceptions::parseEmpty())?,
);
result.append_char(char::from_u32(cValue + 51).ok_or(Exceptions::parse)?);
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
}
@@ -702,7 +685,7 @@ fn decodeEdifactSegment(
// no 1 in the leading (6th) bit
edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value
}
result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::parseEmpty())?);
result.append_char(char::from_u32(edifactValue).ok_or(Exceptions::parse)?);
}
if bits.available() == 0 {
@@ -747,7 +730,7 @@ fn decodeBase256Segment(
// Have seen this particular error in the wild, such as at
// http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
if bits.available() < 8 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
*byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
codewordPosition += 1;
@@ -755,7 +738,7 @@ fn decodeBase256Segment(
result.append_string(
&encoding::all::ISO_8859_1
.decode(&bytes, encoding::DecoderTrap::Strict)
.map_err(|e| Exceptions::parse(e))?,
.map_err(|e| Exceptions::parseWith(e))?,
);
byteSegments.push(bytes);

View File

@@ -105,7 +105,7 @@ impl Version {
numColumns: u32,
) -> Result<&'static Version, Exceptions> {
if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
for version in VERSIONS.iter() {
@@ -114,7 +114,7 @@ impl Version {
}
}
Err(Exceptions::formatEmpty())
Err(Exceptions::format)
}
/**

View File

@@ -53,7 +53,7 @@ impl<'a> Detector<'_> {
if let Some(point) = self.correctTopRight(&points) {
points[3] = point;
} else {
return Err(Exceptions::notFound("point 4 unfound"));
return Err(Exceptions::notFoundWith("point 4 unfound"));
}
// points[3] = self.correctTopRight(&points);
// if points[3] == null {

View File

@@ -254,7 +254,7 @@ fn Scan(
));
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
pub fn detect(
@@ -359,6 +359,6 @@ pub fn detect(
}
// #ifndef __cpp_impl_coroutine
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
// #endif
}

View File

@@ -76,7 +76,7 @@ impl RegressionLine for DMRegressionLine {
fn add(&mut self, p: &RXingResultPoint) -> Result<(), Exceptions> {
if self.direction_inward == RXingResultPoint::default() {
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
self.points.push(*p);
if self.points.len() == 1 {
@@ -241,7 +241,7 @@ impl DMRegressionLine {
end: &RXingResultPoint,
) -> Result<f64, Exceptions> {
if self.points.len() <= 3 {
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
// re-evaluate and filter out all points too far away. required for the gapSizes calculation.
@@ -264,14 +264,8 @@ impl DMRegressionLine {
// calculate the (expected average) distance of two adjacent pixels
let unitPixelDist = RXingResultPoint::length(RXingResultPoint::bresenhamDirection(
&(*self
.points
.last()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
- *self
.points
.first()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?),
&(*self.points.last().ok_or(Exceptions::indexOutOfBounds)?
- *self.points.first().ok_or(Exceptions::indexOutOfBounds)?),
)) as f64;
// calculate the width of 2 modules (first black pixel to first black pixel)
@@ -294,11 +288,7 @@ impl DMRegressionLine {
sumFront
+ self.distance(
end,
&self.project(
self.points
.last()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
),
&self.project(self.points.last().ok_or(Exceptions::indexOutOfBounds)?),
) as f64,
);
modSizes[0] = 0.0; // the first element is an invalid sumBack value, would be pop_front() if vector supported this

View File

@@ -199,7 +199,7 @@ impl<'a> EdgeTracer<'_> {
if self.whiteAt(&pEdge) {
// if we are not making any progress, we still have another endless loop bug
if self.p == RXingResultPoint::centered(&pEdge) {
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
self.p = RXingResultPoint::centered(&pEdge);
@@ -277,7 +277,7 @@ impl<'a> EdgeTracer<'_> {
.points()
.first()
.as_ref()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?),
.ok_or(Exceptions::indexOutOfBounds)?),
) {
return Ok(false);
}
@@ -307,9 +307,9 @@ impl<'a> EdgeTracer<'_> {
.points()
.last()
.as_ref()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?)
.ok_or(Exceptions::indexOutOfBounds)?)
{
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
if !line.points().is_empty()
&& &&self.p
@@ -317,7 +317,7 @@ impl<'a> EdgeTracer<'_> {
.points()
.last()
.as_ref()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
{
return Ok(false);
}
@@ -363,7 +363,7 @@ impl<'a> EdgeTracer<'_> {
line.points()
.last()
.as_ref()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
),
) < 1.0
{
@@ -376,11 +376,7 @@ impl<'a> EdgeTracer<'_> {
} else {
RXingResultPoint::dot(
RXingResultPoint::mainDirection(self.d),
self.p
- line
.points()
.last()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
self.p - line.points().last().ok_or(Exceptions::indexOutOfBounds)?,
)
};
line.add(&self.p)?;
@@ -393,10 +389,7 @@ impl<'a> EdgeTracer<'_> {
}
if !self.updateDirectionFromOrigin(
&(self.p - line.project(&self.p)
+ *line
.points()
.first()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?),
+ *line.points().first().ok_or(Exceptions::indexOutOfBounds)?),
) {
return Ok(false);
}

View File

@@ -26,7 +26,7 @@ pub fn intersect(
l2: &DMRegressionLine,
) -> Result<RXingResultPoint, Exceptions> {
if !(l1.isValid() && l2.isValid()) {
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
let d = l1.a * l2.b - l1.b * l2.a;
let x = (l1.c * l2.b - l1.b * l2.c) / d;

View File

@@ -31,12 +31,12 @@ impl Encoder for ASCIIEncoder {
.getMessage()
.chars()
.nth(context.pos as usize)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
context
.getMessage()
.chars()
.nth(context.pos as usize + 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
)? as u8);
context.pos += 2;
} else {
@@ -73,7 +73,9 @@ impl Encoder for ASCIIEncoder {
}
_ => {
return Err(Exceptions::illegalState(format!("Illegal mode: {newMode}")));
return Err(Exceptions::illegalStateWith(format!(
"Illegal mode: {newMode}"
)));
}
}
} else if high_level_encoder::isExtendedASCII(c) {
@@ -102,7 +104,7 @@ impl ASCIIEncoder {
let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48);
Ok((num + 130) as char)
} else {
Err(Exceptions::illegalArgument(format!(
Err(Exceptions::illegalArgumentWith(format!(
"not digits: {digit1}{digit2}"
)))
}

View File

@@ -53,7 +53,7 @@ impl Encoder for Base256Encoder {
context.updateSymbolInfoWithLength(currentSize);
let mustPad = (context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity()
- currentSize as u32)
> 0;
@@ -62,27 +62,26 @@ impl Encoder for Base256Encoder {
buffer.replace_range(
0..1,
&char::from_u32(dataCount as u32)
.ok_or(Exceptions::parseEmpty())?
.ok_or(Exceptions::parse)?
.to_string(),
);
} else if dataCount <= 1555 {
buffer.replace_range(
0..1,
&char::from_u32((dataCount as u32 / 250) + 249)
.ok_or(Exceptions::parseEmpty())?
.ok_or(Exceptions::parse)?
.to_string(),
);
let (ci_pos, _) = buffer
.char_indices()
.nth(1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
buffer.insert(
ci_pos,
char::from_u32(dataCount as u32 % 250)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
char::from_u32(dataCount as u32 % 250).ok_or(Exceptions::indexOutOfBounds)?,
);
} else {
return Err(Exceptions::illegalState(format!(
return Err(Exceptions::illegalStateWith(format!(
"Message length not in valid ranges: {dataCount}"
)));
}
@@ -92,13 +91,10 @@ impl Encoder for Base256Encoder {
// for (int i = 0, c = buffer.length(); i < c; i++) {
context.writeCodeword(
Self::randomize255State(
buffer
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
buffer.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?,
context.getCodewordCount() as u32 + 1,
)
.ok_or(Exceptions::parseEmpty())? as u8,
.ok_or(Exceptions::parse)? as u8,
);
}
Ok(())

View File

@@ -65,7 +65,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity() as usize
- curCodewordCount;
@@ -140,7 +140,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity() as usize
- curCodewordCount;
let rest = buffer.chars().count() % 3;
@@ -182,7 +182,7 @@ impl C40Encoder {
context: &mut EncoderContext,
buffer: &mut String,
) -> Result<(), Exceptions> {
context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::formatEmpty())?);
context.writeCodewords(&Self::encodeToCodewords(buffer).ok_or(Exceptions::format)?);
buffer.replace_range(0..3, "");
// buffer.delete(0, 3);
Ok(())
@@ -205,7 +205,7 @@ impl C40Encoder {
context.updateSymbolInfoWithLength(curCodewordCount);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity() as usize
- curCodewordCount;
@@ -234,7 +234,9 @@ impl C40Encoder {
context.writeCodeword(C40_UNLATCH);
}
} else {
return Err(Exceptions::illegalState("Unexpected case. Please report!"));
return Err(Exceptions::illegalStateWith(
"Unexpected case. Please report!",
));
}
context.signalEncoderChange(ASCII_ENCODATION);

View File

@@ -164,7 +164,7 @@ impl DefaultPlacement {
.codewords
.chars()
.nth(pos)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as u32;
.ok_or(Exceptions::indexOutOfBounds)? as u32;
v &= 1 << (8 - bit);
self.setBit(col as usize, row as usize, v != 0);

View File

@@ -76,7 +76,7 @@ impl EdifactEncoder {
context.updateSymbolInfo();
let mut available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity()
- context.getCodewordCount() as u32;
let remaining = context.getRemainingCharacters();
@@ -85,7 +85,7 @@ impl EdifactEncoder {
context.updateSymbolInfoWithLength(context.getCodewordCount() + 1);
available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity()
- context.getCodewordCount() as u32;
}
@@ -95,7 +95,7 @@ impl EdifactEncoder {
}
if count > 4 {
return Err(Exceptions::illegalState("Count must not exceed 4"));
return Err(Exceptions::illegalStateWith("Count must not exceed 4"));
}
let restChars = count - 1;
let encoded = Self::encodeToCodewords(buffer)?;
@@ -106,7 +106,7 @@ impl EdifactEncoder {
context.updateSymbolInfoWithLength(context.getCodewordCount() + restChars);
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity()
- context.getCodewordCount() as u32;
if available >= 3 {
@@ -147,30 +147,23 @@ impl EdifactEncoder {
fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> {
let len = sb.chars().count();
if len == 0 {
return Err(Exceptions::illegalState("StringBuilder must not be empty"));
return Err(Exceptions::illegalStateWith(
"StringBuilder must not be empty",
));
}
let c1 = sb
.chars()
.next()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
let c1 = sb.chars().next().ok_or(Exceptions::indexOutOfBounds)?;
let c2 = if len >= 2 {
sb.chars()
.nth(1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
sb.chars().nth(1).ok_or(Exceptions::indexOutOfBounds)?
} else {
0 as char
};
let c3 = if len >= 3 {
sb.chars()
.nth(2)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
sb.chars().nth(2).ok_or(Exceptions::indexOutOfBounds)?
} else {
0 as char
};
let c4 = if len >= 4 {
sb.chars()
.nth(3)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
sb.chars().nth(3).ok_or(Exceptions::indexOutOfBounds)?
} else {
0 as char
};
@@ -180,12 +173,12 @@ impl EdifactEncoder {
let cw2 = (v >> 8) & 255;
let cw3 = v & 255;
let mut res = String::with_capacity(3);
res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBoundsEmpty())?);
res.push(char::from_u32(cw1).ok_or(Exceptions::indexOutOfBounds)?);
if len >= 2 {
res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBoundsEmpty())?);
res.push(char::from_u32(cw2).ok_or(Exceptions::indexOutOfBounds)?);
}
if len >= 3 {
res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBoundsEmpty())?);
res.push(char::from_u32(cw3).ok_or(Exceptions::indexOutOfBounds)?);
}
Ok(res)

View File

@@ -63,10 +63,10 @@ impl<'a> EncoderContext<'_> {
ISO_8859_1_ENCODER
.decode(&encoded_bytes, encoding::DecoderTrap::Strict)
.map_err(|e| {
Exceptions::parse(format!("round trip decode should always work: {e}"))
Exceptions::parseWith(format!("round trip decode should always work: {e}"))
})?
} else {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Message contains characters outside ISO-8859-1 encoding.",
));
};

View File

@@ -154,7 +154,7 @@ const ALOG: [u32; 255] = {
*/
pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String, Exceptions> {
if codewords.chars().count() != symbolInfo.getDataCapacity() as usize {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"The number of codewords does not match the selected symbol",
));
}
@@ -185,7 +185,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
codewords
.chars()
.nth(d)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
);
d += blockCount;
@@ -198,12 +198,12 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
let (char_index, replace_char) = sb
.char_indices()
.nth(symbolInfo.getDataCapacity() as usize + e)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
sb.replace_range(
char_index..(replace_char.len_utf8()),
&ecc.chars()
.nth(pos)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_string(),
);
// sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos));
@@ -228,7 +228,7 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptio
}
}
if table < 0 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Illegal number of error correction codewords specified: {numECWords}"
)));
}
@@ -244,21 +244,21 @@ fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptio
^ codewords
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize;
.ok_or(Exceptions::indexOutOfBounds)? as usize;
for k in (1..numECWords).rev() {
// for (int k = numECWords - 1; k > 0; k--) {
if m != 0 && poly[k] != 0 {
ecc[k] = char::from_u32(
ecc[k - 1] as u32 ^ ALOG[(LOG[m] + LOG[poly[k] as usize]) as usize % 255],
)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else {
ecc[k] = ecc[k - 1];
}
}
if m != 0 && poly[0] != 0 {
ecc[0] = char::from_u32(ALOG[(LOG[m] + LOG[poly[0] as usize]) as usize % 255])
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else {
ecc[0] = 0 as char;
}

View File

@@ -221,18 +221,14 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
if forceC40 {
c40Encoder.encodeMaximalC40(&mut context)?;
encodingMode = context
.getNewEncoding()
.ok_or(Exceptions::illegalStateEmpty())?;
encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?;
context.resetEncoderSignal();
}
while context.hasMoreCharacters() {
encoders[encodingMode].encode(&mut context)?;
if context.getNewEncoding().is_some() {
encodingMode = context
.getNewEncoding()
.ok_or(Exceptions::illegalStateEmpty())?;
encodingMode = context.getNewEncoding().ok_or(Exceptions::illegalState)?;
context.resetEncoderSignal();
}
}
@@ -240,7 +236,7 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
context.updateSymbolInfo();
let capacity = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity();
if len < capacity as usize
&& encodingMode != ASCII_ENCODATION
@@ -611,7 +607,7 @@ pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 {
pub fn illegalCharacter(c: char) -> Result<(), Exceptions> {
// let hex = Integer.toHexString(c);
// hex = "0000".substring(0, 4 - hex.length()) + hex;
Err(Exceptions::illegalArgument(format!(
Err(Exceptions::illegalArgumentWith(format!(
"Illegal character: {c} (0x{c})"
)))
}

View File

@@ -218,7 +218,7 @@ fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<(), Ex
if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none()
|| edges[vertexIndex][edge.getEndMode()?.ordinal()]
.as_ref()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.cachedTotalSize
> edge.cachedTotalSize
{
@@ -635,7 +635,7 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> {
}
if minimalJ < 0 {
return Err(Exceptions::illegalState(format!(
return Err(Exceptions::illegalStateWith(format!(
"Internal error: failed to encode \"{input}\""
)));
}
@@ -669,7 +669,7 @@ impl Edge {
previous: Option<Rc<Edge>>,
) -> Result<Self, Exceptions> {
if fromPosition + characterLength > input.length() as u32 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
let mut size = if let Some(previous) = previous.clone() {
@@ -1276,7 +1276,7 @@ impl RXingResult {
let solution = if let Some(edge) = solution {
edge
} else {
return Err(Exceptions::illegalArgumentEmpty());
return Err(Exceptions::illegalArgument);
};
let input = solution.input.clone();
let mut size = 0;

View File

@@ -128,7 +128,7 @@ impl SymbolInfo {
2 | 4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::illegalState(
_ => Err(Exceptions::illegalStateWith(
"Cannot handle this number of data regions",
)),
}
@@ -140,7 +140,7 @@ impl SymbolInfo {
4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::illegalState(
_ => Err(Exceptions::illegalStateWith(
"Cannot handle this number of data regions",
)),
}
@@ -310,7 +310,7 @@ impl<'a> SymbolInfoLookup<'a> {
}
}
if fail {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Can't find a symbol arrangement that matches the message. Data codewords: {dataCodewords}"
)));
}

View File

@@ -81,7 +81,7 @@ impl X12Encoder {
context.updateSymbolInfo();
let available = context
.getSymbolInfo()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getDataCapacity()
- context.getCodewordCount() as u32;
let count = buffer.chars().count();

View File

@@ -22,110 +22,72 @@ pub enum Exceptions {
ReaderDecodeException(),
}
#[allow(non_upper_case_globals)]
impl Exceptions {
pub fn illegalArgument<I: Into<String>>(x: I) -> Self {
pub const illegalArgument: Self = Self::IllegalArgumentException(None);
pub fn illegalArgumentWith<I: Into<String>>(x: I) -> Self {
Self::IllegalArgumentException(Some(x.into()))
}
pub fn illegalArgumentEmpty() -> Self {
Self::IllegalArgumentException(None)
}
pub fn unsupportedOperation<I: Into<String>>(x: I) -> Self {
pub const unsupportedOperation: Self = Self::UnsupportedOperationException(None);
pub fn unsupportedOperationWith<I: Into<String>>(x: I) -> Self {
Self::UnsupportedOperationException(Some(x.into()))
}
pub fn unsupportedOperationEmpty() -> Self {
Self::UnsupportedOperationException(None)
}
pub fn illegalState<I: Into<String>>(x: I) -> Self {
pub const illegalState: Self = Self::IllegalStateException(None);
pub fn illegalStateWith<I: Into<String>>(x: I) -> Self {
Self::IllegalStateException(Some(x.into()))
}
pub fn illegalStateEmpty() -> Self {
Self::IllegalStateException(None)
}
pub fn arithmetic<I: Into<String>>(x: I) -> Self {
pub const arithmetic: Self = Self::ArithmeticException(None);
pub fn arithmeticWith<I: Into<String>>(x: I) -> Self {
Self::ArithmeticException(Some(x.into()))
}
pub fn arithmeticEmpty() -> Self {
Self::ArithmeticException(None)
}
pub fn notFound<I: Into<String>>(x: I) -> Self {
pub const notFound: Self = Self::NotFoundException(None);
pub fn notFoundWith<I: Into<String>>(x: I) -> Self {
Self::NotFoundException(Some(x.into()))
}
pub fn notFoundEmpty() -> Self {
Self::NotFoundException(None)
}
pub fn format<I: Into<String>>(x: I) -> Self {
pub const format: Self = Self::FormatException(None);
pub fn formatWith<I: Into<String>>(x: I) -> Self {
Self::FormatException(Some(x.into()))
}
pub fn formatEmpty() -> Self {
Self::FormatException(None)
}
pub fn checksum<I: Into<String>>(x: I) -> Self {
pub const checksum: Self = Self::ChecksumException(None);
pub fn checksumWith<I: Into<String>>(x: I) -> Self {
Self::ChecksumException(Some(x.into()))
}
pub fn checksumEmpty() -> Self {
Self::ChecksumException(None)
}
pub fn reader<I: Into<String>>(x: I) -> Self {
pub const reader: Self = Self::ReaderException(None);
pub fn readerWith<I: Into<String>>(x: I) -> Self {
Self::ReaderException(Some(x.into()))
}
pub fn readerEmpty() -> Self {
Self::ReaderException(None)
}
pub fn writer<I: Into<String>>(x: I) -> Self {
pub const writer: Self = Self::WriterException(None);
pub fn writerWith<I: Into<String>>(x: I) -> Self {
Self::WriterException(Some(x.into()))
}
pub fn writerEmpty() -> Self {
Self::WriterException(None)
}
pub fn reedSolomon<I: Into<String>>(x: I) -> Self {
pub const reedSolomon: Self = Self::ReedSolomonException(None);
pub fn reedSolomonWith<I: Into<String>>(x: I) -> Self {
Self::ReedSolomonException(Some(x.into()))
}
pub fn reedSolomonEmpty() -> Self {
Self::ReedSolomonException(None)
}
pub fn indexOutOfBounds<I: Into<String>>(x: I) -> Self {
pub const indexOutOfBounds: Self = Self::IndexOutOfBoundsException(None);
pub fn indexOutOfBoundsWith<I: Into<String>>(x: I) -> Self {
Self::IndexOutOfBoundsException(Some(x.into()))
}
pub fn indexOutOfBoundsEmpty() -> Self {
Self::IndexOutOfBoundsException(None)
}
pub fn runtime<I: Into<String>>(x: I) -> Self {
pub const runtime: Self = Self::RuntimeException(None);
pub fn runtimeWith<I: Into<String>>(x: I) -> Self {
Self::RuntimeException(Some(x.into()))
}
pub fn runtimeEmpty() -> Self {
Self::RuntimeException(None)
}
pub fn parse<I: Into<String>>(x: I) -> Self {
pub const parse: Self = Self::ParseException(None);
pub fn parseWith<I: Into<String>>(x: I) -> Self {
Self::ParseException(Some(x.into()))
}
pub fn parseEmpty() -> Self {
Self::ParseException(None)
}
}
impl fmt::Display for Exceptions {

View File

@@ -35,16 +35,16 @@ pub fn detect_in_svg_with_hints(
let path = PathBuf::from(file_name);
if !path.exists() {
return Err(Exceptions::illegalArgument("file does not exist"));
return Err(Exceptions::illegalArgumentWith("file does not exist"));
}
let Ok(mut file) = File::open(path) else {
return Err(Exceptions::illegalArgument("file cannot be opened"));
return Err(Exceptions::illegalArgumentWith("file cannot be opened"));
};
let mut svg_data = Vec::new();
if file.read_to_end(&mut svg_data).is_err() {
return Err(Exceptions::illegalArgument("file cannot be read"));
return Err(Exceptions::illegalArgumentWith("file cannot be read"));
}
let mut multi_format_reader = MultiFormatReader::default();
@@ -84,16 +84,16 @@ pub fn detect_multiple_in_svg_with_hints(
let path = PathBuf::from(file_name);
if !path.exists() {
return Err(Exceptions::illegalArgument("file does not exist"));
return Err(Exceptions::illegalArgumentWith("file does not exist"));
}
let Ok(mut file) = File::open(path) else {
return Err(Exceptions::illegalArgument("file cannot be opened"));
return Err(Exceptions::illegalArgumentWith("file cannot be opened"));
};
let mut svg_data = Vec::new();
if file.read_to_end(&mut svg_data).is_err() {
return Err(Exceptions::illegalArgument("file cannot be read"));
return Err(Exceptions::illegalArgumentWith("file cannot be read"));
}
let multi_format_reader = MultiFormatReader::default();
@@ -126,7 +126,7 @@ pub fn detect_in_file_with_hints(
hints: &mut DecodingHintDictionary,
) -> Result<RXingResult, Exceptions> {
let Ok(img) = image::open(file_name) else {
return Err(Exceptions::illegalArgument(format!("file '{file_name}' not found or cannot be opened")));
return Err(Exceptions::illegalArgumentWith(format!("file '{file_name}' not found or cannot be opened")));
};
let mut multi_format_reader = MultiFormatReader::default();
@@ -160,7 +160,7 @@ pub fn detect_multiple_in_file_with_hints(
hints: &mut DecodingHintDictionary,
) -> Result<Vec<RXingResult>, Exceptions> {
let img = image::open(file_name)
.map_err(|e| Exceptions::runtime(format!("couldn't read {file_name}: {e}")))?;
.map_err(|e| Exceptions::runtimeWith(format!("couldn't read {file_name}: {e}")))?;
let multi_format_reader = MultiFormatReader::default();
let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader);
@@ -247,7 +247,7 @@ pub fn save_image(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Excepti
let image: image::DynamicImage = bit_matrix.into();
match image.save(file_name) {
Ok(_) => Ok(()),
Err(err) => Err(Exceptions::illegalArgument(format!(
Err(err) => Err(Exceptions::illegalArgumentWith(format!(
"could not save file '{file_name}': {err}"
))),
}
@@ -259,7 +259,7 @@ pub fn save_svg(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exception
match svg::save(file_name, &svg) {
Ok(_) => Ok(()),
Err(err) => Err(Exceptions::illegalArgument(format!(
Err(err) => Err(Exceptions::illegalArgumentWith(format!(
"could not save file '{}': {}",
file_name, err
))),
@@ -294,7 +294,7 @@ pub fn save_file(file_name: &str, bit_matrix: &BitMatrix) -> Result<(), Exceptio
Ok(())
}() {
Ok(_) => Ok(()),
Err(_) => Err(Exceptions::illegalArgument(format!(
Err(_) => Err(Exceptions::illegalArgumentWith(format!(
"could not write to '{file_name}'"
))),
}

View File

@@ -95,7 +95,7 @@ impl LuminanceSource for Luma8LuminanceSource {
}
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, crate::Exceptions> {
Err(crate::Exceptions::unsupportedOperation(
Err(crate::Exceptions::unsupportedOperationWith(
"This luminance source does not support rotation by 45 degrees.",
))
}

View File

@@ -91,7 +91,7 @@ pub trait LuminanceSource {
_width: usize,
_height: usize,
) -> Result<Box<dyn LuminanceSource>, Exceptions> {
Err(Exceptions::unsupportedOperation(
Err(Exceptions::unsupportedOperationWith(
"This luminance source does not support cropping.",
))
}
@@ -118,7 +118,7 @@ pub trait LuminanceSource {
* @return A rotated version of this object.
*/
fn rotateCounterClockwise(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
Err(Exceptions::unsupportedOperation(
Err(Exceptions::unsupportedOperationWith(
"This luminance source does not support rotation by 90 degrees.",
))
}
@@ -130,7 +130,7 @@ pub trait LuminanceSource {
* @return A rotated version of this object.
*/
fn rotateCounterClockwise45(&self) -> Result<Box<dyn LuminanceSource>, Exceptions> {
Err(Exceptions::unsupportedOperation(
Err(Exceptions::unsupportedOperationWith(
"This luminance source does not support rotation by 45 degrees.",
))
}

View File

@@ -86,7 +86,7 @@ pub fn decode(bytes: &[u8], mode: u8) -> Result<DecoderRXingResult, Exceptions>
let pc = getPostCode2(bytes);
let ps2Length = getPostCode2Length(bytes) as usize;
if ps2Length > 10 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
// NumberFormat df = new DecimalFormat("0000000000".substring(0, ps2Length));
// postcode = df.format(pc);

View File

@@ -70,7 +70,7 @@ pub fn decode_with_hints(
correctErrors(&mut codewords, 20, 68, 56, ODD)?;
datawords = vec![0u8; 78];
}
_ => return Err(Exceptions::notFoundEmpty()),
_ => return Err(Exceptions::notFound),
}
datawords[0..10].clone_from_slice(&codewords[0..10]);

View File

@@ -318,7 +318,7 @@ impl Circle<'_> {
pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionResult, Exceptions> {
// find concentric circles
let Some( mut circles) = find_concentric_circles(image) else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
};
// we should have an idea where the center is at this point,
@@ -341,7 +341,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
if try_harder {
continue;
}else {
return Err(Exceptions::notFoundEmpty())
return Err(Exceptions::notFound)
}
};
let grid_sampler = DefaultGridSampler::default();
@@ -378,7 +378,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
if try_harder {
continue;
}else {
return Err(Exceptions::notFoundEmpty())
return Err(Exceptions::notFound)
}
};
return Ok(MaxicodeDetectionResult {
@@ -392,7 +392,7 @@ pub fn detect(image: &BitMatrix, try_harder: bool) -> Result<MaxicodeDetectionRe
});
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/// Locate concentric circles.
@@ -734,7 +734,7 @@ fn box_symbol(
#[cfg(feature = "experimental_features")]
if is_ellipse {
// we don't deal with ellipses yet
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut final_rotation = 0.0;
@@ -1052,9 +1052,7 @@ fn compare_circle(a: &Circle, b: &Circle) -> std::cmp::Ordering {
/// Read appropriate bits from a bitmatrix for the maxicode decoder
pub fn read_bits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let enclosingRectangle = image
.getEnclosingRectangle()
.ok_or(Exceptions::notFoundEmpty())?;
let enclosingRectangle = image.getEnclosingRectangle().ok_or(Exceptions::notFound)?;
let left = enclosingRectangle[0];
let top = enclosingRectangle[1];

View File

@@ -126,10 +126,10 @@ impl MaxiCodeReader {
fn extractPureBits(image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let enclosingRectangleOption = image.getEnclosingRectangle();
if enclosingRectangleOption.is_none() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFoundEmpty())?;
let enclosingRectangle = enclosingRectangleOption.ok_or(Exceptions::notFound)?;
let left = enclosingRectangle[0];
let top = enclosingRectangle[1];

View File

@@ -56,7 +56,7 @@ impl<T: Reader> MultipleBarcodeReader for GenericMultipleBarcodeReader<T> {
let mut results = Vec::new();
self.doDecodeMultiple(image, hints, &mut results, 0, 0, 0);
if results.is_empty() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(results)
}

View File

@@ -53,7 +53,7 @@ impl<'a> MultiDetector<'_> {
let infos = finder.findMulti(hints)?;
if infos.is_empty() {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut result = Vec::new();

View File

@@ -93,7 +93,9 @@ impl<'a> MultiFinderPatternFinder<'_> {
if size < 3 {
// Couldn't find enough finder patterns
return Err(Exceptions::notFound("Couldn't find enough finder patterns"));
return Err(Exceptions::notFoundWith(
"Couldn't find enough finder patterns",
));
}
/*
@@ -210,7 +212,7 @@ impl<'a> MultiFinderPatternFinder<'_> {
if !results.is_empty() {
Ok(results)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -111,7 +111,7 @@ impl MultipleBarcodeReader for QRCodeMultiReader {
// ignore and continue
continue;
} else {
return Err(output.err().unwrap_or(Exceptions::notFoundEmpty()));
return Err(output.err().unwrap_or(Exceptions::notFound));
}
}

View File

@@ -192,6 +192,6 @@ impl MultiFormatReader {
}
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -71,7 +71,7 @@ impl Writer for MultiFormatWriter {
BarcodeFormat::DATA_MATRIX => Box::<DataMatrixWriter>::default(),
BarcodeFormat::AZTEC => Box::<AztecWriter>::default(),
_ => {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"No encoder available for format {format:?}"
)))
}

View File

@@ -65,13 +65,13 @@ impl OneDReader for CodaBarReader {
loop {
let charOffset = self.toNarrowWidePattern(nextStart);
if charOffset == -1 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// Hack: We store the position in the alphabet table into a
// StringBuilder, so that we can access the decoded patterns in
// validatePattern. We'll translate to the actual characters later.
self.decodeRowRXingResult
.push(char::from_u32(charOffset as u32).ok_or(Exceptions::parseEmpty())?);
.push(char::from_u32(charOffset as u32).ok_or(Exceptions::parse)?);
nextStart += 8;
// Stop as soon as we see the end character.
if self.decodeRowRXingResult.chars().count() > 1
@@ -99,7 +99,7 @@ impl OneDReader for CodaBarReader {
// otherwise this is probably a false positive. The exception is if we are
// at the end of the row. (I.e. the barcode barely fits.)
if nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
self.validatePattern(startOffset)?;
@@ -113,8 +113,7 @@ impl OneDReader for CodaBarReader {
.decodeRowRXingResult
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
as usize]
.ok_or(Exceptions::indexOutOfBounds)? as usize]
.to_string(),
);
}
@@ -123,23 +122,23 @@ impl OneDReader for CodaBarReader {
.decodeRowRXingResult
.chars()
.next()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
if !Self::arrayContains(&Self::STARTEND_ENCODING, startchar) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let endchar = self
.decodeRowRXingResult
.chars()
.nth(self.decodeRowRXingResult.chars().count() - 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
if !Self::arrayContains(&Self::STARTEND_ENCODING, endchar) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// remove stop/start characters character and check if a long enough string is contained
if (self.decodeRowRXingResult.chars().count()) <= Self::MIN_CHARACTER_LENGTH as usize {
// Almost surely a false positive ( start + stop + at least 1 character)
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
if !matches!(
@@ -243,7 +242,7 @@ impl CodaBarReader {
.decodeRowRXingResult
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
as usize];
for j in (0_usize..=6).rev() {
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
@@ -282,7 +281,7 @@ impl CodaBarReader {
.decodeRowRXingResult
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
as usize];
for j in (0usize..=6).rev() {
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
@@ -290,7 +289,7 @@ impl CodaBarReader {
let category = (j & 1) + ((pattern as usize) & 1) * 2;
let size = self.counters[(pos + j)];
if (size as f32) < mins[category] || (size as f32) > maxes[category] {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
pattern >>= 1;
}
@@ -311,7 +310,7 @@ impl CodaBarReader {
let mut i = row.getNextUnset(0);
let end = row.getSize();
if i >= end {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut isWhite = true;
let mut count = 0;
@@ -363,7 +362,7 @@ impl CodaBarReader {
i += 2;
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
pub fn arrayContains(array: &[char], key: char) -> bool {

View File

@@ -43,12 +43,12 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
let firstChar = contents
.chars()
.next()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_ascii_uppercase();
let lastChar = contents
.chars()
.nth(contents.chars().count() - 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_ascii_uppercase();
let startsNormal = CodaBarReader::arrayContains(&START_END_CHARS, firstChar);
let endsNormal = CodaBarReader::arrayContains(&START_END_CHARS, lastChar);
@@ -56,7 +56,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
let endsAlt = CodaBarReader::arrayContains(&ALT_START_END_CHARS, lastChar);
if startsNormal {
if !endsNormal {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Invalid start/end guards: {contents}"
)));
}
@@ -64,7 +64,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
contents.to_owned()
} else if startsAlt {
if !endsAlt {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Invalid start/end guards: {contents}"
)));
}
@@ -73,7 +73,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
} else {
// Doesn't start with a guard
if endsNormal || endsAlt {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Invalid start/end guards: {contents}"
)));
}
@@ -93,7 +93,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
) {
resultLength += 10;
} else {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Cannot encode : '{ch}'"
)));
}
@@ -108,7 +108,7 @@ impl OneDimensionalCodeWriter for CodaBarWriter {
let mut c = contents
.chars()
.nth(index)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_ascii_uppercase();
if index == 0 || index == contents.chars().count() - 1 {
// The start/end chars are not in the CodaBarReader.ALPHABET.

View File

@@ -50,7 +50,7 @@ impl OneDReader for Code128Reader {
CODE_START_A => CODE_CODE_A,
CODE_START_B => CODE_CODE_B,
CODE_START_C => CODE_CODE_C,
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
};
let mut done = false;
@@ -100,7 +100,7 @@ impl OneDReader for Code128Reader {
// Take care of illegal start codes
match code {
CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::formatEmpty()),
CODE_START_A | CODE_START_B | CODE_START_C => return Err(Exceptions::format),
_ => {}
}
@@ -294,21 +294,21 @@ impl OneDReader for Code128Reader {
row.getSize().min(nextStart + (nextStart - lastStart) / 2),
false,
)? {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// Pull out from sum the value of the penultimate check code
checksumTotal -= multiplier as usize * lastCode as usize;
// lastCode is the checksum then:
if (checksumTotal % 103) as u8 != lastCode {
return Err(Exceptions::checksumEmpty());
return Err(Exceptions::checksum);
}
// Need to pull out the check digits from string
let resultLength = result.chars().count();
if resultLength == 0 {
// false positive
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// Only bother if the result had at least one character, and if the checksum digit happened to
@@ -329,7 +329,7 @@ impl OneDReader for Code128Reader {
let rawCodesSize = rawCodes.len();
let mut rawBytes = vec![0u8; rawCodesSize];
for (i, rawByte) in rawBytes.iter_mut().enumerate().take(rawCodesSize) {
*rawByte = *rawCodes.get(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?;
*rawByte = *rawCodes.get(i).ok_or(Exceptions::indexOutOfBounds)?;
}
let mut resultObject = RXingResult::new(
&result,
@@ -403,7 +403,7 @@ impl Code128Reader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn decodeCode(
@@ -428,7 +428,7 @@ impl Code128Reader {
if bestMatch >= 0 {
Ok(bestMatch as u8)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
}

View File

@@ -99,7 +99,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
let length = contents.chars().count();
// Check length
if !(1..=80).contains(&length) {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Contents length should be between 1 and 80 characters, but got {length}"
)));
}
@@ -107,13 +107,13 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
// Check for forced code set hint.
let mut forcedCodeSet = -1_i32;
if hints.contains_key(&EncodeHintType::FORCE_CODE_SET) {
let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) = hints.get(&EncodeHintType::FORCE_CODE_SET) else { return Err(Exceptions::illegalStateEmpty()) };
let Some(EncodeHintValue::ForceCodeSet(codeSetHint)) = hints.get(&EncodeHintType::FORCE_CODE_SET) else { return Err(Exceptions::illegalState) };
match codeSetHint.as_str() {
"A" => forcedCodeSet = CODE_CODE_A as i32,
"B" => forcedCodeSet = CODE_CODE_B as i32,
"C" => forcedCodeSet = CODE_CODE_C as i32,
_ => {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Unsupported code set hint: {codeSetHint}"
)))
}
@@ -134,7 +134,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
if c > 127 {
// no full Latin-1 character set available at the moment
// shift and manual code change are not supported
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Bad character in input: ASCII value={c}"
)));
}
@@ -149,7 +149,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
// allows no ascii above 95 (no lower caps, no special symbols)
{
if c > 95 && c <= 127 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Bad character in input for forced code set A: ASCII value={c}"
)));
}
@@ -158,7 +158,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
// allows no ascii below 32 (terminal symbols)
{
if c <= 32 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Bad character in input for forced code set B: ASCII value={c}"
)));
}
@@ -172,7 +172,7 @@ fn check(contents: &str, hints: &crate::EncodingHintDictionary) -> Result<i32, E
|| ch == ESCAPE_FNC_3
|| ch == ESCAPE_FNC_4
{
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Bad character in input for forced code set C: ASCII value={c}"
)));
}
@@ -195,7 +195,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
while position < length {
//Select code to use
let newCodeSet = if forcedCodeSet == -1 {
chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalStateEmpty())?
chooseCode(contents, position, codeSet).ok_or(Exceptions::illegalState)?
} else {
forcedCodeSet as usize // THIS IS RISKY
};
@@ -208,7 +208,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
match contents
.chars()
.nth(position)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
{
ESCAPE_FNC_1 => patternIndex = CODE_FNC_1 as isize,
ESCAPE_FNC_2 => patternIndex = CODE_FNC_2 as isize,
@@ -228,7 +228,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
patternIndex = contents
.chars()
.nth(position)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
as isize
- ' ' as isize;
if patternIndex < 0 {
@@ -240,7 +240,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
patternIndex = contents
.chars()
.nth(position)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
as isize
- ' ' as isize
}
@@ -248,7 +248,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
// CODE_CODE_C
if position + 1 == length {
// this is the last character, but the encoding is C, which always encodes two characers
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"Bad number of characters for digit only encoding.",
));
}
@@ -259,7 +259,7 @@ fn encodeFast(contents: &str, forcedCodeSet: i32) -> Result<Vec<bool>, Exception
.map(|(_u, c)| c)
.collect();
patternIndex = s.parse::<isize>().map_err(|e| {
Exceptions::parse(format!("issue parsing {s}: {e}"))
Exceptions::parseWith(format!("issue parsing {s}: {e}"))
})?;
position += 1;
} // Also incremented below
@@ -535,7 +535,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
if contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
== ESCAPE_FNC_1
{
addPattern(
@@ -554,8 +554,9 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
.collect();
addPattern(
&mut patterns,
s.parse::<usize>()
.map_err(|e| Exceptions::parse(format!("unable to parse {s} {e}")))?,
s.parse::<usize>().map_err(|e| {
Exceptions::parseWith(format!("unable to parse {s} {e}"))
})?,
&mut checkSum,
&mut checkWeight,
i,
@@ -570,7 +571,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
let mut patternIndex = match contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
{
ESCAPE_FNC_1 => CODE_FNC_1 as isize,
ESCAPE_FNC_2 => CODE_FNC_2 as isize,
@@ -588,8 +589,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
as isize
.ok_or(Exceptions::indexOutOfBounds)? as isize
- ' ' as isize
}
};
@@ -680,7 +680,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
minPath: &mut Vec<Vec<Latch>>,
) -> Result<u32, Exceptions> {
if position >= contents.chars().count() {
return Err(Exceptions::illegalStateEmpty());
return Err(Exceptions::illegalState);
}
let mCost = memoizedCost[charset.ordinal()][position];
if mCost > 0 {
@@ -761,7 +761,7 @@ stuvwxyz{|}~\u{007F}\u{00FF}";
}
}
if minCost == u32::MAX {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Bad character in input: ASCII value={}",
contents.chars().nth(position).unwrap_or('x')
)));

View File

@@ -60,7 +60,7 @@ impl OneDReader for Code39Reader {
one_d_reader::recordPattern(row, nextStart, &mut counters)?;
let pattern = Self::toNarrowWidePattern(&counters);
if pattern < 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decodedChar = Self::patternToChar(pattern as u32)?;
self.decodeRowRXingResult.push(decodedChar);
@@ -85,7 +85,7 @@ impl OneDReader for Code39Reader {
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if nextStart != end && (whiteSpaceAfterEnd * 2) < lastPatternSize as usize {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
if self.usingCheckDigit {
@@ -96,7 +96,7 @@ impl OneDReader for Code39Reader {
self.decodeRowRXingResult
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
) {
total += pos;
}
@@ -105,20 +105,20 @@ impl OneDReader for Code39Reader {
.decodeRowRXingResult
.chars()
.nth(max)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
!= Self::ALPHABET_STRING
.chars()
.nth(total % 43)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
{
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
self.decodeRowRXingResult.truncate(max);
}
if self.decodeRowRXingResult.chars().count() == 0 {
// false positive
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let resultString = if self.extendedMode {
@@ -246,7 +246,7 @@ impl Code39Reader {
isWhite = !isWhite;
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
@@ -306,13 +306,13 @@ impl Code39Reader {
return Self::ALPHABET_STRING
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty());
.ok_or(Exceptions::indexOutOfBounds);
}
}
if pattern == Self::ASTERISK_ENCODING {
return Ok('*');
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn decodeExtended(encoded: &str) -> Result<String, Exceptions> {
@@ -322,49 +322,46 @@ impl Code39Reader {
while i < length {
// for i in 0..length {
// for (int i = 0; i < length; i++) {
let c = encoded
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?;
if c == '+' || c == '$' || c == '%' || c == '/' {
let next = encoded
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
let mut decodedChar = '\0';
match c {
'+' => {
// +A to +Z map to a to z
if ('A'..='Z').contains(&next) {
decodedChar = char::from_u32(next as u32 + 32)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
'$' => {
// $A to $Z map to control codes SH to SB
if ('A'..='Z').contains(&next) {
decodedChar = char::from_u32(next as u32 - 64)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
'%' => {
// %A to %E map to control codes ESC to US
if ('A'..='E').contains(&next) {
decodedChar = char::from_u32(next as u32 - 38)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else if ('F'..='J').contains(&next) {
decodedChar = char::from_u32(next as u32 - 11)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else if ('K'..='O').contains(&next) {
decodedChar = char::from_u32(next as u32 + 16)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else if ('P'..='T').contains(&next) {
decodedChar = char::from_u32(next as u32 + 43)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else if next == 'U' {
decodedChar = 0 as char;
} else if next == 'V' {
@@ -374,18 +371,18 @@ impl Code39Reader {
} else if next == 'X' || next == 'Y' || next == 'Z' {
decodedChar = 127 as char;
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
'/' => {
// /A to /O map to ! to , and /Z maps to :
if ('A'..='O').contains(&next) {
decodedChar = char::from_u32(next as u32 - 32)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
} else if next == 'Z' {
decodedChar = ':';
} else {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
_ => {}

View File

@@ -33,7 +33,7 @@ impl OneDimensionalCodeWriter for Code39Writer {
let mut contents = contents.to_owned();
let mut length = contents.chars().count();
if length > 80 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested contents should be less than 80 digits long, but got {length}"
)));
}
@@ -47,14 +47,14 @@ impl OneDimensionalCodeWriter for Code39Writer {
contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
)
.is_none()
{
contents = Self::tryToConvertToExtendedMode(&contents)?;
length = contents.chars().count();
if length > 80 {
return Err(Exceptions::illegalArgument(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)")));
return Err(Exceptions::illegalArgumentWith(format!("Requested contents should be less than 80 digits long, but got {length} (extended full ASCII mode)")));
}
break;
}
@@ -70,7 +70,7 @@ impl OneDimensionalCodeWriter for Code39Writer {
pos += Self::appendPattern(&mut result, pos as usize, &narrowWhite, false);
//append next character to byte matrix
for i in 0..length {
let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?) else {
let Some(indexInString) = Code39Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else {
continue;
};
Self::toIntArray(
@@ -117,56 +117,56 @@ impl Code39Writer {
extendedContent.push('$');
extendedContent.push(
char::from_u32('A' as u32 + (character as u32 - 1))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character < ' ' {
extendedContent.push('%');
extendedContent.push(
char::from_u32('A' as u32 + (character as u32 - 27))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= ',' || character == '/' || character == ':' {
extendedContent.push('/');
extendedContent.push(
char::from_u32('A' as u32 + (character as u32 - 33))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= '9' {
extendedContent.push(
char::from_u32('0' as u32 + (character as u32 - 48))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= '?' {
extendedContent.push('%');
extendedContent.push(
char::from_u32('F' as u32 + (character as u32 - 59))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= 'Z' {
extendedContent.push(
char::from_u32('A' as u32 + (character as u32 - 65))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= '_' {
extendedContent.push('%');
extendedContent.push(
char::from_u32('K' as u32 + (character as u32 - 91))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= 'z' {
extendedContent.push('+');
extendedContent.push(
char::from_u32('A' as u32 + (character as u32 - 97))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character as u32 <= 127 {
extendedContent.push('%');
extendedContent.push(
char::from_u32('P' as u32 + (character as u32 - 123))
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested content contains a non-encodable character: '{character}'"
)));
}

View File

@@ -63,7 +63,7 @@ impl OneDReader for Code93Reader {
one_d_reader::recordPattern(row, nextStart, &mut theCounters)?;
let pattern = Self::toPattern(&theCounters);
if pattern < 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decodedChar = Self::patternToChar(pattern as u32)?;
self.decodeRowRXingResult.push(decodedChar);
@@ -92,12 +92,12 @@ impl OneDReader for Code93Reader {
// Should be at least one more black module
if nextStart == end || !row.get(nextStart) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
if self.decodeRowRXingResult.chars().count() < 2 {
// false positive -- need at least 2 checksum digits
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Self::checkChecksums(&self.decodeRowRXingResult)?;
@@ -191,7 +191,7 @@ impl Code93Reader {
isWhite = !isWhite;
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn toPattern(counters: &[u32; 6]) -> i32 {
@@ -221,7 +221,7 @@ impl Code93Reader {
return Ok(Self::ALPHABET[i]);
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn decodeExtended(encoded: &str) -> Result<String, Exceptions> {
@@ -231,55 +231,52 @@ impl Code93Reader {
while i < length {
// for i in 0..length {
// for (int i = 0; i < length; i++) {
let c = encoded
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
let c = encoded.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?;
if ('a'..='d').contains(&c) {
if i >= length - 1 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
let next = encoded
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
let mut decodedChar = '\0';
match c {
'd' => {
// +A to +Z map to a to z
if ('A'..='Z').contains(&next) {
decodedChar =
char::from_u32(next as u32 + 32).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 + 32).ok_or(Exceptions::parse)?;
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
'a' => {
// $A to $Z map to control codes SH to SB
if ('A'..='Z').contains(&next) {
decodedChar =
char::from_u32(next as u32 - 64).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 - 64).ok_or(Exceptions::parse)?;
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
'b' => {
if ('A'..='E').contains(&next) {
// %A to %E map to control codes ESC to USep
decodedChar =
char::from_u32(next as u32 - 38).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 - 38).ok_or(Exceptions::parse)?;
} else if ('F'..='J').contains(&next) {
// %F to %J map to ; < = > ?
decodedChar =
char::from_u32(next as u32 - 11).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 - 11).ok_or(Exceptions::parse)?;
} else if ('K'..='O').contains(&next) {
// %K to %O map to [ \ ] ^ _
decodedChar =
char::from_u32(next as u32 + 16).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 + 16).ok_or(Exceptions::parse)?;
} else if ('P'..='T').contains(&next) {
// %P to %T map to { | } ~ DEL
decodedChar =
char::from_u32(next as u32 + 43).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 + 43).ok_or(Exceptions::parse)?;
} else if next == 'U' {
// %U map to NUL
decodedChar = '\0';
@@ -293,18 +290,18 @@ impl Code93Reader {
// %X to %Z all map to DEL (127)
decodedChar = 127 as char;
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
'c' => {
// /A to /O map to ! to , and /Z maps to :
if ('A'..='O').contains(&next) {
decodedChar =
char::from_u32(next as u32 - 32).ok_or(Exceptions::parseEmpty())?;
char::from_u32(next as u32 - 32).ok_or(Exceptions::parse)?;
} else if next == 'Z' {
decodedChar = ':';
} else {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
}
_ => {}
@@ -338,12 +335,7 @@ impl Code93Reader {
for i in (0..checkPosition).rev() {
total += weight
* Self::ALPHABET_STRING
.find(
result
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
)
.find(result.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?)
.map_or_else(|| -1_i32, |v| v as i32);
weight += 1;
if weight > weightMax as i32 {
@@ -353,10 +345,10 @@ impl Code93Reader {
if result
.chars()
.nth(checkPosition)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
!= Self::ALPHABET[(total as usize) % 47]
{
Err(Exceptions::checksumEmpty())
Err(Exceptions::checksum)
} else {
Ok(())
}

View File

@@ -35,7 +35,7 @@ impl OneDimensionalCodeWriter for Code93Writer {
let mut contents = Self::convertToExtended(contents)?;
let length = contents.chars().count();
if length > 80 {
return Err(Exceptions::illegalArgument(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" )));
return Err(Exceptions::illegalArgumentWith(format!("Requested contents should be less than 80 digits long after converting to extended encoding, but got {length}" )));
}
//length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar
@@ -48,7 +48,7 @@ impl OneDimensionalCodeWriter for Code93Writer {
for i in 0..length {
// for (int i = 0; i < length; i++) {
let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBoundsEmpty())?) else {panic!("alphabet")};
let Some(indexInString) = Code93Reader::ALPHABET_STRING.find(contents.chars().nth(i).ok_or(Exceptions::indexOutOfBounds)?) else {panic!("alphabet")};
pos += Self::appendPattern(
&mut result,
pos,
@@ -65,7 +65,7 @@ impl OneDimensionalCodeWriter for Code93Writer {
Code93Reader::ALPHABET_STRING
.chars()
.nth(check1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?,
.ok_or(Exceptions::indexOutOfBounds)?,
);
let check2 = Self::computeChecksumIndex(&contents, 15);
@@ -156,15 +156,13 @@ impl Code93Writer {
// SOH - SUB: ($)A - ($)Z
extendedContent.push('a');
extendedContent.push(
char::from_u32('A' as u32 + character as u32 - 1)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32('A' as u32 + character as u32 - 1).ok_or(Exceptions::parse)?,
);
} else if character as u32 <= 31 {
// ESC - US: (%)A - (%)E
extendedContent.push('b');
extendedContent.push(
char::from_u32('A' as u32 + character as u32 - 27)
.ok_or(Exceptions::parseEmpty())?,
char::from_u32('A' as u32 + character as u32 - 27).ok_or(Exceptions::parse)?,
);
} else if character == ' ' || character == '$' || character == '%' || character == '+' {
// space $ % +
@@ -174,7 +172,7 @@ impl Code93Writer {
extendedContent.push('c');
extendedContent.push(
char::from_u32('A' as u32 + character as u32 - '!' as u32)
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character <= '9' {
extendedContent.push(character);
@@ -186,7 +184,7 @@ impl Code93Writer {
extendedContent.push('b');
extendedContent.push(
char::from_u32('F' as u32 + character as u32 - ';' as u32)
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character == '@' {
// @: (%)V
@@ -199,7 +197,7 @@ impl Code93Writer {
extendedContent.push('b');
extendedContent.push(
char::from_u32('K' as u32 + character as u32 - '[' as u32)
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character == '`' {
// `: (%)W
@@ -209,17 +207,17 @@ impl Code93Writer {
extendedContent.push('d');
extendedContent.push(
char::from_u32('A' as u32 + character as u32 - 'a' as u32)
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else if character as u32 <= 127 {
// { - DEL: (%)P - (%)T
extendedContent.push('b');
extendedContent.push(
char::from_u32('P' as u32 + character as u32 - '{' as u32)
.ok_or(Exceptions::parseEmpty())?,
.ok_or(Exceptions::parse)?,
);
} else {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested content contains a non-encodable character: '{character}'"
)));
}

View File

@@ -64,10 +64,8 @@ impl UPCEANReader for EAN13Reader {
rowOffset,
&upc_ean_reader::L_AND_G_PATTERNS,
)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32 % 10)
.ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
@@ -89,9 +87,8 @@ impl UPCEANReader for EAN13Reader {
while x < 6 && rowOffset < end {
let bestMatch =
self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
@@ -153,11 +150,11 @@ impl EAN13Reader {
if lgPatternFound == Self::FIRST_DIGIT_ENCODINGS[d] {
resultString.insert(
0,
char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parseEmpty())?,
char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parse)?,
);
return Ok(());
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -45,11 +45,13 @@ impl OneDimensionalCodeWriter for EAN13Writer {
}
13 => {
if !reader.checkStandardUPCEANChecksum(&contents)? {
return Err(Exceptions::illegalArgument("Contents do not pass checksum"));
return Err(Exceptions::illegalArgumentWith(
"Contents do not pass checksum",
));
}
}
_ => {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested contents should be 12 or 13 digits long, but got {length}"
)))
}
@@ -60,9 +62,9 @@ impl OneDimensionalCodeWriter for EAN13Writer {
let firstDigit = contents
.chars()
.next()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize;
.ok_or(Exceptions::parse)? as usize;
let parities = EAN13Reader::FIRST_DIGIT_ENCODINGS[firstDigit];
let mut result = [false; CODE_WIDTH];
let mut pos = 0;
@@ -77,9 +79,9 @@ impl OneDimensionalCodeWriter for EAN13Writer {
let mut digit = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize;
.ok_or(Exceptions::parse)? as usize;
if (parities >> (6 - i) & 1) == 1 {
digit += 10;
}
@@ -98,9 +100,9 @@ impl OneDimensionalCodeWriter for EAN13Writer {
let digit = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize;
.ok_or(Exceptions::parse)? as usize;
pos += EAN13Writer::appendPattern(
&mut result,

View File

@@ -52,9 +52,8 @@ impl UPCEANReader for EAN8Reader {
while x < 4 && rowOffset < end {
let bestMatch =
self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
@@ -69,9 +68,8 @@ impl UPCEANReader for EAN8Reader {
while x < 4 && rowOffset < end {
let bestMatch =
self.decodeDigit(row, &mut counters, rowOffset, &upc_ean_reader::L_PATTERNS)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
x += 1;

View File

@@ -55,11 +55,13 @@ impl OneDimensionalCodeWriter for EAN8Writer {
}
8 => {
if !EAN8Reader.checkStandardUPCEANChecksum(&contents)? {
return Err(Exceptions::illegalArgument("Contents do not pass checksum"));
return Err(Exceptions::illegalArgumentWith(
"Contents do not pass checksum",
));
}
}
_ => {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested contents should be 7 or 8 digits long, but got {length}"
)))
}
@@ -78,9 +80,9 @@ impl OneDimensionalCodeWriter for EAN8Writer {
let digit = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize;
.ok_or(Exceptions::indexOutOfBounds)? as usize;
pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], false)
as usize;
}
@@ -93,9 +95,9 @@ impl OneDimensionalCodeWriter for EAN8Writer {
let digit = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as usize;
.ok_or(Exceptions::indexOutOfBounds)? as usize;
pos += Self::appendPattern(&mut result, pos, &upc_ean_reader::L_PATTERNS[digit], true)
as usize;
}

View File

@@ -140,7 +140,7 @@ impl OneDReader for ITFReader {
lengthOK = true;
}
if !lengthOK {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
let mut resultObject = RXingResult::new(
@@ -195,11 +195,9 @@ impl ITFReader {
}
let mut bestMatch = self.decodeDigit(&counterBlack)?;
resultString
.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parseEmpty())?);
resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parse)?);
bestMatch = self.decodeDigit(&counterWhite)?;
resultString
.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parseEmpty())?);
resultString.push(char::from_u32('0' as u32 + bestMatch).ok_or(Exceptions::parse)?);
payloadStart += counterDigitPair.iter().sum::<u32>() as usize;
}
@@ -260,7 +258,7 @@ impl ITFReader {
if quietCount != 0 {
// Unable to find the necessary number of quiet zone pixels.
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
} else {
Ok(())
}
@@ -277,7 +275,7 @@ impl ITFReader {
let width = row.getSize();
let endStart = row.getNextSet(0);
if endStart == width {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(endStart)
@@ -372,7 +370,7 @@ impl ITFReader {
isWhite = !isWhite;
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**
@@ -401,7 +399,7 @@ impl ITFReader {
if bestMatch >= 0 {
Ok(bestMatch as u32 % 10)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
}

View File

@@ -32,12 +32,12 @@ impl OneDimensionalCodeWriter for ITFWriter {
fn encode_oned(&self, contents: &str) -> Result<Vec<bool>, Exceptions> {
let length = contents.chars().count();
if length % 2 != 0 {
return Err(Exceptions::illegalArgument(
return Err(Exceptions::illegalArgumentWith(
"The length of the input should be even",
));
}
if length > 80 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested contents should be less than 80 digits long, but got {length}"
)));
}
@@ -51,15 +51,15 @@ impl OneDimensionalCodeWriter for ITFWriter {
let one = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize;
.ok_or(Exceptions::parse)? as usize;
let two = contents
.chars()
.nth(i + 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize;
.ok_or(Exceptions::parse)? as usize;
let mut encoding = [0; 10];
for j in 0..5 {
encoding[2 * j] = PATTERNS[one][j];

View File

@@ -46,7 +46,7 @@ impl OneDReader for MultiFormatOneDReader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
impl MultiFormatOneDReader {
@@ -168,7 +168,7 @@ impl Reader for MultiFormatOneDReader {
Ok(result)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -134,7 +134,7 @@ impl OneDReader for MultiFormatUPCEANReader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
@@ -200,7 +200,7 @@ impl Reader for MultiFormatUPCEANReader {
Ok(result)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -100,7 +100,7 @@ pub trait OneDimensionalCodeWriter: Writer {
*/
fn checkNumeric(contents: &str) -> Result<(), Exceptions> {
if !NUMERIC.is_match(contents) {
Err(Exceptions::illegalArgument(
Err(Exceptions::illegalArgumentWith(
"Input should only contain digits 0-9",
))
} else {
@@ -163,17 +163,17 @@ impl Writer for L {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if contents.is_empty() {
return Err(Exceptions::illegalArgument("Found empty contents"));
return Err(Exceptions::illegalArgumentWith("Found empty contents"));
}
if width < 0 || height < 0 {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Negative size is not allowed. Input: {width}x{height}"
)));
}
if let Some(supportedFormats) = self.getSupportedWriteFormats() {
if !supportedFormats.contains(format) {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Can only encode {supportedFormats:?}, but got {format:?}"
)));
}
@@ -181,9 +181,9 @@ impl Writer for L {
let mut sidesMargin = self.getDefaultMargin();
if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) {
sidesMargin = margin
.parse::<u32>()
.map_err(|e| Exceptions::illegalArgument(format!("couldnt parse {margin}: {e}")))?;
sidesMargin = margin.parse::<u32>().map_err(|e| {
Exceptions::illegalArgumentWith(format!("couldnt parse {margin}: {e}"))
})?;
}
let code = self.encode_oned_with_hints(contents, hints)?;

View File

@@ -131,7 +131,7 @@ pub trait OneDReader: Reader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**
@@ -218,7 +218,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu
let end = row.getSize();
if start >= end {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let mut isWhite = !row.get(start);
@@ -241,7 +241,7 @@ pub fn recordPattern(row: &BitArray, start: usize, counters: &mut [u32]) -> Resu
// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
if !(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end)) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(())
}
@@ -263,7 +263,7 @@ pub fn recordPatternInReverse(
}
}
if numTransitionsLeft >= 0 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
recordPattern(row, start + 1, counters)?;

View File

@@ -38,7 +38,7 @@ pub trait AbstractRSSReaderTrait: OneDReader {
return Ok(value as u32);
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**

View File

@@ -50,13 +50,13 @@ pub fn buildBitArrayFromString(data: &str) -> Result<BitArray, Exceptions> {
// for (int i = 0; i < dotsAndXs.length(); ++i) {
if i % 9 == 0 {
// spaces
if dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())? != ' ' {
return Err(Exceptions::illegalState("space expected"));
if dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)? != ' ' {
return Err(Exceptions::illegalStateWith("space expected"));
}
continue;
}
let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parseEmpty())?;
let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::parse)?;
if currentChar == 'X' || currentChar == 'x' {
binary.set(counter);
}
@@ -78,12 +78,7 @@ pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray, Exce
sb.push(' ');
let mut i = 0;
while i < 8 && current < dotsAndXs_length {
sb.push(
dotsAndXs
.chars()
.nth(current)
.ok_or(Exceptions::parseEmpty())?,
);
sb.push(dotsAndXs.chars().nth(current).ok_or(Exceptions::parse)?);
current += 1;
i += 1;

View File

@@ -149,7 +149,7 @@ pub fn createDecoder<'a>(
_ => {}
}
Err(Exceptions::illegalState(format!(
Err(Exceptions::illegalStateWith(format!(
"unknown decoder: {information}"
)))
}

View File

@@ -39,7 +39,7 @@ impl AI01decoder for AI01392xDecoder<'_> {}
impl AbstractExpandedDecoder for AI01392xDecoder<'_> {
fn parseInformation(&mut self) -> Result<String, crate::Exceptions> {
if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize {
return Err(crate::Exceptions::notFoundEmpty());
return Err(crate::Exceptions::notFound);
}
let mut buf = String::new();

View File

@@ -39,7 +39,7 @@ impl AI01decoder for AI01393xDecoder<'_> {}
impl AbstractExpandedDecoder for AI01393xDecoder<'_> {
fn parseInformation(&mut self) -> Result<String, crate::Exceptions> {
if self.information.getSize() < Self::HEADER_SIZE + Self::GTIN_SIZE as usize {
return Err(crate::Exceptions::notFoundEmpty());
return Err(crate::Exceptions::notFound);
}
let mut buf = String::new();

View File

@@ -57,7 +57,7 @@ impl AbstractExpandedDecoder for AI013x0x1xDecoder<'_> {
if self.information.getSize()
!= Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE + Self::DATE_SIZE
{
return Err(crate::Exceptions::notFoundEmpty());
return Err(crate::Exceptions::notFound);
}
let mut buf = String::new();

View File

@@ -53,7 +53,7 @@ impl AbstractExpandedDecoder for AI013x0xDecoder<'_> {
if self.information.getSize()
!= Self::HEADER_SIZE + Self::GTIN_SIZE as usize + Self::WEIGHT_SIZE
{
return Err(crate::Exceptions::notFoundEmpty());
return Err(crate::Exceptions::notFound);
}
let mut buf = String::new();

View File

@@ -51,7 +51,7 @@ impl DecodedNumeric {
if
/*firstDigit < 0 ||*/
firstDigit > 10 || /*secondDigit < 0 ||*/ secondDigit > 10 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
Ok(Self {

View File

@@ -145,7 +145,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result<String, Excep
// Processing 2-digit AIs
if rawInformation.chars().count() < 2 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let lookup: String = rawInformation.chars().take(2).collect();
@@ -158,7 +158,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result<String, Excep
}
if rawInformation.chars().count() < 3 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let firstThreeDigits: String = rawInformation.chars().take(3).collect();
@@ -171,7 +171,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result<String, Excep
}
if rawInformation.chars().count() < 4 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let threeDigitPlusDigitDataLength = THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH.get(&firstThreeDigits);
@@ -191,7 +191,7 @@ pub fn parseFieldsInGeneralPurpose(rawInformation: &str) -> Result<String, Excep
return processFixedAI(4, ffdl.length, rawInformation);
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn processFixedAI(
@@ -200,13 +200,13 @@ fn processFixedAI(
rawInformation: &str,
) -> Result<String, Exceptions> {
if rawInformation.chars().count() < aiSize {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let ai: String = rawInformation.chars().take(aiSize).collect();
if rawInformation.chars().count() < aiSize + fieldSize {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let field: String = rawInformation

View File

@@ -199,7 +199,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
if let Some(r) = result.getDecodedInformation() {
Ok(r.clone())
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
@@ -345,7 +345,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
if (5..15).contains(&fiveBitValue) {
return Ok(DecodedChar::new(
pos + 5,
char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parseEmpty())?,
char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?,
));
}
@@ -354,14 +354,14 @@ impl<'a> GeneralAppIdDecoder<'_> {
if (64..90).contains(&sevenBitValue) {
return Ok(DecodedChar::new(
pos + 7,
char::from_u32(sevenBitValue + 1).ok_or(Exceptions::parseEmpty())?,
char::from_u32(sevenBitValue + 1).ok_or(Exceptions::parse)?,
));
}
if (90..116).contains(&sevenBitValue) {
return Ok(DecodedChar::new(
pos + 7,
char::from_u32(sevenBitValue + 7).ok_or(Exceptions::parseEmpty())?,
char::from_u32(sevenBitValue + 7).ok_or(Exceptions::parse)?,
));
}
@@ -388,7 +388,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
250 => '?',
251 => '_',
252 => ' ',
_ => return Err(Exceptions::formatEmpty()),
_ => return Err(Exceptions::format),
};
Ok(DecodedChar::new(pos + 8, c))
@@ -423,7 +423,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
if (5..15).contains(&fiveBitValue) {
return Ok(DecodedChar::new(
pos + 5,
char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parseEmpty())?,
char::from_u32('0' as u32 + fiveBitValue - 5).ok_or(Exceptions::parse)?,
));
}
@@ -432,7 +432,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
if (32..58).contains(&sixBitValue) {
return Ok(DecodedChar::new(
pos + 6,
char::from_u32(sixBitValue + 33).ok_or(Exceptions::parseEmpty())?,
char::from_u32(sixBitValue + 33).ok_or(Exceptions::parse)?,
));
}
@@ -443,7 +443,7 @@ impl<'a> GeneralAppIdDecoder<'_> {
61 => '.',
62 => '/',
_ => {
return Err(Exceptions::illegalState(format!(
return Err(Exceptions::illegalStateWith(format!(
"Decoding invalid alphanumeric value: {sixBitValue}"
)))
}

View File

@@ -227,7 +227,7 @@ impl Reader for RSSExpandedReader {
Ok(result)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
}
@@ -297,7 +297,7 @@ impl RSSExpandedReader {
if let Ok(to_add) = to_add_res {
self.pairs.push(to_add);
} else if self.pairs.is_empty() {
return Err(to_add_res.err().unwrap_or(Exceptions::illegalStateEmpty()));
return Err(to_add_res.err().unwrap_or(Exceptions::illegalState));
} else {
// exit this loop when retrieveNextPair() fails and throws
done = true;
@@ -329,7 +329,7 @@ impl RSSExpandedReader {
// }
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn checkRows(&mut self, reverse: bool) -> Option<Vec<ExpandedPair>> {
@@ -373,10 +373,7 @@ impl RSSExpandedReader {
) -> Result<Vec<ExpandedPair>, Exceptions> {
for i in currentRow..self.rows.len() {
// for (int i = currentRow; i < rows.size(); i++) {
let row = self
.rows
.get(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
let row = self.rows.get(i).ok_or(Exceptions::indexOutOfBounds)?;
self.pairs.clear();
for collectedRow in &collectedRows.clone() {
// for (ExpandedRow collectedRow : collectedRows) {
@@ -404,7 +401,7 @@ impl RSSExpandedReader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/// Whether the pairs form a valid find pattern sequence,
@@ -534,25 +531,25 @@ impl RSSExpandedReader {
// Not private for unit testing
pub(crate) fn constructRXingResult(pairs: &[ExpandedPair]) -> Result<RXingResult, Exceptions> {
let binary = bit_array_builder::buildBitArray(&pairs.to_vec())
.ok_or(Exceptions::illegalStateEmpty())?;
let binary =
bit_array_builder::buildBitArray(&pairs.to_vec()).ok_or(Exceptions::illegalState)?;
let mut decoder = abstract_expanded_decoder::createDecoder(&binary)?;
let resultingString = decoder.parseInformation()?;
let firstPoints = pairs
.get(0)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.getFinderPattern()
.as_ref()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getRXingResultPoints();
let lastPoints = pairs
.last()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.getFinderPattern()
.as_ref()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getRXingResultPoints();
let mut result = RXingResult::new(
@@ -651,7 +648,7 @@ impl RSSExpandedReader {
let leftChar = self.decodeDataCharacter(
row,
pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?,
pattern.as_ref().ok_or(Exceptions::notFound)?,
isOddPattern,
true,
)?;
@@ -659,16 +656,16 @@ impl RSSExpandedReader {
if !previousPairs.is_empty()
&& previousPairs
.last()
.ok_or(Exceptions::notFoundEmpty())?
.ok_or(Exceptions::notFound)?
.mustBeLast()
{
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let rightChar = self
.decodeDataCharacter(
row,
pattern.as_ref().ok_or(Exceptions::notFoundEmpty())?,
pattern.as_ref().ok_or(Exceptions::notFound)?,
isOddPattern,
false,
)
@@ -698,13 +695,11 @@ impl RSSExpandedReader {
} else if previousPairs.is_empty() {
rowOffset = 0;
} else {
let lastPair = previousPairs
.last()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
let lastPair = previousPairs.last().ok_or(Exceptions::indexOutOfBounds)?;
rowOffset = lastPair
.getFinderPattern()
.as_ref()
.ok_or(Exceptions::illegalStateEmpty())?
.ok_or(Exceptions::illegalState)?
.getStartEnd()[1] as i32;
}
let mut searchingEvenPair = previousPairs.len() % 2 != 0;
@@ -756,7 +751,7 @@ impl RSSExpandedReader {
isWhite = !isWhite;
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn reverseCounters(counters: &mut [u32]) {
@@ -853,7 +848,7 @@ impl RSSExpandedReader {
let expectedElementWidth: f32 =
(pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) as f32 / 15.0;
if (elementWidth - expectedElementWidth).abs() / expectedElementWidth > 0.3 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
for (i, counter) in counters.iter().enumerate() {
@@ -862,12 +857,12 @@ impl RSSExpandedReader {
let mut count = (value + 0.5) as i32; // Round
if count < 1 {
if value < 0.3 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
count = 1;
} else if count > 8 {
if value > 8.7 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
count = 8;
}
@@ -907,7 +902,7 @@ impl RSSExpandedReader {
let checksumPortion = oddChecksumPortion + evenChecksumPortion;
if (oddSum & 0x01) != 0 || !(4..=13).contains(&oddSum) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let group = ((13 - oddSum) / 2) as usize;
@@ -955,12 +950,12 @@ impl RSSExpandedReader {
1 => {
if oddParityBad {
if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decrementOdd = true;
} else {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decrementEven = true;
}
@@ -968,12 +963,12 @@ impl RSSExpandedReader {
-1 => {
if oddParityBad {
if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
incrementOdd = true;
} else {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
incrementEven = true;
}
@@ -981,7 +976,7 @@ impl RSSExpandedReader {
0 => {
if oddParityBad {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// Both bad
if oddSum < evenSum {
@@ -992,16 +987,16 @@ impl RSSExpandedReader {
incrementEven = true;
}
} else if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
_ => return Err(Exceptions::notFoundEmpty()),
_ => return Err(Exceptions::notFound),
}
if incrementOdd {
if decrementOdd {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Self::increment(&mut self.oddCounts, &self.oddRoundingErrors);
}
@@ -1010,7 +1005,7 @@ impl RSSExpandedReader {
}
if incrementEven {
if decrementEven {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Self::increment(&mut self.evenCounts, &self.oddRoundingErrors);
}

View File

@@ -64,12 +64,12 @@ impl OneDReader for RSS14Reader {
if right.getCount() > 1 && self.checkChecksum(left, right) {
return self
.constructRXingResult(left, right)
.ok_or(Exceptions::illegalStateEmpty());
.ok_or(Exceptions::illegalState);
}
}
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
impl Reader for RSS14Reader {
@@ -126,7 +126,7 @@ impl Reader for RSS14Reader {
Ok(result)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
}
@@ -343,7 +343,7 @@ impl RSS14Reader {
if outsideChar {
if (oddSum & 0x01) != 0 || !(4..=12).contains(&oddSum) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let group = ((12 - oddSum) / 2) as usize;
let oddWidest = Self::OUTSIDE_ODD_WIDEST[group];
@@ -358,7 +358,7 @@ impl RSS14Reader {
))
} else {
if (evenSum & 0x01) != 0 || !(4..=10).contains(&evenSum) {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let group = ((10 - evenSum) / 2) as usize;
let oddWidest = Self::INSIDE_ODD_WIDEST[group];
@@ -417,7 +417,7 @@ impl RSS14Reader {
isWhite = !isWhite;
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
fn parseFoundFinderPattern(
@@ -518,12 +518,12 @@ impl RSS14Reader {
1 => {
if oddParityBad {
if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decrementOdd = true;
} else {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
decrementEven = true;
}
@@ -531,12 +531,12 @@ impl RSS14Reader {
-1 => {
if oddParityBad {
if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
incrementOdd = true;
} else {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
incrementEven = true;
}
@@ -544,7 +544,7 @@ impl RSS14Reader {
0 => {
if oddParityBad {
if !evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
// Both bad
if oddSum < evenSum {
@@ -555,15 +555,15 @@ impl RSS14Reader {
incrementEven = true;
}
} else if evenParityBad {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
_ => return Err(Exceptions::notFoundEmpty()),
_ => return Err(Exceptions::notFound),
}
if incrementOdd {
if decrementOdd {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Self::increment(&mut self.oddCounts, &self.oddRoundingErrors);
}
@@ -572,7 +572,7 @@ impl RSS14Reader {
}
if incrementEven {
if decrementEven {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Self::increment(&mut self.evenCounts, &self.evenRoundingErrors);
}

View File

@@ -104,7 +104,7 @@ impl UPCAReader {
Ok(upcaRXingResult)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}
}

View File

@@ -48,7 +48,7 @@ impl Writer for UPCAWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if format != &BarcodeFormat::UPC_A {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Can only encode UPC-A, but got {format:?}"
)));
}

View File

@@ -49,10 +49,8 @@ impl UPCEANReader for UPCEReader {
let mut x = 0;
while x < 6 && rowOffset < end {
let bestMatch = self.decodeDigit(row, &mut counters, rowOffset, &L_AND_G_PATTERNS)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32 % 10)
.ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
if bestMatch >= 10 {
@@ -68,9 +66,7 @@ impl UPCEANReader for UPCEReader {
}
fn checkChecksum(&self, s: &str) -> Result<bool, Exceptions> {
self.checkStandardUPCEANChecksum(
&convertUPCEtoUPCA(s).ok_or(Exceptions::illegalArgumentEmpty())?,
)
self.checkStandardUPCEANChecksum(&convertUPCEtoUPCA(s).ok_or(Exceptions::illegalArgument)?)
}
fn decodeEnd(
@@ -132,17 +128,15 @@ impl UPCEReader {
if lgPatternFound == Self::NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d] {
resultString.insert(
0,
char::from_u32('0' as u32 + numSys as u32)
.ok_or(Exceptions::parseEmpty())?,
);
resultString.push(
char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parseEmpty())?,
char::from_u32('0' as u32 + numSys as u32).ok_or(Exceptions::parse)?,
);
resultString
.push(char::from_u32('0' as u32 + d as u32).ok_or(Exceptions::parse)?);
return Ok(());
}
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

View File

@@ -46,20 +46,22 @@ impl OneDimensionalCodeWriter for UPCEWriter {
// No check digit present, calculate it and add it
let check = reader.getStandardUPCEANChecksum(
&upc_e_reader::convertUPCEtoUPCA(&contents)
.ok_or(Exceptions::illegalArgumentEmpty())?,
.ok_or(Exceptions::illegalArgument)?,
)?;
contents.push_str(&check.to_string());
}
8 => {
if !reader.checkStandardUPCEANChecksum(
&upc_e_reader::convertUPCEtoUPCA(&contents)
.ok_or(Exceptions::illegalArgumentEmpty())?,
.ok_or(Exceptions::illegalArgument)?,
)? {
return Err(Exceptions::illegalArgument("Contents do not pass checksum"));
return Err(Exceptions::illegalArgumentWith(
"Contents do not pass checksum",
));
}
}
_ => {
return Err(Exceptions::illegalArgument(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Requested contents should be 7 or 8 digits long, but got {length}"
)))
}
@@ -70,19 +72,21 @@ impl OneDimensionalCodeWriter for UPCEWriter {
let firstDigit = contents
.chars()
.next()
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(0), 10);
.ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(0), 10);
if firstDigit != 0 && firstDigit != 1 {
return Err(Exceptions::illegalArgument("Number system must be 0 or 1"));
return Err(Exceptions::illegalArgumentWith(
"Number system must be 0 or 1",
));
}
let checkDigit = contents
.chars()
.nth(7)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(7), 10);
.ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(7), 10);
let parities = UPCEReader::NUMSYS_AND_CHECK_DIGIT_PATTERNS[firstDigit][checkDigit];
let mut result = [false; CODE_WIDTH];
@@ -94,9 +98,9 @@ impl OneDimensionalCodeWriter for UPCEWriter {
let mut digit = contents
.chars()
.nth(i)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?
.ok_or(Exceptions::indexOutOfBounds)?
.to_digit(10)
.ok_or(Exceptions::parseEmpty())? as usize; //Character.digit(contents.charAt(i), 10);
.ok_or(Exceptions::parse)? as usize; //Character.digit(contents.charAt(i), 10);
if (parities >> (6 - i) & 1) == 1 {
digit += 10;
}

View File

@@ -86,10 +86,8 @@ impl UPCEANExtension2Support {
rowOffset,
&upc_ean_reader::L_AND_G_PATTERNS,
)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32 % 10)
.ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
@@ -105,16 +103,16 @@ impl UPCEANExtension2Support {
}
if resultString.chars().count() != 2 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
if resultString
.parse::<u32>()
.map_err(|e| Exceptions::parse(format!("could not parse {resultString}: {e}")))?
.map_err(|e| Exceptions::parseWith(format!("could not parse {resultString}: {e}")))?
% 4
!= checkParity
{
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(rowOffset as u32)

View File

@@ -85,10 +85,8 @@ impl UPCEANExtension5Support {
rowOffset,
&upc_ean_reader::L_AND_G_PATTERNS,
)?;
resultString.push(
char::from_u32('0' as u32 + bestMatch as u32 % 10)
.ok_or(Exceptions::parseEmpty())?,
);
resultString
.push(char::from_u32('0' as u32 + bestMatch as u32 % 10).ok_or(Exceptions::parse)?);
rowOffset += counters.iter().sum::<u32>() as usize;
@@ -105,14 +103,14 @@ impl UPCEANExtension5Support {
}
if resultString.chars().count() != 5 {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let checkDigit = Self::determineCheckDigit(lgPatternFound)?;
if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgumentEmpty())?
if Self::extensionChecksum(resultString).ok_or(Exceptions::illegalArgument)?
!= checkDigit as u32
{
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
Ok(rowOffset as u32)
@@ -147,7 +145,7 @@ impl UPCEANExtension5Support {
return Ok(d);
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**

View File

@@ -182,18 +182,18 @@ pub trait UPCEANReader: OneDReader {
let end = endRange[1];
let quietEnd = end + (end - endRange[0]);
if quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)? {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
let resultString = result;
// UPC/EAN should never be less than 8 chars anyway
if resultString.chars().count() < 8 {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
if !self.checkChecksum(&resultString)? {
return Err(Exceptions::checksumEmpty());
return Err(Exceptions::checksum);
}
let left = (startGuardRange[1] + startGuardRange[0]) as f32 / 2.0;
@@ -241,7 +241,7 @@ pub trait UPCEANReader: OneDReader {
}
}
if !valid {
return Err(Exceptions::notFoundEmpty());
return Err(Exceptions::notFound);
}
}
@@ -292,7 +292,7 @@ pub trait UPCEANReader: OneDReader {
let char_in_question = s
.chars()
.nth(length - 1)
.ok_or(Exceptions::indexOutOfBoundsEmpty())?;
.ok_or(Exceptions::indexOutOfBounds)?;
let check = char_in_question.is_ascii_digit();
let check_against = &s[..length - 1]; //s.subSequence(0, length - 1);
@@ -300,9 +300,7 @@ pub trait UPCEANReader: OneDReader {
Ok(calculated_checksum
== if check {
char_in_question
.to_digit(10)
.ok_or(Exceptions::parseEmpty())?
char_in_question.to_digit(10).ok_or(Exceptions::parse)?
} else {
u32::MAX
})
@@ -317,10 +315,10 @@ pub trait UPCEANReader: OneDReader {
let digit = (s
.chars()
.nth(i as usize)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32)
.ok_or(Exceptions::indexOutOfBounds)? as i32)
- ('0' as i32);
if !(0..=9).contains(&digit) {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
sum += digit;
@@ -333,10 +331,10 @@ pub trait UPCEANReader: OneDReader {
let digit = (s
.chars()
.nth(i as usize)
.ok_or(Exceptions::indexOutOfBoundsEmpty())? as i32)
.ok_or(Exceptions::indexOutOfBounds)? as i32)
- ('0' as i32);
if !(0..=9).contains(&digit) {
return Err(Exceptions::formatEmpty());
return Err(Exceptions::format);
}
sum += digit;
@@ -423,7 +421,7 @@ pub trait UPCEANReader: OneDReader {
}
}
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
/**
@@ -460,7 +458,7 @@ pub trait UPCEANReader: OneDReader {
if bestMatch >= 0 {
Ok(bestMatch as usize)
} else {
Err(Exceptions::notFoundEmpty())
Err(Exceptions::notFound)
}
}

Some files were not shown because too many files have changed in this diff Show More