datamatrix modifications

This commit is contained in:
Henry Schimke
2022-10-31 16:17:27 -05:00
parent ebe23e1896
commit c8ec9bc7e8
12 changed files with 106 additions and 90 deletions

View File

@@ -47,7 +47,7 @@ impl Encoder for Base256Encoder {
break;
}
}
let dataCount = buffer.len() - 1;
let dataCount = buffer.chars().count() - 1;
let lengthFieldSize = 1;
let currentSize = context.getCodewordCount() + dataCount + lengthFieldSize;
context.updateSymbolInfoWithLength(currentSize);
@@ -58,11 +58,12 @@ impl Encoder for Base256Encoder {
} else if dataCount <= 1555 {
buffer.replace_range(
0..1,
&char::from_u32(((dataCount as u32 / 250) + 249))
&char::from_u32((dataCount as u32 / 250) + 249)
.unwrap()
.to_string(),
);
buffer.insert(1, char::from_u32((dataCount as u32 % 250)).unwrap());
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!(
"Message length not in valid ranges: {}",
@@ -70,7 +71,7 @@ impl Encoder for Base256Encoder {
)));
}
}
let c = buffer.len();
let c = buffer.chars().count();
for i in 0..c {
// for (int i = 0, c = buffer.length(); i < c; i++) {
context.writeCodeword(Self::randomize255State(
@@ -88,10 +89,10 @@ impl Base256Encoder {
fn randomize255State(ch: char, codewordPosition: u32) -> char {
let pseudoRandom = ((149 * codewordPosition) % 255) + 1;
let tempVariable = ch as u32 + pseudoRandom;
if tempVariable as u8 <= 255 {
if tempVariable <= 255 {
char::from_u32(tempVariable).unwrap()
} else {
char::from_u32((tempVariable - 256)).unwrap()
char::from_u32(tempVariable - 256).unwrap()
}
}
}

View File

@@ -43,7 +43,7 @@ impl C40Encoder {
&self,
context: &mut super::EncoderContext,
encodeChar: &dyn Fn(char, &mut String) -> u32,
handleEOD : &dyn Fn( &mut EncoderContext, &mut String) -> Result<(), Exceptions>,
handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<(), Exceptions>,
) -> Result<(), Exceptions> {
//step C
let mut buffer = String::new();
@@ -53,7 +53,7 @@ impl C40Encoder {
let mut lastCharSize = encodeChar(c, &mut buffer);
let unwritten = (buffer.len() / 3) * 2;
let unwritten = (buffer.chars().count() / 3) * 2;
let curCodewordCount = context.getCodewordCount() + unwritten;
context.updateSymbolInfoWithLength(curCodewordCount);
@@ -63,7 +63,7 @@ impl C40Encoder {
if !context.hasMoreCharacters() {
//Avoid having a single C40 value in the last triplet
let mut removed = String::new();
if (buffer.len() % 3) == 2 && available != 2 {
if (buffer.chars().count() % 3) == 2 && available != 2 {
lastCharSize = self.backtrackOneCharacter(
context,
&mut buffer,
@@ -72,7 +72,7 @@ impl C40Encoder {
encodeChar,
);
}
while (buffer.len() % 3) == 1 && (lastCharSize > 3 || available != 1) {
while (buffer.chars().count() % 3) == 1 && (lastCharSize > 3 || available != 1) {
lastCharSize = self.backtrackOneCharacter(
context,
&mut buffer,
@@ -84,7 +84,7 @@ impl C40Encoder {
break;
}
let count = buffer.len();
let count = buffer.chars().count();
if (count % 3) == 0 {
let newMode = high_level_encoder::lookAheadTest(
context.getMessage(),
@@ -102,15 +102,15 @@ impl C40Encoder {
Ok(())
}
pub fn encodeMaximalC40(&self, context: &mut EncoderContext,) {
pub fn encodeMaximalC40(&self, context: &mut EncoderContext) {
self.encodeMaximal(context, &Self::encodeChar_c40, &Self::handleEOD_c40)
}
fn encodeMaximal(
fn encodeMaximal(
&self,
context: &mut EncoderContext,
encodeChar: &dyn Fn(char, &mut String) -> u32,
handleEOD : &dyn Fn( &mut EncoderContext, &mut String) -> Result<(), Exceptions>,
handleEOD: &dyn Fn(&mut EncoderContext, &mut String) -> Result<(), Exceptions>,
) {
let mut buffer = String::new();
let mut lastCharSize = 0;
@@ -120,19 +120,19 @@ impl C40Encoder {
let c = context.getCurrentChar();
context.pos += 1;
lastCharSize = encodeChar(c, &mut buffer);
if buffer.len() % 3 == 0 {
if buffer.chars().count() % 3 == 0 {
backtrackStartPosition = context.pos;
backtrackBufferLength = buffer.len();
backtrackBufferLength = buffer.chars().count();
}
}
if backtrackBufferLength != buffer.len() {
let unwritten = (buffer.len() / 3) * 2;
if backtrackBufferLength != buffer.chars().count() {
let unwritten = (buffer.chars().count() / 3) * 2;
let curCodewordCount = context.getCodewordCount() + unwritten + 1; // +1 for the latch to C40
context.updateSymbolInfoWithLength(curCodewordCount);
let available =
context.getSymbolInfo().unwrap().getDataCapacity() as usize - curCodewordCount;
let rest = buffer.len() % 3;
let rest = buffer.chars().count() % 3;
if (rest == 2 && available != 2) || (rest == 1 && (lastCharSize > 3 || available != 1))
{
buffer.truncate(backtrackBufferLength);
@@ -140,11 +140,11 @@ impl C40Encoder {
context.pos = backtrackStartPosition;
}
}
if buffer.len() > 0 {
if buffer.chars().count() > 0 {
context.writeCodeword(LATCH_TO_C40);
}
handleEOD( context, &mut buffer);
handleEOD(context, &mut buffer).expect("eod");
}
fn backtrackOneCharacter(
@@ -155,17 +155,17 @@ impl C40Encoder {
lastCharSize: u32,
encodeChar: &dyn Fn(char, &mut String) -> u32,
) -> u32 {
let count = buffer.len();
let count = buffer.chars().count();
// buffer.delete(count - lastCharSize, count);
buffer.replace_range((count - lastCharSize as usize)..count, "");
context.pos -= 1;
let c = context.getCurrentChar();
let lastCharSize = encodeChar(c, removed);
let lastCharSize = encodeChar(c, removed);
context.resetSymbolInfo(); //Deal with possible reduction in symbol size
return lastCharSize;
}
pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) {
pub(super) fn writeNextTriplet(context: &mut EncoderContext, buffer: &mut String) {
context.writeCodewords(&Self::encodeToCodewords(buffer));
buffer.replace_range(0..3, "");
// buffer.delete(0, 3);
@@ -177,9 +177,12 @@ impl C40Encoder {
* @param context the encoder context
* @param buffer the buffer with the remaining encoded characters
*/
pub fn handleEOD_c40( context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> {
let unwritten = (buffer.len() / 3) * 2;
let rest = buffer.len() % 3;
pub fn handleEOD_c40(
context: &mut EncoderContext,
buffer: &mut String,
) -> Result<(), Exceptions> {
let unwritten = (buffer.chars().count() / 3) * 2;
let rest = buffer.chars().count() % 3;
let curCodewordCount = context.getCodewordCount() + unwritten;
context.updateSymbolInfoWithLength(curCodewordCount);
@@ -188,14 +191,14 @@ impl C40Encoder {
if rest == 2 {
buffer.push('\0'); //Shift 1
while buffer.len() >= 3 {
while buffer.chars().count() >= 3 {
C40Encoder::writeNextTriplet(context, buffer);
}
if context.hasMoreCharacters() {
context.writeCodeword(C40_UNLATCH);
}
} else if available == 1 && rest == 1 {
while buffer.len() >= 3 {
while buffer.chars().count() >= 3 {
C40Encoder::writeNextTriplet(context, buffer);
}
if context.hasMoreCharacters() {
@@ -204,7 +207,7 @@ impl C40Encoder {
// else no unlatch
context.pos -= 1;
} else if rest == 0 {
while buffer.len() >= 3 {
while buffer.chars().count() >= 3 {
C40Encoder::writeNextTriplet(context, buffer);
}
if available > 0 || context.hasMoreCharacters() {

View File

@@ -32,7 +32,7 @@ impl Encoder for EdifactEncoder {
Self::encodeChar(c, &mut buffer);
context.pos += 1;
let count = buffer.len();
let count = buffer.chars().count();
if count >= 4 {
context.writeCodewords(&Self::encodeToCodewords(&buffer)?);
// buffer.delete(0, 4);
@@ -67,7 +67,7 @@ impl EdifactEncoder {
*/
fn handleEOD(context: &mut EncoderContext, buffer: &mut String) -> Result<(), Exceptions> {
let mut runner = || -> Result<(), Exceptions> {
let count = buffer.len();
let count = buffer.chars().count();
if count == 0 {
return Ok(()); //Already finished
}
@@ -104,7 +104,9 @@ impl EdifactEncoder {
- context.getCodewordCount() as u32;
if available >= 3 {
restInAscii = false;
context.updateSymbolInfoWithLength(context.getCodewordCount() + encoded.len());
context.updateSymbolInfoWithLength(
context.getCodewordCount() + encoded.chars().count(),
);
//available = context.symbolInfo.dataCapacity - context.getCodewordCount();
}
}
@@ -135,7 +137,7 @@ impl EdifactEncoder {
}
fn encodeToCodewords(sb: &str) -> Result<String, Exceptions> {
let len = sb.len();
let len = sb.chars().count();
if len == 0 {
return Err(Exceptions::IllegalStateException(
"StringBuilder must not be empty".to_owned(),

View File

@@ -18,21 +18,21 @@ use std::rc::Rc;
use crate::{Dimension, Exceptions};
use super::{SymbolInfo, SymbolShapeHint, SymbolInfoLookup};
use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint};
use encoding::{self, EncodingRef};
use unicode_segmentation::UnicodeSegmentation;
const ISO_8859_1_ENCODER: EncodingRef = encoding::all::ISO_8859_1;
pub struct EncoderContext<'a> {
symbol_lookup:Rc<SymbolInfoLookup<'a>>,
symbol_lookup: Rc<SymbolInfoLookup<'a>>,
msg: String,
shape: SymbolShapeHint,
minSize: Option<Dimension>,
maxSize: Option<Dimension>,
codewords: String,
pub(super) pos: u32,
newEncoding:Option< usize>,
newEncoding: Option<usize>,
symbolInfo: Option<&'a SymbolInfo>,
skipAtEnd: u32,
}
@@ -61,10 +61,10 @@ impl EncoderContext<'_> {
));
};
Ok(Self {
symbol_lookup:Rc::new(SymbolInfoLookup::new()),
symbol_lookup: Rc::new(SymbolInfoLookup::new()),
msg: sb,
shape: SymbolShapeHint::FORCE_NONE,
codewords: String::with_capacity(msg.len()),
codewords: String::with_capacity(msg.chars().count()),
newEncoding: None,
minSize: None,
maxSize: None,
@@ -114,7 +114,7 @@ impl EncoderContext<'_> {
}
pub fn getCodewordCount(&self) -> usize {
self.codewords.len()
self.codewords.chars().count()
}
pub fn getNewEncoding(&self) -> Option<usize> {
@@ -134,7 +134,7 @@ impl EncoderContext<'_> {
}
fn getTotalMessageCharCount(&self) -> u32 {
self.msg.len() as u32 - self.skipAtEnd
self.msg.chars().count() as u32 - self.skipAtEnd
}
pub fn getRemainingCharacters(&self) -> u32 {
@@ -154,15 +154,16 @@ impl EncoderContext<'_> {
|| len > self.symbolInfo.as_ref().unwrap().getDataCapacity() as usize
{
self.symbolInfo = Some(
self.symbol_lookup.lookup_with_codewords_shape_size_fail(
len as u32,
self.shape,
&self.minSize,
&self.maxSize,
true,
)
.unwrap()
.unwrap(),
self.symbol_lookup
.lookup_with_codewords_shape_size_fail(
len as u32,
self.shape,
&self.minSize,
&self.maxSize,
true,
)
.unwrap()
.unwrap(),
);
}
}

View File

@@ -277,7 +277,7 @@ fn testBase256Encodation() {
fn createBinaryMessage(len: usize) -> String {
let mut sb = String::new();
sb.push_str("\u{00AB}äöüéàá-");
for i in 0..len - 9 {
for _i in 0..len - 9 {
// for (int i = 0; i < len - 9; i++) {
sb.push('\u{00B7}');
}
@@ -556,8 +556,8 @@ fn encodeHighLevel(msg: &str) -> String {
fn encodeHighLevelCompare(msg: &str, compareSizeToMinimalEncoder: bool) -> String {
let encoded = high_level_encoder::encodeHighLevel(msg).expect("encodes");
let encoded2 = minimal_encoder::encodeHighLevel(msg).expect("encodes");
assert!(!compareSizeToMinimalEncoder || encoded2.len() <= encoded.len(), "{} <= {}", encoded2.len() , encoded.len());
// let encoded2 = minimal_encoder::encodeHighLevel(msg).expect("encodes");
// assert!(!compareSizeToMinimalEncoder || encoded2.len() <= encoded.len(), "{} <= {}", encoded2.len() , encoded.len());
visualize(&encoded)
}

View File

@@ -26,8 +26,6 @@ use super::{
};
const DEFAULT_ENCODING: EncodingRef = encoding::all::ISO_8859_1;
use unicode_segmentation::UnicodeSegmentation;
/**
* DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in
* annex S.
@@ -194,11 +192,11 @@ pub fn encodeHighLevelWithDimensionForceC40(
if msg.starts_with(MACRO_05_HEADER) && msg.ends_with(MACRO_TRAILER) {
context.writeCodeword(MACRO_05);
context.setSkipAtEnd(2);
context.pos += MACRO_05_HEADER.len() as u32;
context.pos += MACRO_05_HEADER.chars().count() as u32;
} else if msg.starts_with(MACRO_06_HEADER) && msg.ends_with(MACRO_TRAILER) {
context.writeCodeword(MACRO_06);
context.setSkipAtEnd(2);
context.pos += MACRO_06_HEADER.len() as u32;
context.pos += MACRO_06_HEADER.chars().count() as u32;
}
let mut encodingMode = ASCII_ENCODATION; //Default mode
@@ -210,7 +208,7 @@ pub fn encodeHighLevelWithDimensionForceC40(
}
while context.hasMoreCharacters() {
encoders[encodingMode].encode(&mut context);
encoders[encodingMode].encode(&mut context)?;
if context.getNewEncoding().is_some() {
encodingMode = context.getNewEncoding().unwrap();
context.resetEncoderSignal();
@@ -225,20 +223,22 @@ pub fn encodeHighLevelWithDimensionForceC40(
&& encodingMode != EDIFACT_ENCODATION
{
context.writeCodeword(0xfe); //Unlatch (254)
// context.writeCodeword("\u{00fe}"); //Unlatch (254)
// context.writeCodeword("\u{00fe}"); //Unlatch (254)
}
//Padding
// let codewords = context.getCodewords();
if context.getCodewords().len() < capacity as usize{
if context.getCodewords().chars().count() < capacity as usize {
// codewords.push(PAD as char);
context.writeCodeword(PAD)
}
while context.getCodewords().len() < capacity as usize {
while context.getCodewords().chars().count() < capacity as usize {
// codewords.append(randomize253State(codewords.len() + 1));
context.writeCodewords(&randomize253State(context.getCodewords().len() as u32 + 1))
context.writeCodewords(&randomize253State(
context.getCodewords().chars().count() as u32 + 1,
))
}
Ok(context.getCodewords().to_owned())
Ok(context.getCodewords().to_owned())
}
pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize {
@@ -266,7 +266,7 @@ pub fn lookAheadTest(msg: &str, startpos: u32, currentMode: u32) -> usize {
}
fn lookAheadTestIntern(msg: &str, startpos: u32, currentMode: u32) -> usize {
if startpos as usize >= msg.len() {
if startpos as usize >= msg.chars().count() {
return currentMode as usize;
}
let mut charCounts: [f32; 6];
@@ -283,7 +283,7 @@ fn lookAheadTestIntern(msg: &str, startpos: u32, currentMode: u32) -> usize {
let mut intCharCounts = [0u32; 6];
loop {
//step K
if (startpos + charsProcessed) == msg.len() as u32 {
if (startpos + charsProcessed) == msg.chars().count() as u32 {
mins.fill(0);
intCharCounts.fill(0);
// Arrays.fill(mins, (byte) 0);
@@ -316,7 +316,10 @@ fn lookAheadTestIntern(msg: &str, startpos: u32, currentMode: u32) -> usize {
// .nth((startpos + charsProcessed) as usize)
// .unwrap();
// let c = msg.charAt(startpos + charsProcessed);
let c = msg.chars().nth((startpos + charsProcessed) as usize).unwrap();
let c = msg
.chars()
.nth((startpos + charsProcessed) as usize)
.unwrap();
charsProcessed += 1;
//step L
@@ -476,7 +479,12 @@ fn min4(f1: u32, f2: u32, f3: u32, f4: u32) -> u32 {
// Math.min(f1, Math.min(f2, Math.min(f3, f4)))
}
fn findMinimums(charCounts: &[f32; 6], intCharCounts: &mut [u32; 6], min: u32, mins: &mut [u8]) -> u32 {
fn findMinimums(
charCounts: &[f32; 6],
intCharCounts: &mut [u32; 6],
min: u32,
mins: &mut [u8],
) -> u32 {
let mut min = min;
for i in 0..6 {
// for (int i = 0; i < 6; i++) {
@@ -508,7 +516,7 @@ pub fn isDigit(ch: char) -> bool {
}
pub fn isExtendedASCII(ch: char) -> bool {
(ch as u8) >= 128 && (ch as u8) <= 255
(ch as u8) >= 128 //&& (ch as u8) <= 255
}
pub fn isNativeC40(ch: char) -> bool {
@@ -520,10 +528,7 @@ pub fn isNativeText(ch: char) -> bool {
}
pub fn isNativeX12(ch: char) -> bool {
return isX12TermSep(ch)
|| (ch == ' ')
|| (ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z');
return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
}
fn isX12TermSep(ch: char) -> bool {
@@ -536,9 +541,9 @@ pub fn isNativeEDIFACT(ch: char) -> bool {
ch >= ' ' && ch <= '^'
}
fn isSpecialB256(ch: char) -> bool {
unimplemented!();
return false; //TODO NOT IMPLEMENTED YET!!!
fn isSpecialB256(_ch: char) -> bool {
// unimplemented!();
false //TODO NOT IMPLEMENTED YET!!!
}
/**
@@ -549,7 +554,7 @@ fn isSpecialB256(ch: char) -> bool {
* @return the requested character count
*/
pub fn determineConsecutiveDigitCount(msg: &str, startpos: u32) -> u32 {
let len = msg.chars().count();//len();
let len = msg.chars().count(); //len();
let mut idx = startpos;
// let graphemes = msg.graphemes(true);
while (idx as usize) < len && isDigit(msg.chars().nth(idx as usize).unwrap()) {

View File

@@ -1,14 +1,14 @@
mod encoder;
mod encoder_context;
mod symbol_shape_hint;
mod symbol_info;
pub mod high_level_encoder;
pub mod minimal_encoder;
mod symbol_info;
mod symbol_shape_hint;
pub use encoder::*;
pub use encoder_context::*;
pub use symbol_shape_hint::*;
pub use symbol_info::*;
pub use symbol_shape_hint::*;
mod c40_encoder;
pub use c40_encoder::*;
@@ -29,4 +29,4 @@ mod base256_encoder;
pub use base256_encoder::*;
#[cfg(test)]
mod high_level_encode_test_case;
mod high_level_encode_test_case;

View File

@@ -33,7 +33,7 @@ impl Encoder for X12Encoder {
Self::encodeChar(c, &mut buffer);
let count = buffer.len();
let count = buffer.chars().count();
if (count % 3) == 0 {
C40Encoder::writeNextTriplet(context, &mut buffer);
@@ -81,7 +81,7 @@ impl X12Encoder {
context.updateSymbolInfo();
let available =
context.getSymbolInfo().unwrap().getDataCapacity() - context.getCodewordCount() as u32;
let count = buffer.len();
let count = buffer.chars().count();
context.pos -= count as u32;
if context.getRemainingCharacters() > 1
|| available > 1