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 {
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 {

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
* @throws FormatException if the exact number of bytes expected is not read
*/
pub fn readCodewords(&self) -> Result<Vec<u8>, Exceptions> {
let result = vec![0u8; self.version.getTotalCodewords() as usize];
let resultOffset = 0;
pub fn readCodewords(&mut self) -> Result<Vec<u8>, Exceptions> {
let mut result = vec![0u8; self.version.getTotalCodewords() as usize];
let mut resultOffset = 0;
let row = 4;
let column = 0_usize;
let mut row = 4;
let mut column = 0_usize;
let numRows = self.mappingBitMatrix.getHeight() as usize;
let numColumns = self.mappingBitMatrix.getWidth() as usize;
let corner1Read = false;
let corner2Read = false;
let corner3Read = false;
let corner4Read = false;
let mut corner1Read = false;
let mut corner2Read = false;
let mut corner3Read = false;
let mut corner4Read = false;
// Read all of the codewords
loop {
@@ -193,7 +193,9 @@ impl BitMatrixParser {
* @param numColumns Number of columns 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
if row < 0 {
row += numRows;
@@ -222,7 +224,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix
* @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;
if self.readModule(row - 2, column - 2, numRows, numColumns) {
currentByte |= 1;
@@ -267,7 +269,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix
* @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;
if self.readModule(numRows - 1, 0, numRows, numColumns) {
currentByte |= 1;
@@ -312,7 +314,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix
* @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;
if self.readModule(numRows - 3, 0, numRows, numColumns) {
currentByte |= 1;
@@ -357,7 +359,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix
* @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;
if self.readModule(numRows - 1, 0, numRows, numColumns) {
currentByte |= 1;
@@ -402,7 +404,7 @@ impl BitMatrixParser {
* @param numColumns Number of columns in the mapping matrix
* @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;
if self.readModule(numRows - 3, 0, numRows, numColumns) {
currentByte |= 1;
@@ -467,7 +469,8 @@ impl BitMatrixParser {
let sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
let sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
let bitMatrixWithoutAlignment = BitMatrix::new(sizeDataRegionColumn, sizeDataRegionRow)?;
let mut bitMatrixWithoutAlignment =
BitMatrix::new(sizeDataRegionColumn, sizeDataRegionRow)?;
for dataRegionRow in 0..numDataRegionsRow {
// for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
let dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;

File diff suppressed because it is too large Load Diff

View File

@@ -14,10 +14,15 @@
* limitations under the License.
*/
use crate::{common::{reedsolomon::{ReedSolomonDecoder, get_predefined_genericgf, PredefinedGenericGF}, DecoderRXingResult, BitMatrix}, Exceptions};
use super::{DataBlock, BitMatrixParser, decoded_bit_stream_parser};
use crate::{
common::{
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
@@ -28,104 +33,110 @@ use super::{DataBlock, BitMatrixParser, decoded_bit_stream_parser};
pub struct Decoder(ReedSolomonDecoder);
impl Decoder {
pub fn new() -> Self {
Self(ReedSolomonDecoder::new(get_predefined_genericgf(PredefinedGenericGF::DataMatrixField256)))
// rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
}
/**
* <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans.
* "true" is taken to mean a black module.</p>
*
* @param image booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
pub fn decode_bools(&self, image:&Vec<Vec<bool>>) -> Result<DecoderRXingResult,Exceptions> {
self.decode(&BitMatrix::parse_bools(&image))
}
/**
* <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
* to mean a black module.</p>
*
* @param bits booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
pub fn decode(&self, bits:&BitMatrix) -> Result<DecoderRXingResult,Exceptions> {
// Construct a parser and read version, error-correction level
let parser = BitMatrixParser::new(bits)?;
let version = parser.getVersion();
// Read codewords
let codewords = parser.readCodewords()?;
// Separate into data blocks
let dataBlocks = DataBlock::getDataBlocks(&codewords, version)?;
// Count total number of data bytes
let totalBytes = 0;
for db in dataBlocks {
totalBytes += db.getNumDataCodewords();
}
let resultBytes = vec![0u8;totalBytes as usize];
let dataBlocksCount = dataBlocks.len();
// Error-correct and copy data blocks together into a stream of bytes
for j in 0..dataBlocksCount {
// for (int j = 0; j < dataBlocksCount; j++) {
let dataBlock = dataBlocks[j];
let codewordBytes = dataBlock.getCodewords();
let numDataCodewords = dataBlock.getNumDataCodewords() as usize;
self.correctErrors(codewordBytes, numDataCodewords as u32);
for i in 0..numDataCodewords {
// for (int i = 0; i < numDataCodewords; i++) {
// De-interlace data blocks.
resultBytes[i * dataBlocksCount + j] = codewordBytes[i];
}
pub fn new() -> Self {
Self(ReedSolomonDecoder::new(get_predefined_genericgf(
PredefinedGenericGF::DataMatrixField256,
)))
// rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
}
// Decode the contents of that stream of bytes
decoded_bit_stream_parser::decode(&resultBytes)
}
/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails
*/
fn correctErrors(&self, codewordBytes:&[u8], numDataCodewords:u32) -> Result<(),Exceptions> {
let numCodewords = codewordBytes.len();
// First read into an array of ints
// let codewordsInts = vec![0i32;numCodewords];
// for i in 0..numCodewords {
// // for (int i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i];
// }
let codewordsInts : Vec<i32> = codewordBytes.iter().map(|x| *x as i32).collect();
//try {
self.0.decode(&mut codewordsInts, codewordBytes.len() as i32- numDataCodewords as i32)?;
//} catch (ReedSolomonException ignored) {
//throw ChecksumException.getChecksumInstance();
//}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for i in 0..numDataCodewords as usize {
// for (int i = 0; i < numDataCodewords; i++) {
codewordBytes[i] = codewordsInts[i] as u8;
/**
* <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans.
* "true" is taken to mean a black module.</p>
*
* @param image booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
pub fn decode_bools(&self, image: &Vec<Vec<bool>>) -> Result<DecoderRXingResult, Exceptions> {
self.decode(&BitMatrix::parse_bools(&image))
}
// codewordsInts.into_iter().take(numDataCodewords as usize).map(|x| x as u8).collect::<Vec<u8>>()
Ok(())
}
/**
* <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
* to mean a black module.</p>
*
* @param bits booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
pub fn decode(&self, bits: &BitMatrix) -> Result<DecoderRXingResult, Exceptions> {
// Construct a parser and read version, error-correction level
let mut parser = BitMatrixParser::new(bits)?;
// Read codewords
let codewords = parser.readCodewords()?;
let version = parser.getVersion();
// Separate into data blocks
let dataBlocks = DataBlock::getDataBlocks(&codewords, &version)?;
// Count total number of data bytes
let mut totalBytes = 0;
for db in &dataBlocks {
totalBytes += db.getNumDataCodewords();
}
let mut resultBytes = vec![0u8; totalBytes as usize];
let dataBlocksCount = dataBlocks.len();
// Error-correct and copy data blocks together into a stream of bytes
for j in 0..dataBlocksCount {
// for (int j = 0; j < dataBlocksCount; j++) {
let dataBlock = &dataBlocks[j];
let mut codewordBytes = dataBlock.getCodewords().to_vec();
let numDataCodewords = dataBlock.getNumDataCodewords() as usize;
self.correctErrors(&mut codewordBytes, numDataCodewords as u32)?;
for i in 0..numDataCodewords {
// for (int i = 0; i < numDataCodewords; i++) {
// De-interlace data blocks.
resultBytes[i * dataBlocksCount + j] = codewordBytes[i];
}
}
// Decode the contents of that stream of bytes
decoded_bit_stream_parser::decode(&resultBytes)
}
/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @throws ChecksumException if error correction fails
*/
fn correctErrors(
&self,
codewordBytes: &mut [u8],
numDataCodewords: u32,
) -> Result<(), Exceptions> {
let _numCodewords = codewordBytes.len();
// First read into an array of ints
// let codewordsInts = vec![0i32;numCodewords];
// for i in 0..numCodewords {
// // for (int i = 0; i < numCodewords; i++) {
// codewordsInts[i] = codewordBytes[i];
// }
let mut codewordsInts: Vec<i32> = codewordBytes.iter().map(|x| *x as i32).collect();
//try {
self.0.decode(
&mut codewordsInts,
codewordBytes.len() as i32 - numDataCodewords as i32,
)?;
//} catch (ReedSolomonException ignored) {
//throw ChecksumException.getChecksumInstance();
//}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for i in 0..numDataCodewords as usize {
// for (int i = 0; i < numDataCodewords; i++) {
codewordBytes[i] = codewordsInts[i] as u8;
}
// codewordsInts.into_iter().take(numDataCodewords as usize).map(|x| x as u8).collect::<Vec<u8>>()
Ok(())
}
}

View File

@@ -1,12 +1,11 @@
mod version;
mod bit_matrix_parser;
mod data_block;
mod decoder;
mod bit_matrix_parser;
mod version;
pub use version::*;
pub use bit_matrix_parser::*;
pub use data_block::*;
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 <= '^' {
sb.push((c as u8 - 64) as char);
} else {
high_level_encoder::illegalCharacter(c);
high_level_encoder::illegalCharacter(c).expect("");
}
}