Skip to content

Commit

Permalink
Merge pull request #11 from Asha20/pr/exception_helpers
Browse files Browse the repository at this point in the history
Simplify the creation of Exceptions
  • Loading branch information
hschimke authored Feb 16, 2023
2 parents 46e8032 + 41c5615 commit 7b891bd
Show file tree
Hide file tree
Showing 131 changed files with 1,046 additions and 1,342 deletions.
2 changes: 1 addition & 1 deletion src/aztec/aztec_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Reader for AztecReader {
} else if let Ok(det) = detector.detect(true) {
det
} else {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
};

let points = detectorRXingResult.getPoints();
Expand Down
6 changes: 3 additions & 3 deletions src/aztec/aztec_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,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::IllegalArgumentException(None))?,
.ok_or(Exceptions::illegalArgument)?,
);
}
}
Expand Down Expand Up @@ -96,9 +96,9 @@ fn encode(
layers: i32,
) -> Result<BitMatrix> {
if format != BarcodeFormat::AZTEC {
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"can only encode AZTEC, but got {format:?}"
))));
)));
}
let aztec = if let Some(cset) = charset {
// dbg!(cset.name(), cset.whatwg_name());
Expand Down
44 changes: 12 additions & 32 deletions src/aztec/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,13 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
result.push_str(
&encdr
.decode(&decoded_bytes, encoding::DecoderTrap::Strict)
.map_err(|a| Exceptions::IllegalStateException(Some(a.to_string())))?,
.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::FormatException(Some(
"FLG(7) is reserved and illegal".to_owned(),
)))
} // 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;
Expand All @@ -184,18 +180,15 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
let next_digit = read_code(corrected_bits, index, 4);
index += 4;
if !(2..=11).contains(&next_digit) {
return Err(Exceptions::FormatException(Some(
"Not a decimal digit".to_owned(),
))); // Not a decimal digit
return Err(Exceptions::formatWith("Not a decimal digit"));
// Not a decimal digit
}
eci = eci * 10 + (next_digit - 2);
n -= 1;
}
let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci);
if charset_eci.is_err() {
return Err(Exceptions::FormatException(Some(
"Charset must exist".to_owned(),
)));
return Err(Exceptions::formatWith("Charset must exist"));
}
encdr = CharacterSetECI::getCharset(&charset_eci?);
}
Expand All @@ -208,17 +201,8 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
// 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::IndexOutOfBoundsException(None))?,
);
if str
.chars()
.nth(6)
.ok_or(Exceptions::IndexOutOfBoundsException(None))?
== '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 {
Expand All @@ -239,9 +223,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
if let Ok(str) = encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict) {
result.push_str(&str);
} else {
return Err(Exceptions::IllegalStateException(Some(
"bad encoding".to_owned(),
)));
return Err(Exceptions::illegalStateWith("bad encoding"));
}
// result.push_str(decodedBytes.toString(encoding.name()));
//} catch (UnsupportedEncodingException uee) {
Expand Down Expand Up @@ -293,9 +275,7 @@ fn get_character(table: Table, code: u32) -> Result<&'static str> {
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::IllegalStateException(Some(
"Bad table".to_owned(),
))),
_ => Err(Exceptions::illegalStateWith("Bad table")),
}
// switch (table) {
// case UPPER:
Expand Down Expand Up @@ -356,9 +336,9 @@ 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::FormatException(Some(format!(
return Err(Exceptions::formatWith(format!(
"numCodewords {num_codewords}< numDataCodewords{num_data_codewords}"
))));
)));
}
let mut offset = rawbits.len() % codeword_size;

Expand Down Expand Up @@ -389,7 +369,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::FormatException(None));
return Err(Exceptions::format);
//throw FormatException.getFormatInstance();
} else if data_word == &1 || data_word == &(mask - 1) {
stuffed_bits += 1;
Expand Down
10 changes: 3 additions & 7 deletions src/aztec/detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,7 @@ impl<'a> Detector<'_> {
|| !self.is_valid(&bulls_eye_corners[2])
|| !self.is_valid(&bulls_eye_corners[3])
{
return Err(Exceptions::NotFoundException(Some(
"no valid points".to_owned(),
)));
return Err(Exceptions::notFoundWith("no valid points"));
}
let length = 2 * self.nb_center_layers;
// Get the bits around the bull's eye
Expand Down Expand Up @@ -207,9 +205,7 @@ impl<'a> Detector<'_> {
return Ok(shift);
}
}
Err(Exceptions::NotFoundException(Some(
"rotation failure".to_owned(),
)))
Err(Exceptions::notFoundWith("rotation failure"))
}

/**
Expand Down Expand Up @@ -318,7 +314,7 @@ impl<'a> Detector<'_> {
}

if self.nb_center_layers != 5 && self.nb_center_layers != 7 {
return Err(Exceptions::NotFoundException(None));
return Err(Exceptions::notFound);
}

self.compact = self.nb_center_layers == 5;
Expand Down
36 changes: 18 additions & 18 deletions src/aztec/encoder/aztec_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub const WORD_SIZE: [u32; 33] = [
pub fn encode_simple(data: &str) -> Result<AztecCode> {
let Ok(bytes) = encoding::all::ISO_8859_1
.encode(data, encoding::EncoderTrap::Replace) else {
return Err(Exceptions::IllegalArgumentException(Some(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)
}
Expand All @@ -71,9 +71,9 @@ pub fn encode(data: &str, minECCPercent: u32, userSpecifiedLayers: i32) -> Resul
if let Ok(bytes) = encoding::all::ISO_8859_1.encode(data, encoding::EncoderTrap::Strict) {
encode_bytes(&bytes, minECCPercent, userSpecifiedLayers)
} else {
Err(Exceptions::IllegalArgumentException(Some(format!(
Err(Exceptions::illegalArgumentWith(format!(
"'{data}' cannot be encoded as ISO_8859_1"
))))
)))
}
}

Expand All @@ -98,9 +98,9 @@ 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::IllegalArgumentException(Some(format!(
Err(Exceptions::illegalArgumentWith(format!(
"'{data}' cannot be encoded as ISO_8859_1"
))))
)))
}
}

Expand Down Expand Up @@ -174,24 +174,24 @@ pub fn encode_bytes_with_charset(
MAX_NB_BITS
})
{
return Err(Exceptions::IllegalArgumentException(Some(format!(
return Err(Exceptions::illegalArgumentWith(format!(
"Illegal value {user_specified_layers} for layers"
))));
)));
}
total_bits_in_layer_var = total_bits_in_layer(layers, compact);
word_size = WORD_SIZE[layers as usize];
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::IllegalArgumentException(Some(
"Data to large for user specified layer".to_owned(),
)));
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::IllegalArgumentException(Some(
"Data to large for user specified layer".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Data to large for user specified layer",
));
}
} else {
word_size = 0;
Expand All @@ -203,9 +203,9 @@ pub fn encode_bytes_with_charset(
loop {
// for (int i = 0; ; i++) {
if i > MAX_NB_BITS {
return Err(Exceptions::IllegalArgumentException(Some(
"Data too large for an Aztec code".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Data too large for an Aztec code",
));
}
compact = i <= 3;
layers = if compact { i + 1 } else { i };
Expand Down Expand Up @@ -474,9 +474,9 @@ fn getGF(wordSize: usize) -> Result<GenericGFRef> {
8 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData8)),
10 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData10)),
12 => Ok(get_predefined_genericgf(PredefinedGenericGF::AztecData12)),
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
_ => Err(Exceptions::illegalArgumentWith(format!(
"Unsupported word size {wordSize}"
)))),
))),
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/aztec/encoder/high_level_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@ impl HighLevelEncoder {
initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?;
}
} else {
return Err(Exceptions::IllegalArgumentException(Some(
"No ECI code for character set".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"No ECI code for character set",
));
}
// if self.charset != null {
// CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(charset);
Expand Down
8 changes: 4 additions & 4 deletions src/aztec/encoder/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ impl State {
token.add(0, 3); // 0: FNC1
} else */
if eci > 999999 {
return Err(Exceptions::IllegalArgumentException(Some(
"ECI code must be between 0 and 999999".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"ECI code must be between 0 and 999999",
));
// throw new IllegalArgumentException("ECI code must be between 0 and 999999");
} else {
let Ok(eci_digits) = encoding::all::ISO_8859_1
.encode(&format!("{eci}"), encoding::EncoderTrap::Strict)
else {
return Err(Exceptions::IllegalArgumentException(None))
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
Expand Down
4 changes: 2 additions & 2 deletions src/aztec/encoder/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ impl TokenType {
match self {
TokenType::Simple(a) => a.appendTo(bit_array, text),
TokenType::BinaryShift(a) => a.appendTo(bit_array, text),
TokenType::Empty => Err(Exceptions::IllegalStateException(Some(String::from(
TokenType::Empty => Err(Exceptions::illegalStateWith(
"cannot appendTo on Empty final item",
)))),
)),
}
}
}
Expand Down
18 changes: 9 additions & 9 deletions src/client/result/AddressBookParsedResult.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,19 +121,19 @@ impl AddressBookParsedRXingResult {
geo: Vec<String>,
) -> Result<Self> {
if phone_numbers.len() != phone_types.len() && !phone_types.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(
"Phone numbers and types lengths differ".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Phone numbers and types lengths differ",
));
}
if emails.len() != email_types.len() && !email_types.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(
"Emails and types lengths differ".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Emails and types lengths differ",
));
}
if addresses.len() != address_types.len() && !address_types.is_empty() {
return Err(Exceptions::IllegalArgumentException(Some(
"Addresses and types lengths differ".to_owned(),
)));
return Err(Exceptions::illegalArgumentWith(
"Addresses and types lengths differ",
));
}
Ok(Self {
names,
Expand Down
Loading

0 comments on commit 7b891bd

Please sign in to comment.