Implement clippy suggestions

This commit is contained in:
Henry Schimke
2023-01-04 14:48:16 -06:00
parent c65eadf102
commit 48287631dd
196 changed files with 2465 additions and 2574 deletions

View File

@@ -73,10 +73,10 @@ impl Encoder for ASCIIEncoder {
}
_ => {
return Err(Exceptions::IllegalStateException(format!(
return Err(Exceptions::IllegalStateException(Some(format!(
"Illegal mode: {}",
newMode
)));
))));
}
}
} else if high_level_encoder::isExtendedASCII(c) {
@@ -105,10 +105,15 @@ impl ASCIIEncoder {
let num = (digit1 as u8 - 48) * 10 + (digit2 as u8 - 48);
Ok((num + 130) as char)
} else {
Err(Exceptions::IllegalArgumentException(format!(
Err(Exceptions::IllegalArgumentException(Some(format!(
"not digits: {}{}",
digit1, digit2
)))
))))
}
}
}
impl Default for ASCIIEncoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -65,10 +65,10 @@ impl Encoder for Base256Encoder {
let (ci_pos, _) = buffer.char_indices().nth(1).unwrap();
buffer.insert(ci_pos, char::from_u32(dataCount as u32 % 250).unwrap());
} else {
return Err(Exceptions::IllegalStateException(format!(
return Err(Exceptions::IllegalStateException(Some(format!(
"Message length not in valid ranges: {}",
dataCount
)));
))));
}
}
let c = buffer.chars().count();
@@ -96,3 +96,9 @@ impl Base256Encoder {
}
}
}
impl Default for Base256Encoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -167,7 +167,7 @@ impl C40Encoder {
let c = context.getCurrentChar();
let lastCharSize = encodeChar(c, removed);
context.resetSymbolInfo(); //Deal with possible reduction in symbol size
return lastCharSize;
lastCharSize
}
pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) {
@@ -219,9 +219,9 @@ impl C40Encoder {
context.writeCodeword(C40_UNLATCH);
}
} else {
return Err(Exceptions::IllegalStateException(
return Err(Exceptions::IllegalStateException(Some(
"Unexpected case. Please report!".to_owned(),
));
)));
}
context.signalEncoderChange(ASCII_ENCODATION);
@@ -233,11 +233,11 @@ impl C40Encoder {
sb.push('\u{3}');
return 1;
}
if c >= '0' && c <= '9' {
if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char);
return 1;
}
if c >= 'A' && c <= 'Z' {
if ('A'..='Z').contains(&c) {
sb.push((c as u8 - 65 + 14) as char);
return 1;
}
@@ -274,7 +274,7 @@ impl C40Encoder {
}
fn encodeToCodewords(sb: &str) -> String {
let v = (1600 * sb.chars().nth(0).unwrap() as u32)
let v = (1600 * sb.chars().next().unwrap() as u32)
+ (40 * sb.chars().nth(1).unwrap() as u32)
+ sb.chars().nth(2).unwrap() as u32
+ 1;
@@ -286,3 +286,9 @@ impl C40Encoder {
// return new String(new char[] {cw1, cw2});
}
}
impl Default for C40Encoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -64,7 +64,7 @@ impl DefaultPlacement {
}
pub fn setBit(&mut self, col: usize, row: usize, bit: bool) {
self.bits[row * self.numcols + col] = if bit { 1 } else { 0 };
self.bits[row * self.numcols + col] = u8::from(bit); //if bit { 1 } else { 0 };
}
pub fn noBit(&self, col: usize, row: usize) -> bool {
@@ -281,7 +281,7 @@ mod test_placement {
fn unvisualize(visualized: &str) -> String {
let mut sb = String::new();
for token in visualized.split(" ") {
for token in visualized.split(' ') {
// for (String token : SPACE.split(visualized)) {
let tkn: u32 = token.parse().unwrap();
sb.push(char::from_u32(tkn).unwrap());

View File

@@ -65,7 +65,7 @@ impl EdifactEncoder {
* @param context the encoder context
* @param buffer the buffer with the remaining encoded characters
*/
fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> {
fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> {
let mut runner = || -> Result<(), Exceptions> {
let count = buffer.chars().count();
if count == 0 {
@@ -89,9 +89,9 @@ impl EdifactEncoder {
}
if count > 4 {
return Err(Exceptions::IllegalStateException(
return Err(Exceptions::IllegalStateException(Some(
"Count must not exceed 4".to_owned(),
));
)));
}
let restChars = count - 1;
let encoded = Self::encodeToCodewords(buffer)?;
@@ -127,9 +127,9 @@ impl EdifactEncoder {
}
fn encodeChar(c: char, sb: &mut String) {
if c >= ' ' && c <= '?' {
if (' '..='?').contains(&c) {
sb.push(c);
} else if c >= '@' && c <= '^' {
} else if ('@'..='^').contains(&c) {
sb.push((c as u8 - 64) as char);
} else {
high_level_encoder::illegalCharacter(c).expect("");
@@ -139,11 +139,11 @@ impl EdifactEncoder {
fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> {
let len = sb.chars().count();
if len == 0 {
return Err(Exceptions::IllegalStateException(
return Err(Exceptions::IllegalStateException(Some(
"StringBuilder must not be empty".to_owned(),
));
)));
}
let c1 = sb.chars().nth(0).unwrap();
let c1 = sb.chars().next().unwrap();
let c2 = if len >= 2 {
sb.chars().nth(1).unwrap()
} else {
@@ -161,9 +161,9 @@ impl EdifactEncoder {
};
let v: u32 = ((c1 as u32) << 18) + ((c2 as u32) << 12) + ((c3 as u32) << 6) + c4 as u32;
let cw1 = (v as u32 >> 16) & 255;
let cw2 = (v as u32 >> 8) & 255;
let cw3 = v as u32 & 255;
let cw1 = (v >> 16) & 255;
let cw2 = (v >> 8) & 255;
let cw3 = v & 255;
let mut res = String::with_capacity(3);
res.push(char::from_u32(cw1).unwrap());
if len >= 2 {
@@ -176,3 +176,9 @@ impl EdifactEncoder {
Ok(res)
}
}
impl Default for EdifactEncoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -64,9 +64,9 @@ impl<'a> EncoderContext<'_> {
.decode(&encoded_bytes, encoding::DecoderTrap::Strict)
.expect("round trip decode should always work")
} else {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"Message contains characters outside ISO-8859-1 encoding.".to_owned(),
));
)));
};
Ok(Self {
symbol_lookup: Rc::new(SymbolInfoLookup::new()),

View File

@@ -152,9 +152,9 @@ 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::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"The number of codewords does not match the selected symbol".to_owned(),
));
)));
}
let mut sb = String::with_capacity(
(symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()) as usize,
@@ -171,7 +171,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
for i in 0..blockCount {
// for (int i = 0; i < blockCount; i++) {
dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i as u32 + 1) as u32;
errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i as u32 + 1) as u32;
errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i as u32 + 1);
}
for block in 0..blockCount {
// for (int block = 0; block < blockCount; block++) {
@@ -186,7 +186,7 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
let ecc = createECCBlock(&temp, errorSizes[block] as usize)?;
let mut pos = 0;
let mut e = block;
while e < errorSizes[block] as usize * blockCount as usize {
while e < errorSizes[block] as usize * blockCount {
// for (int e = block; e < errorSizes[block] * blockCount; e += blockCount) {
let (char_index, replace_char) = sb
.char_indices()
@@ -209,18 +209,19 @@ pub fn encodeECC200(codewords: &str, symbolInfo: &SymbolInfo) -> Result<String,
fn createECCBlock(codewords: &str, numECWords: usize) -> Result<String, Exceptions> {
let mut table = -1_isize;
for i in 0..FACTOR_SETS.len() {
for (i, set) in FACTOR_SETS.iter().enumerate() {
// for i in 0..FACTOR_SETS.len() {
// for (int i = 0; i < FACTOR_SETS.length; i++) {
if FACTOR_SETS[i] as usize == numECWords {
if set == &(numECWords as u32) {
table = i as isize;
break;
}
}
if table < 0 {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal number of error correction codewords specified: {}",
numECWords
)));
))));
}
let poly = &FACTORS[table as usize];
let mut ecc = vec![0 as char; numECWords];

View File

@@ -119,7 +119,7 @@ fn testC40EncodationSpecialCases1() {
let substitute_symbols = SymbolInfoLookup::new();
let substitute_symbols = useTestSymbols(substitute_symbols);
let sil = Rc::new(substitute_symbols.clone());
let sil = Rc::new(substitute_symbols);
let visualized = encodeHighLevelCompareSIL("AIMAIMAIMAIMAIMAIM", false, Some(sil.clone()));
assert_eq!("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized);

View File

@@ -284,7 +284,7 @@ pub fn encodeHighLevelWithDimensionForceC40(
pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize {
let newMode = lookAheadTestIntern(msg, startpos, currentMode);
if currentMode as usize == X12_ENCODATION && newMode as usize == X12_ENCODATION {
if currentMode as usize == X12_ENCODATION && newMode == X12_ENCODATION {
// let msg_graphemes = msg.graphemes(true);
let endpos = (startpos + 3).min(msg.chars().count() as u32);
for i in startpos..endpos {
@@ -540,20 +540,15 @@ fn findMinimums(
mins[i] += 1;
}
}
return min;
min
}
fn getMinimumCount(mins: &[u8]) -> u32 {
let mut minCount = 0;
for i in 0..6 {
// for (int i = 0; i < 6; i++) {
minCount += mins[i] as u32;
}
minCount
mins.iter().take(6).sum::<u8>() as u32
}
pub fn isDigit(ch: char) -> bool {
ch >= '0' && ch <= '9'
('0'..='9').contains(&ch)
}
pub fn isExtendedASCII(ch: char) -> bool {
@@ -561,15 +556,15 @@ pub fn isExtendedASCII(ch: char) -> bool {
}
pub fn isNativeC40(ch: char) -> bool {
(ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')
(ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch)
}
pub fn isNativeText(ch: char) -> bool {
(ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z')
(ch == ' ') || ('0'..='9').contains(&ch) || ('a'..='z').contains(&ch)
}
pub fn isNativeX12(ch: char) -> bool {
return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
isX12TermSep(ch) || (ch == ' ') || ('0'..='9').contains(&ch) || ('A'..='Z').contains(&ch)
}
fn isX12TermSep(ch: char) -> bool {
@@ -579,7 +574,7 @@ fn isX12TermSep(ch: char) -> bool {
}
pub fn isNativeEDIFACT(ch: char) -> bool {
ch >= ' ' && ch <= '^'
(' '..='^').contains(&ch)
}
fn isSpecialB256(_ch: char) -> bool {
@@ -607,8 +602,8 @@ 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::IllegalArgumentException(format!(
Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal character: {} (0x{})",
c, c
)))
))))
}

View File

@@ -65,22 +65,22 @@ const ISO_8859_1_ENCODER: EncodingRef = encoding::all::ISO_8859_1;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Mode {
ASCII,
Ascii,
C40,
TEXT,
Text,
X12,
EDF,
Edf,
B256,
}
impl Mode {
pub fn ordinal(&self) -> usize {
match self {
Mode::ASCII => 0,
Mode::Ascii => 0,
Mode::C40 => 1,
Mode::TEXT => 2,
Mode::Text => 2,
Mode::X12 => 3,
Mode::EDF => 4,
Mode::Edf => 4,
Mode::B256 => 5,
}
}
@@ -177,8 +177,7 @@ pub fn encodeHighLevelWithDetails(
&encode(msg, priorityCharset, fnc1, shape, macroId)?,
encoding::DecoderTrap::Strict,
)
.expect("should decode")
.to_owned())
.expect("should decode"))
// return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1);
}
@@ -214,7 +213,7 @@ fn encode(
.to_vec())
}
fn addEdge(edges: &mut Vec<Vec<Option<Rc<Edge>>>>, edge: Rc<Edge>) -> Result<(), Exceptions> {
fn addEdge(edges: &mut [Vec<Option<Rc<Edge>>>], edge: Rc<Edge>) -> Result<(), Exceptions> {
let vertexIndex = (edge.fromPosition + edge.characterLength) as usize;
if edges[vertexIndex][edge.getEndMode()?.ordinal()].is_none()
|| edges[vertexIndex][edge.getEndMode()?.ordinal()]
@@ -256,7 +255,7 @@ fn getNumberOfC40Words(
} else if !isExtendedASCII(ci, input.getFNC1Character()) {
thirdsCount += 2; //shift
} else {
let asciiValue = ci as u8 & 0xff;
let asciiValue = ci as u8;
if asciiValue >= 128
&& (c40 && high_level_encoder::isNativeC40((asciiValue - 128) as char)
|| !c40 && high_level_encoder::isNativeText((asciiValue - 128) as char))
@@ -280,20 +279,20 @@ fn getNumberOfC40Words(
fn addEdges(
input: Rc<Input>,
edges: &mut Vec<Vec<Option<Rc<Edge>>>>,
edges: &mut [Vec<Option<Rc<Edge>>>],
from: u32,
previous: Option<Rc<Edge>>,
) -> Result<(), Exceptions> {
if input.isECI(from)? {
addEdge(
edges,
Rc::new(Edge::new(input, Mode::ASCII, from, 1, previous.clone())?),
Rc::new(Edge::new(input, Mode::Ascii, from, 1, previous)?),
)?;
return Ok(());
}
let ch = input.charAt(from as usize)?;
if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::EDF {
if previous.is_none() || previous.as_ref().unwrap().getEndMode()? != Mode::Edf {
//not possible to unlatch a full EDF edge to something
//else
if high_level_encoder::isDigit(ch)
@@ -305,7 +304,7 @@ fn addEdges(
edges,
Rc::new(Edge::new(
input.clone(),
Mode::ASCII,
Mode::Ascii,
from,
2,
previous.clone(),
@@ -317,7 +316,7 @@ fn addEdges(
edges,
Rc::new(Edge::new(
input.clone(),
Mode::ASCII,
Mode::Ascii,
from,
1,
previous.clone(),
@@ -325,7 +324,7 @@ fn addEdges(
)?;
}
let modes = [Mode::C40, Mode::TEXT];
let modes = [Mode::C40, Mode::Text];
for mode in modes {
// for (Mode mode : modes) {
let mut characterLength = [0u32; 1];
@@ -387,7 +386,7 @@ fn addEdges(
edges,
Rc::new(Edge::new(
input.clone(),
Mode::EDF,
Mode::Edf,
from,
i + 1,
previous.clone(),
@@ -404,7 +403,7 @@ fn addEdges(
{
addEdge(
edges,
Rc::new(Edge::new(input, Mode::EDF, from, 4, previous.clone())?),
Rc::new(Edge::new(input, Mode::Edf, from, 4, previous)?),
)?;
}
Ok(())
@@ -626,7 +625,7 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> {
// for (int j = 0; j < 6; j++) {
if edges[inputLength][j].is_some() {
let edge = edges[inputLength][j].as_ref().unwrap();
let size = if j >= 1 && j <= 3 {
let size = if (1..=3).contains(&j) {
edge.cachedTotalSize + 1
} else {
edge.cachedTotalSize
@@ -640,10 +639,10 @@ fn encodeMinimally(input: Rc<Input>) -> Result<RXingResult, Exceptions> {
}
if minimalJ < 0 {
return Err(Exceptions::RuntimeException(format!(
return Err(Exceptions::RuntimeException(Some(format!(
"Internal error: failed to encode \"{}\"",
input
)));
))));
}
RXingResult::new(edges[inputLength][minimalJ as usize].clone())
}
@@ -704,7 +703,7 @@ impl Edge {
* B256 -> ASCII: without latch after n bytes
*/
match mode {
Mode::ASCII => {
Mode::Ascii => {
size += 1;
if input.isECI(fromPosition).expect("bool")
|| isExtendedASCII(
@@ -717,7 +716,7 @@ impl Edge {
size += 1;
}
if previousMode == Mode::C40
|| previousMode == Mode::TEXT
|| previousMode == Mode::Text
|| previousMode == Mode::X12
{
size += 1; // unlatch 254 to ASCII
@@ -725,21 +724,22 @@ impl Edge {
}
Mode::B256 => {
size += 1;
if previousMode != Mode::B256 {
if previousMode != Mode::B256 || Self::getB256Size(mode, previous.clone()) == 250 {
size += 1; //byte count
} else if Self::getB256Size(mode, previous.clone()) == 250 {
size += 1; //extra byte count
}
if previousMode == Mode::ASCII {
// } else if Self::getB256Size(mode, previous.clone()) == 250 {
// size += 1; //extra byte count
// }
if previousMode == Mode::Ascii {
size += 1; //latch to B256
} else if previousMode == Mode::C40
|| previousMode == Mode::TEXT
|| previousMode == Mode::Text
|| previousMode == Mode::X12
{
size += 2; //unlatch to ASCII, latch to B256
}
}
Mode::C40 | Mode::TEXT | Mode::X12 => {
Mode::C40 | Mode::Text | Mode::X12 => {
if mode == Mode::X12 {
size += 2;
} else {
@@ -754,22 +754,22 @@ impl Edge {
* 2;
}
if previousMode == Mode::ASCII || previousMode == Mode::B256 {
if previousMode == Mode::Ascii || previousMode == Mode::B256 {
size += 1; //additional byte for latch from ASCII to this mode
} else if previousMode != mode
&& (previousMode == Mode::C40
|| previousMode == Mode::TEXT
|| previousMode == Mode::Text
|| previousMode == Mode::X12)
{
size += 2; //unlatch 254 to ASCII followed by latch to this mode
}
}
Mode::EDF => {
Mode::Edf => {
size += 3;
if previousMode == Mode::ASCII || previousMode == Mode::B256 {
if previousMode == Mode::Ascii || previousMode == Mode::B256 {
size += 1; //additional byte for latch from ASCII to this mode
} else if previousMode == Mode::C40
|| previousMode == Mode::TEXT
|| previousMode == Mode::Text
|| previousMode == Mode::X12
{
size += 2; //unlatch 254 to ASCII followed by latch to this mode
@@ -811,7 +811,7 @@ impl Edge {
if let Some(prev) = previous {
prev.mode
} else {
Mode::ASCII
Mode::Ascii
}
// if previous.is_none() { Mode::ASCII} else {previous.as_ref().unwrap().mode}
}
@@ -820,7 +820,7 @@ impl Edge {
if let Some(prev) = previous {
prev.getEndMode()
} else {
Ok(Mode::ASCII)
Ok(Mode::Ascii)
}
// return previous == null ? Mode::ASCII : previous.getEndMode();
}
@@ -833,27 +833,27 @@ impl Edge {
* */
pub fn getEndMode(&self) -> Result<Mode, Exceptions> {
let mode = self.mode;
if mode == Mode::EDF {
if mode == Mode::Edf {
if self.characterLength < 4 {
return Ok(Mode::ASCII);
return Ok(Mode::Ascii);
}
let lastASCII = Self::getLastASCII(&self)?; // see 5.2.8.2 EDIFACT encodation Rules
let lastASCII = Self::getLastASCII(self)?; // see 5.2.8.2 EDIFACT encodation Rules
if lastASCII > 0
&& self.getCodewordsRemaining(self.cachedTotalSize + lastASCII) <= 2 - lastASCII
{
return Ok(Mode::ASCII);
return Ok(Mode::Ascii);
}
}
if mode == Mode::C40 || mode == Mode::TEXT || mode == Mode::X12 {
if mode == Mode::C40 || mode == Mode::Text || mode == Mode::X12 {
// see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules
if self.fromPosition + self.characterLength >= self.input.length() as u32
&& self.getCodewordsRemaining(self.cachedTotalSize) == 0
{
return Ok(Mode::ASCII);
return Ok(Mode::Ascii);
}
let lastASCII = Self::getLastASCII(&self)?;
let lastASCII = Self::getLastASCII(self)?;
if lastASCII == 1 && self.getCodewordsRemaining(self.cachedTotalSize + 1) == 0 {
return Ok(Mode::ASCII);
return Ok(Mode::Ascii);
}
}
@@ -969,7 +969,7 @@ impl Edge {
* minimal number of codewords.
**/
pub fn getCodewordsRemaining(&self, minimum: u32) -> u32 {
Self::getMinSymbolSize(&self, minimum) - minimum
Self::getMinSymbolSize(self, minimum) - minimum
}
pub fn getBytes1(c: u32) -> Vec<u8> {
@@ -1003,9 +1003,9 @@ impl Edge {
2
} else if c == 32 {
3
} else if c >= 48 && c <= 57 {
} else if (48..=57).contains(&c) {
c - 44
} else if c >= 65 && c <= 90 {
} else if (65..=90).contains(&c) {
c - 51
} else {
c
@@ -1033,7 +1033,7 @@ impl Edge {
);
i += 2;
}
return Ok(result);
Ok(result)
}
pub fn getShiftValue(c: char, c40: bool, fnc1: Option<char>) -> u32 {
@@ -1055,7 +1055,7 @@ impl Edge {
}
if c40 {
let c = c as u32;
return if c <= 31 {
if c <= 31 {
c
} else if c == 32 {
3
@@ -1073,10 +1073,10 @@ impl Edge {
c - 96
} else {
c
};
}
} else {
let c = c as u32;
return if c == 0 {
if c == 0 {
0
} else if setIndex == 0 && c <= 3 {
c - 1
@@ -1086,25 +1086,25 @@ impl Edge {
c
} else if c == 32 {
3
} else if c >= 33 && c <= 47 {
} else if (33..=47).contains(&c) {
c - 33
} else if c >= 48 && c <= 57 {
} else if (48..=57).contains(&c) {
c - 44
} else if c >= 58 && c <= 64 {
} else if (58..=64).contains(&c) {
c - 43
} else if c >= 65 && c <= 90 {
} else if (65..=90).contains(&c) {
c - 64
} else if c >= 91 && c <= 95 {
} else if (91..=95).contains(&c) {
c - 69
} else if c == 96 {
0
} else if c >= 97 && c <= 122 {
} else if (97..=122).contains(&c) {
c - 83
} else if c >= 123 && c <= 127 {
} else if (123..=127).contains(&c) {
c - 96
} else {
c
};
}
}
}
@@ -1123,7 +1123,7 @@ impl Edge {
c40Values.push(shiftValue as u8); //Shift[123]
c40Values.push(Self::getC40Value(c40, shiftValue, ci, fnc1) as u8);
} else {
let asciiValue = ((ci as u8 & 0xff) - 128) as char;
let asciiValue = (ci as u8 - 128) as char;
if c40 && high_level_encoder::isNativeC40(asciiValue)
|| !c40 && high_level_encoder::isNativeText(asciiValue)
{
@@ -1178,13 +1178,14 @@ impl Edge {
while i < numberOfThirds {
// for (int i = 0; i < numberOfThirds; i += 3) {
let mut edfValues = [0u32; 4];
for j in 0..4 {
for edfValue in &mut edfValues {
// for j in 0..4 {
// for (int j = 0; j < 4; j++) {
if pos <= endPos {
edfValues[j] = self.input.charAt(pos)? as u32 & 0x3f;
*edfValue = self.input.charAt(pos)? as u32 & 0x3f;
pos += 1;
} else {
edfValues[j] = if pos == endPos + 1 { 0x1f } else { 0 };
*edfValue = if pos == endPos + 1 { 0x1f } else { 0 };
}
}
let mut val24 = edfValues[0] << 18;
@@ -1203,32 +1204,32 @@ impl Edge {
pub fn getLatchBytes(&self) -> Result<Vec<u8>, Exceptions> {
match Self::getPreviousMode(self.previous.clone())? {
Mode::ASCII | Mode::B256 =>
Mode::Ascii | Mode::B256 =>
//after B256 ends (via length) we are back to ASCII
{
match self.mode {
Mode::B256 => return Ok(Self::getBytes1(231)),
Mode::C40 => return Ok(Self::getBytes1(230)),
Mode::TEXT => return Ok(Self::getBytes1(239)),
Mode::Text => return Ok(Self::getBytes1(239)),
Mode::X12 => return Ok(Self::getBytes1(238)),
Mode::EDF => return Ok(Self::getBytes1(240)),
Mode::Edf => return Ok(Self::getBytes1(240)),
_ => {}
}
}
Mode::C40 | Mode::TEXT | Mode::X12
Mode::C40 | Mode::Text | Mode::X12
if self.mode != Self::getPreviousMode(self.previous.clone())? =>
{
match self.mode {
Mode::ASCII => return Ok(Self::getBytes1(254)),
Mode::Ascii => return Ok(Self::getBytes1(254)),
Mode::B256 => return Ok(Self::getBytes2(254, 231)),
Mode::C40 => return Ok(Self::getBytes2(254, 230)),
Mode::TEXT => return Ok(Self::getBytes2(254, 239)),
Mode::Text => return Ok(Self::getBytes2(254, 239)),
Mode::X12 => return Ok(Self::getBytes2(254, 238)),
Mode::EDF => return Ok(Self::getBytes2(254, 240)),
Mode::Edf => return Ok(Self::getBytes2(254, 240)),
}
}
Mode::C40 | Mode::TEXT | Mode::X12 => {}
Mode::EDF => assert!(self.mode == Mode::EDF), //The rightmost EDIFACT edge always contains an unlatch character
Mode::C40 | Mode::Text | Mode::X12 => {}
Mode::Edf => assert!(self.mode == Mode::Edf), //The rightmost EDIFACT edge always contains an unlatch character
}
Ok(Vec::new())
@@ -1237,12 +1238,12 @@ impl Edge {
// Important: The function does not return the length bytes (one or two) in case of B256 encoding
pub fn getDataBytes(&self) -> Result<Vec<u8>, Exceptions> {
match self.mode {
Mode::ASCII => {
Mode::Ascii => {
if self.input.isECI(self.fromPosition)? {
return Ok(Self::getBytes2(
Ok(Self::getBytes2(
241,
self.input.getECIValue(self.fromPosition as usize)? as u32 + 1,
));
))
} else if isExtendedASCII(
self.input.charAt(self.fromPosition as usize)?,
self.input.getFNC1Character(),
@@ -1266,15 +1267,13 @@ impl Edge {
));
}
}
Mode::B256 => {
return Ok(Self::getBytes1(
self.input.charAt(self.fromPosition as usize)? as u32,
))
}
Mode::C40 => return self.getC40Words(true, self.input.getFNC1Character()),
Mode::TEXT => return self.getC40Words(false, self.input.getFNC1Character()),
Mode::X12 => return self.getX12Words(),
Mode::EDF => return self.getEDFBytes(),
Mode::B256 => Ok(Self::getBytes1(
self.input.charAt(self.fromPosition as usize)? as u32,
)),
Mode::C40 => self.getC40Words(true, self.input.getFNC1Character()),
Mode::Text => self.getC40Words(false, self.input.getFNC1Character()),
Mode::X12 => self.getX12Words(),
Mode::Edf => self.getEDFBytes(),
}
// assert!( false);
// Ok(vec![0])
@@ -1289,15 +1288,15 @@ impl RXingResult {
let solution = if let Some(edge) = solution {
edge
} else {
return Err(Exceptions::IllegalArgumentException("()".to_string()));
return Err(Exceptions::IllegalArgumentException(None));
};
let input = solution.input.clone();
let mut size = 0;
let mut bytesAL = Vec::new(); //new ArrayList<>();
let mut randomizePostfixLength = Vec::new(); //new ArrayList<>();
let mut randomizeLengths = Vec::new(); //new ArrayList<>();
if (solution.mode == Mode::C40 || solution.mode == Mode::TEXT || solution.mode == Mode::X12)
&& solution.getEndMode()? != Mode::ASCII
if (solution.mode == Mode::C40 || solution.mode == Mode::Text || solution.mode == Mode::X12)
&& solution.getEndMode()? != Mode::Ascii
{
size += Self::prepend(&Edge::getBytes1(254), &mut bytesAL);
}
@@ -1355,10 +1354,11 @@ impl RXingResult {
}
let mut bytes = vec![0u8; bytesAL.len()];
for i in 0..bytes.len() {
// for (int i = 0; i < bytes.length; i++) {
bytes[i] = *bytesAL.get(i).unwrap();
}
// for (i, byte) in bytes.iter_mut().enumerate() {
// // for (int i = 0; i < bytes.length; i++) {
// *byte = *bytesAL.get(i).unwrap();
// }
bytes[..].copy_from_slice(&bytesAL[..]);
Ok(Self { bytes })
}

View File

@@ -127,9 +127,9 @@ impl SymbolInfo {
2 | 4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::IllegalStateException(
_ => Err(Exceptions::IllegalStateException(Some(
"Cannot handle this number of data regions".to_owned(),
)),
))),
}
// switch (dataRegions) {
// case 1:
@@ -152,9 +152,9 @@ impl SymbolInfo {
4 => Ok(2),
16 => Ok(4),
36 => Ok(6),
_ => Err(Exceptions::IllegalStateException(
_ => Err(Exceptions::IllegalStateException(Some(
"Cannot handle this number of data regions".to_owned(),
)),
))),
}
// switch (dataRegions) {
// case 1:
@@ -344,10 +344,10 @@ impl<'a> SymbolInfoLookup<'a> {
}
}
if fail {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can't find a symbol arrangement that matches the message. Data codewords: {}",
dataCodewords
)));
))));
}
Ok(None)
}

View File

@@ -40,11 +40,11 @@ impl TextEncoder {
sb.push('\u{3}');
return 1;
}
if c >= '0' && c <= '9' {
if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char);
return 1;
}
if c >= 'a' && c <= 'z' {
if ('a'..='z').contains(&c) {
sb.push((c as u8 - 97 + 14) as char);
return 1;
}
@@ -63,7 +63,7 @@ impl TextEncoder {
sb.push((c as u8 - 58 + 15) as char);
return 2;
}
if c >= '[' && c <= '_' {
if ('['..='_').contains(&c) {
sb.push('\u{1}'); //Shift 2 Set
sb.push((c as u8 - 91 + 22) as char);
return 2;
@@ -86,6 +86,12 @@ impl TextEncoder {
sb.push_str("\u{1}\u{001e}"); //Shift 2, Upper Shift
let mut len = 2;
len += Self::encodeChar((c as u8 - 128) as char, sb);
return len;
len
}
}
impl Default for TextEncoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -65,19 +65,19 @@ impl X12Encoder {
'>' => sb.push('\u{2}'),
' ' => sb.push('\u{3}'),
_ => {
if c >= '0' && c <= '9' {
if ('0'..='9').contains(&c) {
sb.push((c as u8 - 48 + 4) as char);
} else if c >= 'A' && c <= 'Z' {
} else if ('A'..='Z').contains(&c) {
sb.push((c as u8 - 65 + 14) as char);
} else {
high_level_encoder::illegalCharacter(c).expect("detect_illegal_character");
}
}
}
return 1;
1
}
fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> {
fn handleEOD(context: &mut EncoderContext, buffer: &mut str) -> Result<(), Exceptions> {
context.updateSymbolInfo();
let available =
context.getSymbolInfo().unwrap().getDataCapacity() - context.getCodewordCount() as u32;
@@ -95,3 +95,9 @@ impl X12Encoder {
Ok(())
}
}
impl Default for X12Encoder {
fn default() -> Self {
Self::new()
}
}