Skip to content

Commit

Permalink
perf: code cleanup and loop fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hschimke committed Feb 9, 2024
1 parent 44d7853 commit b57d7e3
Show file tree
Hide file tree
Showing 19 changed files with 121 additions and 189 deletions.
11 changes: 5 additions & 6 deletions src/common/bit_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ pub struct BitArray {

impl BitArray {
pub fn new() -> Self {
// Self {
// bits: Vec::new(),
// size: 0,
// read_offset: 0,
// }
Self::default()
Self {
bits: Vec::new(),
size: 0,
read_offset: 0,
}
}

pub fn with_size(size: usize) -> Self {
Expand Down
76 changes: 27 additions & 49 deletions src/common/eci_encoder_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ use unicode_segmentation::UnicodeSegmentation;

use super::{CharacterSet, Eci};

use once_cell::sync::Lazy;

// static ENCODERS: Lazy<Vec<CharacterSet>> = Lazy::new(|| {
// let mut enc_vec = Vec::new();
// for name in NAMES {
Expand Down Expand Up @@ -53,30 +51,28 @@ use once_cell::sync::Lazy;
// "Shift_JIS",
// ];

static ENCODERS: Lazy<Vec<CharacterSet>> = Lazy::new(|| {
vec![
CharacterSet::Cp437,
CharacterSet::ISO8859_2,
CharacterSet::ISO8859_3,
CharacterSet::ISO8859_4,
CharacterSet::ISO8859_5,
// CharacterSet::ISO8859_6,
CharacterSet::ISO8859_7,
// CharacterSet::ISO8859_8,
CharacterSet::ISO8859_9,
// CharacterSet::ISO8859_10,
// CharacterSet::ISO8859_11,
// CharacterSet::ISO8859_13,
// CharacterSet::ISO8859_14,
CharacterSet::ISO8859_15,
CharacterSet::ISO8859_16,
CharacterSet::Shift_JIS,
CharacterSet::Cp1250,
CharacterSet::Cp1251,
CharacterSet::Cp1252,
CharacterSet::Cp1256,
]
});
const ENCODERS: [CharacterSet; 14] = [
CharacterSet::Cp437,
CharacterSet::ISO8859_2,
CharacterSet::ISO8859_3,
CharacterSet::ISO8859_4,
CharacterSet::ISO8859_5,
// CharacterSet::ISO8859_6,
CharacterSet::ISO8859_7,
// CharacterSet::ISO8859_8,
CharacterSet::ISO8859_9,
// CharacterSet::ISO8859_10,
// CharacterSet::ISO8859_11,
// CharacterSet::ISO8859_13,
// CharacterSet::ISO8859_14,
CharacterSet::ISO8859_15,
CharacterSet::ISO8859_16,
CharacterSet::Shift_JIS,
CharacterSet::Cp1250,
CharacterSet::Cp1251,
CharacterSet::Cp1252,
CharacterSet::Cp1256,
];

/**
* Set of CharsetEncoders for a given input string
Expand Down Expand Up @@ -144,10 +140,7 @@ impl ECIEncoderSet {
}
if !canEncode {
//for the character at position i we don't yet have an encoder in the list
for i_encoder in 0..ENCODERS.len() {
// for encoder in ENCODERS {
let encoder = ENCODERS.get(i_encoder).unwrap();
// for (CharsetEncoder encoder : ENCODERS) {
for encoder in ENCODERS.iter() {
if encoder.encode(stringToEncode.get(i).unwrap()).is_ok() {
//Good, we found an encoder that can encode the character. We add him to the list and continue scanning
//the input
Expand All @@ -172,33 +165,18 @@ impl ECIEncoderSet {
// we need more than one single byte encoder or we need a Unicode encoder.
// In this case we append a UTF-8 and UTF-16 encoder to the list
// encoders = [] new CharsetEncoder[neededEncoders.size() + 2];
encoders = Vec::new();
// let index = 0;
encoders = Vec::with_capacity(neededEncoders.len() + 2);

for encoder in neededEncoders {
// for (CharsetEncoder encoder : neededEncoders) {
//encoders[index++] = encoder;
encoders.push(encoder);
}
encoders.extend(neededEncoders);

encoders.push(CharacterSet::UTF8);
encoders.push(CharacterSet::UTF16BE);
}

//Compute priorityEncoderIndex by looking up priorityCharset in encoders
// if priorityCharset != null {
if priorityCharset.is_some() {
// for i in 0..encoders.len() {
for (i, encoder) in encoders.iter().enumerate() {
// for (int i = 0; i < encoders.length; i++) {
// if priorityCharset.as_ref().unwrap().name() == encoder.name() {
if priorityCharset.as_ref().unwrap() == encoder {
priorityEncoderIndexValue = Some(i);
break;
}
}
if let Some(pc) = priorityCharset.as_ref() {
priorityEncoderIndexValue = encoders.iter().position(|enc| enc == pc);
}
// }
//invariants
assert_eq!(encoders[0], CharacterSet::ISO8859_1);
Self {
Expand Down
23 changes: 3 additions & 20 deletions src/common/minimal_eci_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,6 @@ impl MinimalECIInput {
.zip(&stringToEncode)
.take(stringToEncode.len())
{
// for i in 0..stringToEncode.len() {
// for (int i = 0; i < bytes.length; i++) {
// let c = stringToEncode.get(i).unwrap();
*byt = if fnc1.is_some() && c == fnc1.as_ref().unwrap() {
1000
} else {
Expand Down Expand Up @@ -332,17 +329,12 @@ impl MinimalECIInput {
}
}
//optimize memory by removing edges that have been passed.
for j in 0..encoderSet.len() {
// for (int j = 0; j < encoderSet.length(); j++) {
edges[i - 1][j] = None;
}
edges[i - 1][..encoderSet.len()].fill(None);
}
let mut minimalJ: i32 = -1;
let mut minimalSize: i32 = i32::MAX;
for j in 0..encoderSet.len() {
// for (int j = 0; j < encoderSet.length(); j++) {
if edges[inputLength][j].is_some() {
let edge = edges[inputLength][j].clone().unwrap();
if let Some(edge) = edges[inputLength][j].clone() {
if (edge.cachedTotalSize as i32) < minimalSize {
minimalSize = edge.cachedTotalSize as i32;
minimalJ = j as i32;
Expand Down Expand Up @@ -379,20 +371,11 @@ impl MinimalECIInput {
c.previous.clone().unwrap().encoderIndex
};
if previousEncoderIndex != c.encoderIndex {
// intsAL.splice(
// 0..0,
// [256 as u16 + encoderSet.getECIValue(c.encoderIndex) as u16],
// );
intsAL.insert(0, 256_u16 + encoderSet.get_eci(c.encoderIndex) as u16);
}
current = c.previous.clone();
}
//let mut ints = vec![0; intsAL.len()];
// for i in 0..ints.len() {
// // for (int i = 0; i < ints.length; i++) {
// ints[i] = *intsAL.get(i).unwrap();
// }
//ints[..].copy_from_slice(&intsAL[..]);

intsAL
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/common/quad.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl Quadrilateral {
pub fn orientation(&self) -> f64 {
let centerLine =
(*self.top_right() + *self.bottom_right()) - (*self.top_left() + *self.bottom_left());
if (centerLine == Point { x: 0.0, y: 0.0 }) {
if centerLine == Point::default() {
return 0.0;
}
let centerLineF = Point::normalized(centerLine);
Expand Down
12 changes: 6 additions & 6 deletions src/common/reedsolomon/reedsolomon_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,10 @@ impl ReedSolomonDecoder {
let omega = &sigmaOmega[1];
let errorLocations = self.findErrorLocations(sigma)?;
let errorMagnitudes = self.findErrorMagnitudes(omega, &errorLocations)?;
for i in 0..errorLocations.len() {
for (error_location, error_magnitude) in errorLocations.iter().zip(errorMagnitudes) {
// for i in 0..errorLocations.len() {
//for (int i = 0; i < errorLocations.length; i++) {
let log_value = self.field.log(errorLocations[i] as i32)?;
let log_value = self.field.log(*error_location as i32)?;
if log_value > received.len() as i32 - 1 {
return Err(Exceptions::reed_solomon_with("Bad error location"));
}
Expand All @@ -100,7 +101,7 @@ impl ReedSolomonDecoder {
return Err(Exceptions::reed_solomon_with("Bad error location"));
}
received[position as usize] =
GenericGF::addOrSubtract(received[position as usize], errorMagnitudes[i]);
GenericGF::addOrSubtract(received[position as usize], error_magnitude);
}
Ok(errorLocations.len())
}
Expand Down Expand Up @@ -164,9 +165,8 @@ impl ReedSolomonDecoder {
return Err(Exceptions::reed_solomon_with("sigmaTilde(0) was zero"));
}

let inverse = match self.field.inverse(sigmaTildeAtZero) {
Ok(res) => res,
Err(_err) => return Err(Exceptions::reed_solomon_with("ArithmetricException")),
let Ok(inverse) = self.field.inverse(sigmaTildeAtZero) else {
return Err(Exceptions::reed_solomon_with("ArithmetricException"));
};
let sigma = t.multiply_with_scalar(inverse);
let omega = r.multiply_with_scalar(inverse);
Expand Down
5 changes: 0 additions & 5 deletions src/common/string_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,10 @@ pub fn guessCharset(bytes: &[u8], hints: &DecodingHintDictionary) -> Option<Char

// for i in 0..length {
for value in bytes.iter().take(length).copied() {
// for (int i = 0;
// i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8);
// i++) {
if !(can_be_iso88591 || can_be_shift_jis || can_be_utf8) {
break;
}

// let value = bytes[i];

// UTF-8 stuff
if can_be_utf8 {
if utf8_bytes_left > 0 {
Expand Down
22 changes: 11 additions & 11 deletions src/datamatrix/decoder/data_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use super::Version;
*
* @author [email protected] (Brian Brown)
*/
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataBlock {
numDataCodewords: u32,
codewords: Vec<u8>,
Expand Down Expand Up @@ -65,19 +66,18 @@ impl DataBlock {

// Now establish DataBlocks of the appropriate size and number of data codewords
let mut result = Vec::with_capacity(totalBlocks);
let mut numRXingResultBlocks = 0;
let mut numRXingResultBlocks: usize = 0;
for ecBlock in ecBlockArray {
for _i in 0..ecBlock.getCount() {
// for (int i = 0; i < ecBlock.getCount(); i++) {
let numDataCodewords = ecBlock.getDataCodewords() as usize;
let numBlockCodewords = ecBlocks.getECCodewords() as usize + numDataCodewords;
// result[numRXingResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]);
result.push(DataBlock::new(
let numDataCodewords = ecBlock.getDataCodewords() as usize;
let numBlockCodewords = ecBlocks.getECCodewords() as usize + numDataCodewords;
result.extend(vec![
DataBlock::new(
numDataCodewords as u32,
vec![0; numBlockCodewords],
));
numRXingResultBlocks += 1;
}
vec![0; numBlockCodewords]
);
ecBlock.getCount() as usize
]);
numRXingResultBlocks += ecBlock.getCount() as usize;
}

// All blocks have the same amount of data, except that the last n
Expand Down
13 changes: 5 additions & 8 deletions src/datamatrix/detector/datamatrix_detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,14 @@ impl<'a> Detector<'_> {
))
}

#[inline]
fn shiftPoint(p: Point, to: Point, div: u32) -> Point {
let x = (to.x - p.x) / (div as f32 + 1.0);
let y = (to.y - p.y) / (div as f32 + 1.0);
point_f(p.x + x, p.y + y)
}

#[inline]
fn moveAway(p: Point, fromX: f32, fromY: f32) -> Point {
let mut x = p.x;
let mut y = p.y;
Expand Down Expand Up @@ -177,10 +179,7 @@ impl<'a> Detector<'_> {
// A..D
// : :
// B--C
let pointA = points[0];
let pointB = points[1];
let pointC = points[2];
let pointD = points[3];
let [pointA, pointB, pointC, pointD] = points;

// Transition detection on the edge is not stable.
// To safely detect, shift the points to the module center.
Expand Down Expand Up @@ -269,10 +268,7 @@ impl<'a> Detector<'_> {
// A..D
// | :
// B--C
let mut pointA = points[0];
let mut pointB = points[1];
let mut pointC = points[2];
let mut pointD = points[3];
let [mut pointA, mut pointB, mut pointC, mut pointD] = points;

// calculate pseudo dimensions
let mut dimH = self.transitionsBetween(pointA, pointD) + 1;
Expand Down Expand Up @@ -317,6 +313,7 @@ impl<'a> Detector<'_> {
[pointAs, pointBs, pointCs, pointDs]
}

#[inline]
fn isValid(&self, p: Point) -> bool {
p.x >= 0.0
&& p.x <= self.image.getWidth() as f32 - 1.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ fn Scan(
let mut br = Point::default();
let mut tr = Point::default();

for l in lines.iter_mut() {
l.reset();
}
lines.iter_mut().for_each(|l| l.reset());

let [lineL, lineB, lineR, lineT] = lines;

Expand Down
6 changes: 1 addition & 5 deletions src/datamatrix/encoder/ascii_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::Exceptions;

use super::{high_level_encoder, Encoder};

#[derive(Debug, Default)]
pub struct ASCIIEncoder;

impl Encoder for ASCIIEncoder {
Expand Down Expand Up @@ -111,8 +112,3 @@ impl ASCIIEncoder {
}
}
}
impl Default for ASCIIEncoder {
fn default() -> Self {
Self::new()
}
}
10 changes: 3 additions & 7 deletions src/datamatrix/encoder/base256_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ use super::{
Encoder,
};

#[derive(Debug, Default)]
pub struct Base256Encoder;

impl Encoder for Base256Encoder {
fn getEncodingMode(&self) -> usize {
BASE256_ENCODATION
Expand Down Expand Up @@ -109,7 +111,7 @@ impl Base256Encoder {
pub fn new() -> Self {
Self
}
fn randomize255State(ch: char, codewordPosition: u32) -> Option<char> {
const fn randomize255State(ch: char, codewordPosition: u32) -> Option<char> {
let pseudoRandom = ((149 * codewordPosition) % 255) + 1;
let tempVariable = ch as u32 + pseudoRandom;
if tempVariable <= 255 {
Expand All @@ -119,9 +121,3 @@ impl Base256Encoder {
}
}
}

impl Default for Base256Encoder {
fn default() -> Self {
Self::new()
}
}
Loading

0 comments on commit b57d7e3

Please sign in to comment.