datamatrix decoder (few tests)

This commit is contained in:
Henry Schimke
2022-11-22 07:22:46 -06:00
parent 8573212ef6
commit 325fdcfda0
7 changed files with 752 additions and 629 deletions

View File

@@ -166,6 +166,12 @@ impl ECIStringBuilder {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
return self.current_bytes.is_empty() && self.result.is_empty(); return self.current_bytes.is_empty() && self.result.is_empty();
} }
pub fn build_result(mut self) -> Self {
self.encodeCurrentBytesIfAny();
self
}
} }
impl fmt::Display for ECIStringBuilder { impl fmt::Display for ECIStringBuilder {

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.datamatrix.decoder;
import org.junit.Assert;
import org.junit.Test;
/**
* @author bbrown@google.com (Brian Brown)
*/
public final class DecodedBitStreamParserTestCase extends Assert {
@Test
public void testAsciiStandardDecode() throws Exception {
// ASCII characters 0-127 are encoded as the value + 1
byte[] bytes = {(byte) ('a' + 1), (byte) ('b' + 1), (byte) ('c' + 1),
(byte) ('A' + 1), (byte) ('B' + 1), (byte) ('C' + 1)};
String decodedString = DecodedBitStreamParser.decode(bytes).getText();
assertEquals("abcABC", decodedString);
}
@Test
public void testAsciiDoubleDigitDecode() throws Exception {
// ASCII double digit (00 - 99) Numeric Value + 130
byte[] bytes = {(byte) 130 , (byte) (1 + 130),
(byte) (98 + 130), (byte) (99 + 130)};
String decodedString = DecodedBitStreamParser.decode(bytes).getText();
assertEquals("00019899", decodedString);
}
// TODO(bbrown): Add test cases for each encoding type
// TODO(bbrown): Add test cases for switching encoding types
}

View File

@@ -78,20 +78,20 @@ impl BitMatrixParser {
* @return bytes encoded within the Data Matrix Code * @return bytes encoded within the Data Matrix Code
* @throws FormatException if the exact number of bytes expected is not read * @throws FormatException if the exact number of bytes expected is not read
*/ */
pub fn readCodewords(&self) -> Result<Vec<u8>, Exceptions> { pub fn readCodewords(&mut self) -> Result<Vec<u8>, Exceptions> {
let result = vec![0u8; self.version.getTotalCodewords() as usize]; let mut result = vec![0u8; self.version.getTotalCodewords() as usize];
let resultOffset = 0; let mut resultOffset = 0;
let row = 4; let mut row = 4;
let column = 0_usize; let mut column = 0_usize;
let numRows = self.mappingBitMatrix.getHeight() as usize; let numRows = self.mappingBitMatrix.getHeight() as usize;
let numColumns = self.mappingBitMatrix.getWidth() as usize; let numColumns = self.mappingBitMatrix.getWidth() as usize;
let corner1Read = false; let mut corner1Read = false;
let corner2Read = false; let mut corner2Read = false;
let corner3Read = false; let mut corner3Read = false;
let corner4Read = false; let mut corner4Read = false;
// Read all of the codewords // Read all of the codewords
loop { loop {
@@ -193,7 +193,9 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return value of the given bit in the mapping matrix * @return value of the given bit in the mapping matrix
*/ */
fn readModule(&self, row: usize, column: usize, numRows: usize, numColumns: usize) -> bool { fn readModule(&mut self, row: usize, column: usize, numRows: usize, numColumns: usize) -> bool {
let mut row = row;
let mut column = column;
// Adjust the row and column indices based on boundary wrapping // Adjust the row and column indices based on boundary wrapping
if row < 0 { if row < 0 {
row += numRows; row += numRows;
@@ -222,7 +224,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return byte from the utah shape * @return byte from the utah shape
*/ */
fn readUtah(&self, row: usize, column: usize, numRows: usize, numColumns: usize) -> u32 { fn readUtah(&mut self, row: usize, column: usize, numRows: usize, numColumns: usize) -> u32 {
let mut currentByte = 0; let mut currentByte = 0;
if self.readModule(row - 2, column - 2, numRows, numColumns) { if self.readModule(row - 2, column - 2, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
@@ -267,7 +269,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 1 * @return byte from the Corner condition 1
*/ */
fn readCorner1(&self, numRows: usize, numColumns: usize) -> u32 { fn readCorner1(&mut self, numRows: usize, numColumns: usize) -> u32 {
let mut currentByte = 0; let mut currentByte = 0;
if self.readModule(numRows - 1, 0, numRows, numColumns) { if self.readModule(numRows - 1, 0, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
@@ -312,7 +314,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 2 * @return byte from the Corner condition 2
*/ */
fn readCorner2(&self, numRows: usize, numColumns: usize) -> u32 { fn readCorner2(&mut self, numRows: usize, numColumns: usize) -> u32 {
let mut currentByte = 0; let mut currentByte = 0;
if self.readModule(numRows - 3, 0, numRows, numColumns) { if self.readModule(numRows - 3, 0, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
@@ -357,7 +359,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 3 * @return byte from the Corner condition 3
*/ */
fn readCorner3(&self, numRows: usize, numColumns: usize) -> u32 { fn readCorner3(&mut self, numRows: usize, numColumns: usize) -> u32 {
let mut currentByte = 0; let mut currentByte = 0;
if self.readModule(numRows - 1, 0, numRows, numColumns) { if self.readModule(numRows - 1, 0, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
@@ -402,7 +404,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix * @param numColumns Number of columns in the mapping matrix
* @return byte from the Corner condition 4 * @return byte from the Corner condition 4
*/ */
fn readCorner4(&self, numRows: usize, numColumns: usize) -> u32 { fn readCorner4(&mut self, numRows: usize, numColumns: usize) -> u32 {
let mut currentByte = 0; let mut currentByte = 0;
if self.readModule(numRows - 3, 0, numRows, numColumns) { if self.readModule(numRows - 3, 0, numRows, numColumns) {
currentByte |= 1; currentByte |= 1;
@@ -467,7 +469,8 @@ impl BitMatrixParser {
let sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; let sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
let sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; let sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
let bitMatrixWithoutAlignment = BitMatrix::new(sizeDataRegionColumn, sizeDataRegionRow)?; let mut bitMatrixWithoutAlignment =
BitMatrix::new(sizeDataRegionColumn, sizeDataRegionRow)?;
for dataRegionRow in 0..numDataRegionsRow { for dataRegionRow in 0..numDataRegionsRow {
// for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) { // for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
let dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; let dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;

View File

@@ -16,8 +16,10 @@
use encoding::Encoding; use encoding::Encoding;
use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult}}; use crate::{
common::{BitSource, DecoderRXingResult, ECIStringBuilder},
Exceptions,
};
/** /**
* <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes * <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes
@@ -38,7 +40,7 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
ANSIX12_ENCODE, ANSIX12_ENCODE,
EDIFACT_ENCODE, EDIFACT_ENCODE,
BASE256_ENCODE, BASE256_ENCODE,
ECI_ENCODE ECI_ENCODE,
} }
/** /**
@@ -46,346 +48,421 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
* The C40 Basic Character Set (*'s used for placeholders for the shift values) * The C40 Basic Character Set (*'s used for placeholders for the shift values)
*/ */
const C40_BASIC_SET_CHARS: [char; 40] = [ const C40_BASIC_SET_CHARS: [char; 40] = [
'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' 'Y', 'Z',
]; ];
const C40_SHIFT2_SET_CHARS: [char; 27] = [ const C40_SHIFT2_SET_CHARS: [char; 27] = [
'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=',
'/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' '>', '?', '@', '[', '\\', ']', '^', '_',
]; ];
/** /**
* See ISO 16022:2006, Annex C Table C.2 * See ISO 16022:2006, Annex C Table C.2
* The Text Basic Character Set (*'s used for placeholders for the shift values) * The Text Basic Character Set (*'s used for placeholders for the shift values)
*/ */
const TEXT_BASIC_SET_CHARS : [char;40]= const TEXT_BASIC_SET_CHARS: [char; 40] = [
['*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' 'y', 'z',
]; ];
// Shift 2 for Text is the same encoding as C40 // Shift 2 for Text is the same encoding as C40
const TEXT_SHIFT2_SET_CHARS: [char; 27] = C40_SHIFT2_SET_CHARS; const TEXT_SHIFT2_SET_CHARS: [char; 27] = C40_SHIFT2_SET_CHARS;
const TEXT_SHIFT3_SET_CHARS: [char; 32] = [ const TEXT_SHIFT3_SET_CHARS: [char; 32] = [
'`', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', '`',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127 as char 'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'{',
'|',
'}',
'~',
127 as char,
]; ];
pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(bytes: &[u8]) -> Result<DecoderRXingResult, Exceptions> {
let bits = BitSource::new(bytes); let mut bits = BitSource::new(bytes.to_vec());
let result = ECIStringBuilder::with_capacity(100); let mut result = ECIStringBuilder::with_capacity(100);
let resultTrailer = String::new(); let mut resultTrailer = String::new();
let byteSegments = Vec::new();//new ArrayList<>(1); let mut byteSegments = Vec::new(); //new ArrayList<>(1);
let mode = Mode::ASCII_ENCODE; let mut mode = Mode::ASCII_ENCODE;
// Could look directly at 'bytes', if we're sure of not having to account for multi byte values // Could look directly at 'bytes', if we're sure of not having to account for multi byte values
let fnc1Positions = Vec::new(); let mut fnc1Positions = Vec::new();
let symbologyModifier; let symbologyModifier;
let isECIencoded = false; let mut isECIencoded = false;
loop { loop {
if mode == Mode::ASCII_ENCODE { if mode == Mode::ASCII_ENCODE {
mode = decodeAsciiSegment(bits, result, resultTrailer, fnc1Positions); mode = decodeAsciiSegment(
&mut bits,
&mut result,
&mut resultTrailer,
&mut fnc1Positions,
)?;
} else { } else {
match mode { match mode {
Mode::C40_ENCODE=> Mode::C40_ENCODE => decodeC40Segment(&mut bits, &mut result, &mut fnc1Positions)?,
decodeC40Segment(bits, result, fnc1Positions), Mode::TEXT_ENCODE => decodeTextSegment(&mut bits, &mut result, &mut fnc1Positions)?,
Mode::TEXT_ENCODE=> Mode::ANSIX12_ENCODE => decodeAnsiX12Segment(&mut bits, &mut result)?,
decodeTextSegment(bits, result, fnc1Positions), Mode::EDIFACT_ENCODE => decodeEdifactSegment(&mut bits, &mut result)?,
Mode::ANSIX12_ENCODE=> Mode::BASE256_ENCODE => {
decodeAnsiX12Segment(bits, result), decodeBase256Segment(&mut bits, &mut result, &mut byteSegments)?
Mode::EDIFACT_ENCODE=>
decodeEdifactSegment(bits, result),
Mode::BASE256_ENCODE=>
decodeBase256Segment(bits, result, byteSegments),
Mode::ECI_ENCODE=>{
decodeECISegment(bits, result);
isECIencoded = true; // ECI detection only, atm continue decoding as ASCII
},
_=>
return Err(Exceptions::FormatException("".to_owned())),
} }
Mode::ECI_ENCODE => {
decodeECISegment(&mut bits, &mut result)?;
isECIencoded = true; // ECI detection only, atm continue decoding as ASCII
}
_ => return Err(Exceptions::FormatException("".to_owned())),
};
mode = Mode::ASCII_ENCODE; mode = Mode::ASCII_ENCODE;
} }
if ! (mode != Mode::PAD_ENCODE && bits.available() > 0) { break } if !(mode != Mode::PAD_ENCODE && bits.available() > 0) {
} //while (mode != Mode.PAD_ENCODE && bits.available() > 0); break;
if (resultTrailer.length() > 0) {
result.appendCharacters(resultTrailer);
} }
if (isECIencoded) { } //while (mode != Mode.PAD_ENCODE && bits.available() > 0);
if resultTrailer.len() > 0 {
result.appendCharacters(&resultTrailer);
}
if isECIencoded {
// Examples for this numbers can be found in this documentation of a hardware barcode scanner: // Examples for this numbers can be found in this documentation of a hardware barcode scanner:
// https://honeywellaidc.force.com/supportppr/s/article/List-of-barcode-symbology-AIM-Identifiers // https://honeywellaidc.force.com/supportppr/s/article/List-of-barcode-symbology-AIM-Identifiers
if (fnc1Positions.contains(0) || fnc1Positions.contains(4)) { if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
symbologyModifier = 5; symbologyModifier = 5;
} else if (fnc1Positions.contains(1) || fnc1Positions.contains(5)) { } else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) {
symbologyModifier = 6; symbologyModifier = 6;
} else { } else {
symbologyModifier = 4; symbologyModifier = 4;
} }
} else { } else {
if (fnc1Positions.contains(0) || fnc1Positions.contains(4)) { if fnc1Positions.contains(&0) || fnc1Positions.contains(&4) {
symbologyModifier = 2; symbologyModifier = 2;
} else if (fnc1Positions.contains(1) || fnc1Positions.contains(5)) { } else if fnc1Positions.contains(&1) || fnc1Positions.contains(&5) {
symbologyModifier = 3; symbologyModifier = 3;
} else { } else {
symbologyModifier = 1; symbologyModifier = 1;
} }
} }
return new DecoderRXingResult(bytes, Ok(DecoderRXingResult::with_symbology(
result.toString(), bytes.to_vec(),
byteSegments.isEmpty() ? null : byteSegments, result.build_result().to_string(),
null, byteSegments,
symbologyModifier); String::new(),
symbologyModifier,
))
// return new DecoderRXingResult(bytes,
// result.toString(),
// byteSegments.isEmpty() ? null : byteSegments,
// null,
// symbologyModifier);
} }
/** /**
* See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
*/ */
fn decodeAsciiSegment( bits:&BitSource, fn decodeAsciiSegment(
result:&ECIStringBuilder, bits: &mut BitSource,
resultTrailer:&String, result: &mut ECIStringBuilder,
fnc1positions:&[usize]) -> Result<Mode,Exceptions> { resultTrailer: &mut String,
boolean upperShift = false; fnc1positions: &mut Vec<usize>,
do { ) -> Result<Mode, Exceptions> {
int oneByte = bits.readBits(8); let mut upperShift = false;
if (oneByte == 0) { loop {
throw FormatException.getFormatInstance(); let mut oneByte = bits.readBits(8)?;
} else if (oneByte <= 128) { // ASCII data (ASCII value + 1) if oneByte == 0 {
if (upperShift) { return Err(Exceptions::FormatException("".to_owned()));
} else if oneByte <= 128 {
// ASCII data (ASCII value + 1)
if upperShift {
oneByte += 128; oneByte += 128;
//upperShift = false; //upperShift = false;
} }
result.append((char) (oneByte - 1)); result.append_char(char::from_u32(oneByte - 1).unwrap());
return Mode.ASCII_ENCODE; return Ok(Mode::ASCII_ENCODE);
} else if (oneByte == 129) { // Pad } else if oneByte == 129 {
return Mode.PAD_ENCODE; // Pad
} else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) return Ok(Mode::PAD_ENCODE);
int value = oneByte - 130; } else if oneByte <= 229 {
if (value < 10) { // pad with '0' for single digit values // 2-digit data 00-99 (Numeric Value + 130)
result.append('0'); let value = oneByte - 130;
if value < 10 {
// pad with '0' for single digit values
result.append_char('0');
} }
result.append(value); //result.append_char(char::from_u32(value).unwrap());
result.append_string(&format!("{}", value));
} else { } else {
switch (oneByte) { match oneByte {
case 230: // Latch to C40 encodation 230=> // Latch to C40 encodation
return Mode.C40_ENCODE; return Ok(Mode::C40_ENCODE),
case 231: // Latch to Base 256 encodation 231=> // Latch to Base 256 encodation
return Mode.BASE256_ENCODE; return Ok(Mode::BASE256_ENCODE),
case 232: // FNC1 232=> {// FNC1
fnc1positions.add(result.length()); fnc1positions.push(result.len());
result.append((char) 29); // translate as ASCII 29 result.append_char( 29 as char); // translate as ASCII 29
break; },
case 233: // Structured Append 233| // Structured Append
case 234: // Reader Programming 234=> // Reader Programming
// Ignore these symbols for now // Ignore these symbols for now
//throw ReaderException.getInstance(); //throw ReaderException.getInstance();
break; {},
case 235: // Upper Shift (shift to Extended ASCII) 235=> // Upper Shift (shift to Extended ASCII)
upperShift = true; upperShift = true,
break;
case 236: // 05 Macro 236=> {// 05 Macro
result.append("[)>\u001E05\u001D"); result.append_string("[)>\u{001E}05\u{001D}");
resultTrailer.insert(0, "\u001E\u0004"); resultTrailer.replace_range(0..0, "\u{001E}\u{0004}");
break; // resultTrailer.insert(0, "\u{001E}\u{0004}");
case 237: // 06 Macro },
result.append("[)>\u001E06\u001D"); 237=>{ // 06 Macro
resultTrailer.insert(0, "\u001E\u0004"); result.append_string("[)>\u{001E}06\u{001D}");
break; resultTrailer.replace_range(0..0, "\u{001E}\u{0004}");
case 238: // Latch to ANSI X12 encodation // resultTrailer.insert(0, "\u{001E}\u{0004}");
return Mode.ANSIX12_ENCODE; },
case 239: // Latch to Text encodation 238=> // Latch to ANSI X12 encodation
return Mode.TEXT_ENCODE; return Ok(Mode::ANSIX12_ENCODE),
case 240: // Latch to EDIFACT encodation 239=> // Latch to Text encodation
return Mode.EDIFACT_ENCODE; return Ok(Mode::TEXT_ENCODE),
case 241: // ECI Character 240=> // Latch to EDIFACT encodation
return Mode.ECI_ENCODE; return Ok(Mode::EDIFACT_ENCODE),
default: 241=> // ECI Character
return Ok(Mode::ECI_ENCODE),
_=>{
// Not to be used in ASCII encodation // Not to be used in ASCII encodation
// but work around encoders that end with 254, latch back to ASCII // but work around encoders that end with 254, latch back to ASCII
if (oneByte != 254 || bits.available() != 0) { if oneByte != 254 || bits.available() != 0 {
throw FormatException.getFormatInstance(); return Err(Exceptions::FormatException("".to_owned()))
}},
} }
}
if !(bits.available() > 0) {
break; break;
} }
} } //while (bits.available() > 0);
} while (bits.available() > 0); Ok(Mode::ASCII_ENCODE)
return Mode.ASCII_ENCODE;
} }
/** /**
* See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1
*/ */
fn decodeC40Segment( bits:&BitSource, result:&ECIStringBuilder, fnc1positions:&[usize]) fn decodeC40Segment(
-> Result<(),Exceptions> { bits: &mut BitSource,
result: &mut ECIStringBuilder,
fnc1positions: &mut Vec<usize>,
) -> Result<(), Exceptions> {
// Three C40 values are encoded in a 16-bit value as // Three C40 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
boolean upperShift = false; let mut upperShift = false;
int[] cValues = new int[3]; let mut cValues = [0; 3];
int shift = 0; let mut shift = 0;
do { loop {
// If there is only one byte left then it will be encoded as ASCII // If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8) { if bits.available() == 8 {
return; return Ok(());
} }
int firstByte = bits.readBits(8); let firstByte = bits.readBits(8)?;
if (firstByte == 254) { // Unlatch codeword if firstByte == 254 {
return; // Unlatch codeword
return Ok(());
} }
parseTwoBytes(firstByte, bits.readBits(8), cValues); parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues);
for (int i = 0; i < 3; i++) { for i in 0..3 {
int cValue = cValues[i]; // for (int i = 0; i < 3; i++) {
switch (shift) { let cValue = cValues[i];
case 0: match shift {
if (cValue < 3) { 0 => {
if cValue < 3 {
shift = cValue + 1; shift = cValue + 1;
} else if (cValue < C40_BASIC_SET_CHARS.length) { } else if cValue < C40_BASIC_SET_CHARS.len() as u32 {
char c40char = C40_BASIC_SET_CHARS[cValue]; let c40char = C40_BASIC_SET_CHARS[cValue as usize];
if (upperShift) { if upperShift {
result.append((char) (c40char + 128)); result.append_char(char::from_u32(c40char as u32 + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append(c40char); result.append_char(c40char);
} }
} else { } else {
throw FormatException.getFormatInstance(); return Err(Exceptions::FormatException("".to_owned()));
} }
break; }
case 1: 1 => {
if (upperShift) { if upperShift {
result.append((char) (cValue + 128)); result.append_char(char::from_u32((cValue + 128) as u32).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append((char) cValue); result.append_char(char::from_u32(cValue as u32).unwrap());
} }
shift = 0; shift = 0;
break; }
case 2: 2 => {
if (cValue < C40_SHIFT2_SET_CHARS.length) { if cValue < C40_SHIFT2_SET_CHARS.len() as u32 {
char c40char = C40_SHIFT2_SET_CHARS[cValue]; let c40char = C40_SHIFT2_SET_CHARS[cValue as usize];
if (upperShift) { if upperShift {
result.append((char) (c40char + 128)); result.append_char(char::from_u32(c40char as u32 + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append(c40char); result.append_char(c40char);
} }
} else { } else {
switch (cValue) { match cValue {
case 27: // FNC1 27 => {
fnc1positions.add(result.length()); // FNC1
result.append((char) 29); // translate as ASCII 29 fnc1positions.push(result.len());
break; result.append_char(29 as char); // translate as ASCII 29
case 30: // Upper Shift }
upperShift = true; 30 =>
break; // Upper Shift
default: {
throw FormatException.getFormatInstance(); upperShift = true
}
_ => return Err(Exceptions::FormatException("".to_owned())),
} }
} }
shift = 0; shift = 0;
break; }
case 3: 3 => {
if (upperShift) { if upperShift {
result.append((char) (cValue + 224)); result.append_char(char::from_u32(cValue as u32 + 224).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append((char) (cValue + 96)); result.append_char(char::from_u32(cValue as u32 + 96).unwrap());
} }
shift = 0; shift = 0;
}
_ => return Err(Exceptions::FormatException("".to_owned())),
}
}
if !(bits.available() > 0) {
break; break;
default:
throw FormatException.getFormatInstance();
} }
} } //while (bits.available() > 0);
} while (bits.available() > 0); Ok(())
} }
/** /**
* See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2
*/ */
fn decodeTextSegment( bits:&BitSource, result:&ECIStringBuilder, fnc1positions:&[usize]) fn decodeTextSegment(
-> Result<(),Exceptions> { bits: &mut BitSource,
result: &mut ECIStringBuilder,
fnc1positions: &mut Vec<usize>,
) -> Result<(), Exceptions> {
// Three Text values are encoded in a 16-bit value as // Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
let upperShift = false; let mut upperShift = false;
let cValues = [0;3];//new int[3]; let mut cValues = [0; 3]; //new int[3];
let shift = 0; let mut shift = 0;
loop { loop {
// If there is only one byte left then it will be encoded as ASCII // If there is only one byte left then it will be encoded as ASCII
if bits.available() == 8 { if bits.available() == 8 {
return Ok(()) return Ok(());
} }
let firstByte = bits.readBits(8)?; let firstByte = bits.readBits(8)?;
if firstByte == 254 { // Unlatch codeword if firstByte == 254 {
return Ok(()) // Unlatch codeword
return Ok(());
} }
parseTwoBytes(firstByte, bits.readBits(8)?, &cValues); parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues);
for cValue in cValues { for cValue in cValues {
// for (int i = 0; i < 3; i++) { // for (int i = 0; i < 3; i++) {
// int cValue = cValues[i]; // int cValue = cValues[i];
match shift { match shift {
0=> 0 => {
if cValue < 3 { if cValue < 3 {
shift = cValue + 1; shift = cValue + 1;
} else if cValue < TEXT_BASIC_SET_CHARS.len() { } else if cValue < TEXT_BASIC_SET_CHARS.len() as u32 {
let textChar = TEXT_BASIC_SET_CHARS[cValue]; let textChar = TEXT_BASIC_SET_CHARS[cValue as usize];
if upperShift { if upperShift {
result.append_char( (textChar + 128)); result
.append_char(char::from_u32(textChar as u32 + 128 as u32).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append(textChar); result.append_char(textChar);
} }
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException("".to_owned()));
}, }
1=> }
{if upperShift { 1 => {
result.append_char( (cValue + 128)); if upperShift {
result.append_char(char::from_u32(cValue + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char( cValue); result.append_char(char::from_u32(cValue).unwrap());
}
shift = 0;
} }
shift = 0;},
2=> 2 => {
{// Shift 2 for Text is the same encoding as C40 // Shift 2 for Text is the same encoding as C40
if cValue < TEXT_SHIFT2_SET_CHARS.len() { if cValue < TEXT_SHIFT2_SET_CHARS.len() as u32 {
let textChar = TEXT_SHIFT2_SET_CHARS[cValue]; let textChar = TEXT_SHIFT2_SET_CHARS[cValue as usize];
if upperShift { if upperShift {
result.append_char( (textChar + 128)); result.append_char(char::from_u32(textChar as u32 + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char(textChar); result.append_char(textChar);
} }
} else { } else {
match cValue { match cValue {
27=>{ // FNC1 27 => {
fnc1positions.push(result.length()); // FNC1
result.append_char( 29); // translate as ASCII 29 fnc1positions.push(result.len());
}, result.append_char(29 as char); // translate as ASCII 29
30=> // Upper Shift }
upperShift = true, 30 =>
// Upper Shift
{
upperShift = true
}
_=> _ => return Err(Exceptions::FormatException("".to_owned())),
return Err(Exceptions::FormatException("".to_owned())),
} }
} }
shift = 0;}, shift = 0;
3=> }
if cValue < TEXT_SHIFT3_SET_CHARS.len() { 3 => {
let textChar = TEXT_SHIFT3_SET_CHARS[cValue]; if cValue < TEXT_SHIFT3_SET_CHARS.len() as u32 {
let textChar = TEXT_SHIFT3_SET_CHARS[cValue as usize];
if upperShift { if upperShift {
result.append_char( (textChar + 128)); result.append_char(char::from_u32(textChar as u32 + 128).unwrap());
upperShift = false; upperShift = false;
} else { } else {
result.append_char(textChar); result.append_char(textChar);
@@ -393,13 +470,15 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
shift = 0; shift = 0;
} else { } else {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException("".to_owned()));
}, }
}
_=> _ => return Err(Exceptions::FormatException("".to_owned())),
return Err(Exceptions::FormatException("".to_owned())),
} }
} }
if !(bits.available() > 0){break} if !(bits.available() > 0) {
break;
}
} //while (bits.available() > 0); } //while (bits.available() > 0);
Ok(()) Ok(())
@@ -408,59 +487,79 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
/** /**
* See ISO 16022:2006, 5.2.7 * See ISO 16022:2006, 5.2.7
*/ */
fn decodeAnsiX12Segment( bits:&BitSource, fn decodeAnsiX12Segment(
result:&ECIStringBuilder) -> Result<(),Exceptions> { bits: &mut BitSource,
result: &mut ECIStringBuilder,
) -> Result<(), Exceptions> {
// Three ANSI X12 values are encoded in a 16-bit value as // Three ANSI X12 values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1 // (1600 * C1) + (40 * C2) + C3 + 1
let cValues = [0;3];//new int[3]; let mut cValues = [0; 3]; //new int[3];
loop { loop {
// If there is only one byte left then it will be encoded as ASCII // If there is only one byte left then it will be encoded as ASCII
if bits.available() == 8 { if bits.available() == 8 {
return Ok(()) return Ok(());
} }
let firstByte = bits.readBits(8)?; let firstByte = bits.readBits(8)?;
if firstByte == 254 { // Unlatch codeword if firstByte == 254 {
return Ok(()) // Unlatch codeword
return Ok(());
} }
parseTwoBytes(firstByte, bits.readBits(8)?, &cValues); parseTwoBytes(firstByte, bits.readBits(8)?, &mut cValues);
for cValue in cValues { for cValue in cValues {
// for (int i = 0; i < 3; i++) { // for (int i = 0; i < 3; i++) {
// int cValue = cValues[i]; // int cValue = cValues[i];
match cValue { match cValue {
0=> // X12 segment terminator <CR> 0 =>
result.append_char('\r'), // X12 segment terminator <CR>
{
result.append_char('\r')
}
1=> // X12 segment separator * 1 =>
result.append_char('*'), // X12 segment separator *
{
result.append_char('*')
}
2=> // X12 sub-element separator > 2 =>
result.append_char('>'), // X12 sub-element separator >
{
result.append_char('>')
}
3=> // space 3 =>
result.append_char(' '), // space
{
result.append_char(' ')
}
_=> _ => {
if cValue < 14 { // 0 - 9 if cValue < 14 {
// 0 - 9
result.append_char(char::from_u32(cValue + 44).unwrap()); result.append_char(char::from_u32(cValue + 44).unwrap());
} else if cValue < 40 { // A - Z } else if cValue < 40 {
// A - Z
result.append_char(char::from_u32(cValue + 51).unwrap()); result.append_char(char::from_u32(cValue + 51).unwrap());
} else { } else {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException("".to_owned()));
},
} }
} }
if ! (bits.available() > 0) { break } }
}
if !(bits.available() > 0) {
break;
}
} //while (bits.available() > 0); } //while (bits.available() > 0);
Ok(()) Ok(())
} }
fn parseTwoBytes( firstByte:u32, secondByte:u32, result:&[u32]) { fn parseTwoBytes(firstByte: u32, secondByte: u32, result: &mut [u32]) {
let fullBitValue = (firstByte << 8) + secondByte - 1; let mut fullBitValue = (firstByte << 8) + secondByte - 1;
let temp = fullBitValue / 1600; let mut temp = fullBitValue / 1600;
result[0] = temp; result[0] = temp;
fullBitValue -= temp * 1600; fullBitValue -= temp * 1600;
temp = fullBitValue / 40; temp = fullBitValue / 40;
@@ -471,19 +570,23 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
/** /**
* See ISO 16022:2006, 5.2.8 and Annex C Table C.3 * See ISO 16022:2006, 5.2.8 and Annex C Table C.3
*/ */
fn decodeEdifactSegment( bits:&BitSource, result:&ECIStringBuilder) -> Result<(),Exceptions>{ fn decodeEdifactSegment(
bits: &mut BitSource,
result: &mut ECIStringBuilder,
) -> Result<(), Exceptions> {
loop { loop {
// If there is only two or less bytes left then it will be encoded as ASCII // If there is only two or less bytes left then it will be encoded as ASCII
if bits.available() <= 16 { if bits.available() <= 16 {
return Ok(()); return Ok(());
} }
for i in 0..4 { for _i in 0..4 {
// for (int i = 0; i < 4; i++) { // for (int i = 0; i < 4; i++) {
let edifactValue = bits.readBits(6)?; let mut edifactValue = bits.readBits(6)?;
// Check for the unlatch character // Check for the unlatch character
if edifactValue == 0x1F { // 011111 if edifactValue == 0x1F {
// 011111
// Read rest of byte, which should be 0, and stop // Read rest of byte, which should be 0, and stop
let bitsLeft = 8 - bits.getBitOffset(); let bitsLeft = 8 - bits.getBitOffset();
if bitsLeft != 8 { if bitsLeft != 8 {
@@ -492,13 +595,16 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
return Ok(()); return Ok(());
} }
if (edifactValue & 0x20) == 0 { // no 1 in the leading (6th) bit if (edifactValue & 0x20) == 0 {
// no 1 in the leading (6th) bit
edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value
} }
result.append_char(char::from_u32(edifactValue).unwrap()); result.append_char(char::from_u32(edifactValue).unwrap());
} }
if ! (bits.available() > 0) { break } if !(bits.available() > 0) {
break;
}
} }
Ok(()) Ok(())
@@ -507,16 +613,18 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
/** /**
* See ISO 16022:2006, 5.2.9 and Annex B, B.2 * See ISO 16022:2006, 5.2.9 and Annex B, B.2
*/ */
fn decodeBase256Segment( bits:&BitSource, fn decodeBase256Segment(
result:&ECIStringBuilder, bits: &mut BitSource,
byteSegments:&Vec<Vec<u8>>) result: &mut ECIStringBuilder,
-> Result<(),Exceptions> { byteSegments: &mut Vec<Vec<u8>>,
) -> Result<(), Exceptions> {
// Figure out how long the Base 256 Segment is. // Figure out how long the Base 256 Segment is.
let codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed let mut codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed
let d1 = unrandomize255State(bits.readBits(8)?, codewordPosition); let d1 = unrandomize255State(bits.readBits(8)?, codewordPosition);
codewordPosition += 1; codewordPosition += 1;
let count; let count;
if d1 == 0 { // Read the remainder of the symbol if d1 == 0 {
// Read the remainder of the symbol
count = bits.available() as u32 / 8; count = bits.available() as u32 / 8;
} else if d1 < 250 { } else if d1 < 250 {
count = d1; count = d1;
@@ -526,23 +634,28 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
} }
// We're seeing NegativeArraySizeException errors from users. // We're seeing NegativeArraySizeException errors from users.
if (count < 0) { if count < 0 {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException("".to_owned()));
} }
let bytes = vec![0u8;count as usize]; let mut bytes = vec![0u8; count as usize];
for i in 0..count as usize { for i in 0..count as usize {
// for (int i = 0; i < count; i++) { // for (int i = 0; i < count; i++) {
// Have seen this particular error in the wild, such as at // 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 // 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 { if bits.available() < 8 {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException("".to_owned()));
} }
bytes[i] = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; bytes[i] = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
codewordPosition += 1; codewordPosition += 1;
} }
result.append_string(
&encoding::all::ISO_8859_1
.decode(&bytes, encoding::DecoderTrap::Strict)
.expect("decode"),
);
byteSegments.push(bytes); byteSegments.push(bytes);
result.append_string(&encoding::all::ISO_8859_1.decode(&bytes, encoding::DecoderTrap::Strict).expect("decode")); // result.append_string(&encoding::all::ISO_8859_1.decode(&bytes, encoding::DecoderTrap::Strict).expect("decode"));
Ok(()) Ok(())
} }
@@ -550,11 +663,9 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
/** /**
* See ISO 16022:2007, 5.4.1 * See ISO 16022:2007, 5.4.1
*/ */
fn decodeECISegment( bits:&BitSource, fn decodeECISegment(bits: &mut BitSource, result: &mut ECIStringBuilder) -> Result<(), Exceptions> {
result:&ECIStringBuilder)
-> Result<(),Exceptions> {
if bits.available() < 8 { if bits.available() < 8 {
return Err(Exceptions::FormatException("".to_owned())) return Err(Exceptions::FormatException("".to_owned()));
} }
let c1 = bits.readBits(8)?; let c1 = bits.readBits(8)?;
if c1 <= 127 { if c1 <= 127 {
@@ -578,15 +689,55 @@ use crate::{Exceptions, common::{BitSource, ECIStringBuilder, DecoderRXingResult
}*/ }*/
} }
/** /**
* See ISO 16022:2006, Annex B, B.2 * See ISO 16022:2006, Annex B, B.2
*/ */
fn unrandomize255State( randomizedBase256Codeword:u32, fn unrandomize255State(randomizedBase256Codeword: u32, base256CodewordPosition: usize) -> u32 {
base256CodewordPosition:usize) -> u32{
let pseudoRandomNumber = ((149 * base256CodewordPosition as u32) % 255) + 1; let pseudoRandomNumber = ((149 * base256CodewordPosition as u32) % 255) + 1;
let tempVariable = randomizedBase256Codeword - pseudoRandomNumber; let tempVariable = randomizedBase256Codeword - pseudoRandomNumber;
if tempVariable >= 0 {tempVariable} else {tempVariable + 256} if tempVariable >= 0 {
tempVariable
} else {
tempVariable + 256
}
} }
#[cfg(test)]
mod tests {
use crate::datamatrix::decoder::decoded_bit_stream_parser;
#[test]
fn testAsciiStandardDecode() {
// ASCII characters 0-127 are encoded as the value + 1
let bytes = [
(b'a' + 1),
(b'b' + 1),
(b'c' + 1),
(b'A' + 1),
(b'B' + 1),
(b'C' + 1),
];
let decodedString = String::from(
decoded_bit_stream_parser::decode(&bytes)
.expect("decode")
.getText(),
);
assert_eq!("abcABC", decodedString);
}
#[test]
fn testAsciiDoubleDigitDecode() {
// ASCII double digit (00 - 99) Numeric Value + 130
let bytes = [130, (1 + 130), (98 + 130), (99 + 130)];
let decodedString = String::from(
decoded_bit_stream_parser::decode(&bytes)
.expect("decode")
.getText(),
);
assert_eq!("00019899", decodedString);
}
// TODO(bbrown): Add test cases for each encoding type
// TODO(bbrown): Add test cases for switching encoding types
}

View File

@@ -14,10 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{common::{reedsolomon::{ReedSolomonDecoder, get_predefined_genericgf, PredefinedGenericGF}, DecoderRXingResult, BitMatrix}, Exceptions}; use crate::{
common::{
use super::{DataBlock, BitMatrixParser, decoded_bit_stream_parser}; reedsolomon::{get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder},
BitMatrix, DecoderRXingResult,
},
Exceptions,
};
use super::{decoded_bit_stream_parser, BitMatrixParser, DataBlock};
/** /**
* <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting * <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting
@@ -28,10 +33,10 @@ use super::{DataBlock, BitMatrixParser, decoded_bit_stream_parser};
pub struct Decoder(ReedSolomonDecoder); pub struct Decoder(ReedSolomonDecoder);
impl Decoder { impl Decoder {
pub fn new() -> Self { pub fn new() -> Self {
Self(ReedSolomonDecoder::new(get_predefined_genericgf(
Self(ReedSolomonDecoder::new(get_predefined_genericgf(PredefinedGenericGF::DataMatrixField256))) PredefinedGenericGF::DataMatrixField256,
)))
// rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256); // rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
} }
@@ -58,32 +63,32 @@ impl Decoder {
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
pub fn decode(&self, bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> { pub fn decode(&self, bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> {
// Construct a parser and read version, error-correction level // Construct a parser and read version, error-correction level
let parser = BitMatrixParser::new(bits)?; let mut parser = BitMatrixParser::new(bits)?;
let version = parser.getVersion();
// Read codewords // Read codewords
let codewords = parser.readCodewords()?; let codewords = parser.readCodewords()?;
let version = parser.getVersion();
// Separate into data blocks // Separate into data blocks
let dataBlocks = DataBlock::getDataBlocks(&codewords, version)?; let dataBlocks = DataBlock::getDataBlocks(&codewords, &version)?;
// Count total number of data bytes // Count total number of data bytes
let totalBytes = 0; let mut totalBytes = 0;
for db in dataBlocks { for db in &dataBlocks {
totalBytes += db.getNumDataCodewords(); totalBytes += db.getNumDataCodewords();
} }
let resultBytes = vec![0u8;totalBytes as usize]; let mut resultBytes = vec![0u8; totalBytes as usize];
let dataBlocksCount = dataBlocks.len(); let dataBlocksCount = dataBlocks.len();
// Error-correct and copy data blocks together into a stream of bytes // Error-correct and copy data blocks together into a stream of bytes
for j in 0..dataBlocksCount { for j in 0..dataBlocksCount {
// for (int j = 0; j < dataBlocksCount; j++) { // for (int j = 0; j < dataBlocksCount; j++) {
let dataBlock = dataBlocks[j]; let dataBlock = &dataBlocks[j];
let codewordBytes = dataBlock.getCodewords(); let mut codewordBytes = dataBlock.getCodewords().to_vec();
let numDataCodewords = dataBlock.getNumDataCodewords() as usize; let numDataCodewords = dataBlock.getNumDataCodewords() as usize;
self.correctErrors(codewordBytes, numDataCodewords as u32); self.correctErrors(&mut codewordBytes, numDataCodewords as u32)?;
for i in 0..numDataCodewords { for i in 0..numDataCodewords {
// for (int i = 0; i < numDataCodewords; i++) { // for (int i = 0; i < numDataCodewords; i++) {
// De-interlace data blocks. // De-interlace data blocks.
@@ -103,18 +108,25 @@ impl Decoder {
* @param numDataCodewords number of codewords that are data bytes * @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails * @throws ChecksumException if error correction fails
*/ */
fn correctErrors(&self, codewordBytes:&[u8], numDataCodewords:u32) -> Result<(),Exceptions> { fn correctErrors(
let numCodewords = codewordBytes.len(); &self,
codewordBytes: &mut [u8],
numDataCodewords: u32,
) -> Result<(), Exceptions> {
let _numCodewords = codewordBytes.len();
// First read into an array of ints // First read into an array of ints
// let codewordsInts = vec![0i32;numCodewords]; // let codewordsInts = vec![0i32;numCodewords];
// for i in 0..numCodewords { // for i in 0..numCodewords {
// // for (int i = 0; i < numCodewords; i++) { // // for (int i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i]; // codewordsInts[i] = codewordBytes[i];
// } // }
let codewordsInts : Vec<i32> = codewordBytes.iter().map(|x| *x as i32).collect(); let mut codewordsInts: Vec<i32> = codewordBytes.iter().map(|x| *x as i32).collect();
//try { //try {
self.0.decode(&mut codewordsInts, codewordBytes.len() as i32- numDataCodewords as i32)?; self.0.decode(
&mut codewordsInts,
codewordBytes.len() as i32 - numDataCodewords as i32,
)?;
//} catch (ReedSolomonException ignored) { //} catch (ReedSolomonException ignored) {
//throw ChecksumException.getChecksumInstance(); //throw ChecksumException.getChecksumInstance();
//} //}
@@ -127,5 +139,4 @@ impl Decoder {
// codewordsInts.into_iter().take(numDataCodewords as usize).map(|x| x as u8).collect::<Vec<u8>>() // codewordsInts.into_iter().take(numDataCodewords as usize).map(|x| x as u8).collect::<Vec<u8>>()
Ok(()) Ok(())
} }
} }

View File

@@ -1,12 +1,11 @@
mod bit_matrix_parser;
mod version;
mod data_block; mod data_block;
mod decoder; mod decoder;
mod bit_matrix_parser; mod version;
pub use version::*; pub use bit_matrix_parser::*;
pub use data_block::*; pub use data_block::*;
pub use decoder::*; pub use decoder::*;
pub use bit_matrix_parser::*; pub use version::*;
pub mod decoded_bit_stream_parser; pub mod decoded_bit_stream_parser;

View File

@@ -132,7 +132,7 @@ impl EdifactEncoder {
} else if c >= '@' && c <= '^' { } else if c >= '@' && c <= '^' {
sb.push((c as u8 - 64) as char); sb.push((c as u8 - 64) as char);
} else { } else {
high_level_encoder::illegalCharacter(c); high_level_encoder::illegalCharacter(c).expect("");
} }
} }