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

@@ -83,7 +83,7 @@ impl Reader for DataMatrixReader {
points = detectorRXingResult.getPoints().clone();
}
let mut result = RXingResult::new(
decoderRXingResult.getText().clone(),
decoderRXingResult.getText(),
decoderRXingResult.getRawBytes().clone(),
points.clone(),
BarcodeFormat::DATA_MATRIX,
@@ -127,10 +127,10 @@ impl DataMatrixReader {
*/
fn extractPureBits(&self, image: &BitMatrix) -> Result<BitMatrix, Exceptions> {
let Some(leftTopBlack) = image.getTopLeftOnBit() else {
return Err(Exceptions::NotFoundException("".to_owned()))
return Err(Exceptions::NotFoundException(None))
};
let Some(rightBottomBlack) = image.getBottomRightOnBit()else {
return Err(Exceptions::NotFoundException("".to_owned()))
return Err(Exceptions::NotFoundException(None))
};
let moduleSize = Self::moduleSize(&leftTopBlack, image)?;
@@ -143,7 +143,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::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
// throw NotFoundException.getNotFoundInstance();
}
@@ -180,12 +180,12 @@ impl DataMatrixReader {
x += 1;
}
if x == width {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
let moduleSize = x - leftTopBlack[0];
if moduleSize == 0 {
return Err(Exceptions::NotFoundException("".to_owned()));
return Err(Exceptions::NotFoundException(None));
}
Ok(moduleSize)

View File

@@ -60,23 +60,23 @@ impl Writer for DataMatrixWriter {
hints: &crate::EncodingHintDictionary,
) -> Result<crate::common::BitMatrix, crate::Exceptions> {
if contents.is_empty() {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"Found empty contents".to_owned(),
));
)));
}
if format != &BarcodeFormat::DATA_MATRIX {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Can only encode DATA_MATRIX, but got {:?}",
format
)));
))));
}
if width < 0 || height < 0 {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Requested dimensions can't be negative: {}x{}",
width, height
)));
))));
}
// Try to get force shape & min / max size
@@ -125,7 +125,7 @@ impl Writer for DataMatrixWriter {
if hasEncodingHint {
let Some(EncodeHintValue::CharacterSet(char_set_name)) =
hints.get(&EncodeHintType::CHARACTER_SET) else {
return Err(Exceptions::IllegalArgumentException("charset does not exist".to_owned()))
return Err(Exceptions::IllegalArgumentException(Some("charset does not exist".to_owned())))
};
charset = encoding::label::encoding_from_whatwg_label(char_set_name);
// charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
@@ -159,7 +159,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::NotFoundException("symbol info is bad".to_owned()))
return Err(Exceptions::NotFoundException(Some("symbol info is bad".to_owned())))
};
//2. step: ECC generation

View File

@@ -33,8 +33,8 @@ impl BitMatrixParser {
*/
pub fn new(bitMatrix: &BitMatrix) -> Result<Self, Exceptions> {
let dimension = bitMatrix.getHeight();
if dimension < 8 || dimension > 144 || (dimension & 0x01) != 0 {
return Err(Exceptions::FormatException("".to_owned()));
if !(8..=144).contains(&dimension) || (dimension & 0x01) != 0 {
return Err(Exceptions::FormatException(None));
}
let version = Self::readVersion(bitMatrix)?;
@@ -50,7 +50,7 @@ impl BitMatrixParser {
}
pub fn getVersion(&self) -> &Version {
&self.version
self.version
}
/**
@@ -178,7 +178,7 @@ impl BitMatrixParser {
}
if resultOffset != self.version.getTotalCodewords() as usize {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
Ok(result)
@@ -257,7 +257,7 @@ impl BitMatrixParser {
if self.readModule(row, column, numRows, numColumns) {
currentByte |= 1;
}
return currentByte;
currentByte
}
/**
@@ -302,7 +302,7 @@ impl BitMatrixParser {
if self.readModule(3, numColumns - 1, numRows, numColumns) {
currentByte |= 1;
}
return currentByte;
currentByte
}
/**
@@ -347,7 +347,7 @@ impl BitMatrixParser {
if self.readModule(1, numColumns - 1, numRows, numColumns) {
currentByte |= 1;
}
return currentByte;
currentByte
}
/**
@@ -392,7 +392,7 @@ impl BitMatrixParser {
if self.readModule(1, numColumns - 1, numRows, numColumns) {
currentByte |= 1;
}
return currentByte;
currentByte
}
/**
@@ -437,7 +437,7 @@ impl BitMatrixParser {
if self.readModule(3, numColumns - 1, numRows, numColumns) {
currentByte |= 1;
}
return currentByte;
currentByte
}
/**
@@ -455,9 +455,9 @@ impl BitMatrixParser {
let symbolSizeColumns = version.getSymbolSizeColumns();
if bitMatrix.getHeight() != symbolSizeRows {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"Dimension of bitMatrix must match the version size".to_owned(),
));
)));
}
let dataRegionSizeRows = version.getDataRegionSizeRows();

View File

@@ -93,9 +93,11 @@ impl DataBlock {
let mut rawCodewordsOffset = 0;
for i in 0..shorterBlocksNumDataCodewords {
// for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
for j in 0..numRXingResultBlocks {
for res in result.iter_mut().take(numRXingResultBlocks) {
// for j in 0..numRXingResultBlocks {
// for (int j = 0; j < numRXingResultBlocks; j++) {
result[j].codewords[i] = rawCodewords[rawCodewordsOffset];
res.codewords[i] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
}
@@ -107,10 +109,10 @@ impl DataBlock {
} else {
numRXingResultBlocks
};
for j in 0..numLongerBlocks {
for res in result.iter_mut().take(numLongerBlocks) {
// for j in 0..numLongerBlocks {
// for (int j = 0; j < numLongerBlocks; j++) {
result[j].codewords[longerBlocksNumDataCodewords - 1] =
rawCodewords[rawCodewordsOffset];
res.codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
@@ -136,7 +138,7 @@ impl DataBlock {
}
if rawCodewordsOffset != rawCodewords.len() {
return Err(Exceptions::IllegalArgumentException("".to_owned()));
return Err(Exceptions::IllegalArgumentException(None));
}
Ok(result)

View File

@@ -137,7 +137,7 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
decodeECISegment(&mut bits, &mut result)?;
isECIencoded = true; // ECI detection only, atm continue decoding as ASCII
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
};
mode = Mode::ASCII_ENCODE;
}
@@ -145,7 +145,7 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
break;
}
} //while (mode != Mode.PAD_ENCODE && bits.available() > 0);
if resultTrailer.len() > 0 {
if !resultTrailer.is_empty() {
result.appendCharacters(&resultTrailer);
}
if isECIencoded {
@@ -158,14 +158,12 @@ pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
} else {
symbologyModifier = 4;
}
} else if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
symbologyModifier = 2;
} else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) {
symbologyModifier = 3;
} else {
if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
symbologyModifier = 2;
} else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) {
symbologyModifier = 3;
} else {
symbologyModifier = 1;
}
symbologyModifier = 1;
}
Ok(DecoderRXingResult::with_symbology(
@@ -196,7 +194,7 @@ fn decodeAsciiSegment(
loop {
let mut oneByte = bits.readBits(8)?;
if oneByte == 0 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
} else if oneByte <= 128 {
// ASCII data (ASCII value + 1)
if upperShift {
@@ -256,11 +254,11 @@ 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::FormatException("".to_owned()))
return Err(Exceptions::FormatException(None))
}},
}
}
if !(bits.available() > 0) {
if bits.available() == 0 {
break;
}
} //while (bits.available() > 0);
@@ -296,9 +294,10 @@ fn decodeC40Segment(
parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues);
for i in 0..3 {
for cValue in cValues {
// for i in 0..3 {
// for (int i = 0; i < 3; i++) {
let cValue = cValues[i];
// let cValue = cValues[i];
match shift {
0 => {
if cValue < 3 {
@@ -312,15 +311,15 @@ fn decodeC40Segment(
result.append_char(c40char);
}
} else {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
}
1 => {
if upperShift {
result.append_char(char::from_u32((cValue + 128) as u32).unwrap());
result.append_char(char::from_u32(cValue + 128).unwrap());
upperShift = false;
} else {
result.append_char(char::from_u32(cValue as u32).unwrap());
result.append_char(char::from_u32(cValue).unwrap());
}
shift = 0;
}
@@ -346,25 +345,25 @@ fn decodeC40Segment(
upperShift = true
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
shift = 0;
}
3 => {
if upperShift {
result.append_char(char::from_u32(cValue as u32 + 224).unwrap());
result.append_char(char::from_u32(cValue + 224).unwrap());
upperShift = false;
} else {
result.append_char(char::from_u32(cValue as u32 + 96).unwrap());
result.append_char(char::from_u32(cValue + 96).unwrap());
}
shift = 0;
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
if !(bits.available() > 0) {
if bits.available() == 0 {
break;
}
} //while (bits.available() > 0);
@@ -409,14 +408,13 @@ fn decodeTextSegment(
} else if cValue < TEXT_BASIC_SET_CHARS.len() as u32 {
let textChar = TEXT_BASIC_SET_CHARS[cValue as usize];
if upperShift {
result
.append_char(char::from_u32(textChar as u32 + 128 as u32).unwrap());
result.append_char(char::from_u32(textChar as u32 + 128_u32).unwrap());
upperShift = false;
} else {
result.append_char(textChar);
}
} else {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
}
1 => {
@@ -452,7 +450,7 @@ fn decodeTextSegment(
upperShift = true
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
shift = 0;
@@ -468,14 +466,14 @@ fn decodeTextSegment(
}
shift = 0;
} else {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
}
_ => return Err(Exceptions::FormatException("".to_owned())),
_ => return Err(Exceptions::FormatException(None)),
}
}
if !(bits.available() > 0) {
if bits.available() == 0 {
break;
}
} //while (bits.available() > 0);
@@ -543,12 +541,12 @@ fn decodeAnsiX12Segment(
// A - Z
result.append_char(char::from_u32(cValue + 51).unwrap());
} else {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
}
}
}
if !(bits.available() > 0) {
if bits.available() == 0 {
break;
}
} //while (bits.available() > 0);
@@ -601,7 +599,7 @@ fn decodeEdifactSegment(
result.append_char(char::from_u32(edifactValue).unwrap());
}
if !(bits.available() > 0) {
if bits.available() == 0 {
break;
}
}
@@ -635,18 +633,19 @@ fn decodeBase256Segment(
// We're seeing NegativeArraySizeException errors from users.
// but we shouldn't in rust because it's unsigned
// if count < 0 {
// return Err(Exceptions::FormatException("".to_owned()));
// return Err(Exceptions::FormatException(None));
// }
let mut bytes = vec![0u8; count as usize];
for i in 0..count as usize {
for byte in bytes.iter_mut().take(count as usize) {
// for i in 0..count as usize {
// for (int i = 0; i < count; i++) {
// 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::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
bytes[i] = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
*byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
codewordPosition += 1;
}
result.append_string(
@@ -665,7 +664,7 @@ fn decodeBase256Segment(
*/
fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<(), Exceptions> {
if bits.available() < 8 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
let c1 = bits.readBits(8)?;
if c1 <= 127 {

View File

@@ -50,7 +50,7 @@ impl Decoder {
* @throws ChecksumException if error correction fails
*/
pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> {
self.decode(&BitMatrix::parse_bools(&image))
self.decode(&BitMatrix::parse_bools(image))
}
/**
@@ -72,7 +72,7 @@ impl Decoder {
let version = parser.getVersion();
// Separate into data blocks
let dataBlocks = DataBlock::getDataBlocks(&codewords, &version)?;
let dataBlocks = DataBlock::getDataBlocks(&codewords, version)?;
// Count total number of data bytes
let mut totalBytes = 0;
@@ -140,3 +140,9 @@ impl Decoder {
Ok(())
}
}
impl Default for Decoder {
fn default() -> Self {
Self::new()
}
}

View File

@@ -111,7 +111,7 @@ impl Version {
numColumns: u32,
) -> Result<&'static Version, Exceptions> {
if (numRows & 0x01) != 0 || (numColumns & 0x01) != 0 {
return Err(Exceptions::FormatException("".to_owned()));
return Err(Exceptions::FormatException(None));
}
for version in VERSIONS.iter() {
@@ -120,7 +120,7 @@ impl Version {
}
}
Err(Exceptions::FormatException("".to_owned()))
Err(Exceptions::FormatException(None))
}
/**

View File

@@ -53,7 +53,9 @@ impl<'a> Detector<'_> {
if let Some(point) = self.correctTopRight(&points) {
points[3] = point;
} else {
return Err(Exceptions::NotFoundException("point 4 unfound".to_owned()));
return Err(Exceptions::NotFoundException(Some(
"point 4 unfound".to_owned(),
)));
}
// points[3] = self.correctTopRight(&points);
// if points[3] == null {
@@ -82,7 +84,7 @@ impl<'a> Detector<'_> {
}
let bits = Self::sampleGrid(
&self.image,
self.image,
&topLeft,
&bottomLeft,
&bottomRight,
@@ -253,9 +255,9 @@ impl<'a> Detector<'_> {
+ self.transitionsBetween(&pointCs, &candidate2);
if sumc1 > sumc2 {
return Some(candidate1);
Some(candidate1)
} else {
return Some(candidate2);
Some(candidate2)
}
}
@@ -315,10 +317,10 @@ impl<'a> Detector<'_> {
}
fn isValid(&self, p: &RXingResultPoint) -> bool {
return p.getX() >= 0.0
p.getX() >= 0.0
&& p.getX() <= self.image.getWidth() as f32 - 1.0
&& p.getY() > 0.0
&& p.getY() <= self.image.getHeight() as f32 - 1.0;
&& p.getY() <= self.image.getHeight() as f32 - 1.0
}
fn sampleGrid(
@@ -332,7 +334,7 @@ impl<'a> Detector<'_> {
) -> Result<BitMatrix, Exceptions> {
let sampler = DefaultGridSampler {};
return sampler.sample_grid_detailed(
sampler.sample_grid_detailed(
image,
dimensionX,
dimensionY,
@@ -352,7 +354,7 @@ impl<'a> Detector<'_> {
bottomRight.getY(),
bottomLeft.getX(),
bottomLeft.getY(),
);
)
}
/**
@@ -404,6 +406,6 @@ impl<'a> Detector<'_> {
x += xstep;
}
return transitions;
transitions
}
}

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()
}
}