format aztec

This commit is contained in:
Henry Schimke
2022-08-17 16:40:52 -05:00
parent 1035164fd7
commit ebe219b50d
4 changed files with 1622 additions and 1312 deletions

View File

@@ -2,15 +2,19 @@ pub mod decoder;
pub mod detector;
pub mod encoder;
use crate::{ResultPoint,BarcodeFormat,EncodeHintType,Writer,Reader,ReaderException,WriterException};
use crate::common::{BitMatrix,DetectorResult,DecoderResult};
use crate::{BarcodeFormat,BinaryBitmap,DecodeHintType,FormatException,NotFoundException,Reader,Result,ResultMetadataType,ResultPoint,ResultPointCallback};
use crate::aztec::decoder::Decoder;
use crate::aztec::detector::Detector;
use crate::common::{BitMatrix, DecoderResult, DetectorResult};
use crate::{
BarcodeFormat, BinaryBitmap, DecodeHintType, FormatException, NotFoundException, Reader,
Result, ResultMetadataType, ResultPoint, ResultPointCallback,
};
use crate::{
BarcodeFormat, EncodeHintType, Reader, ReaderException, ResultPoint, Writer, WriterException,
};
use crate::aztec::encoder::{AztecCode, Encoder};
// AztecDetectorResult.java
/**
* <p>Extends {@link DetectorResult} with more information specific to the Aztec format,
@@ -20,7 +24,6 @@ use crate::aztec::encoder::{AztecCode,Encoder};
*/
pub struct AztecDetectorResult {
//super: DetectorResult;
compact: bool,
nb_datablocks: i32,
@@ -43,9 +46,20 @@ impl DetectorResult for AztecDetectorResult {
}
impl AztecDetectorResult {
pub fn new( bits: &BitMatrix, points: &Vec<ResultPoint>, compact: bool, nb_datablocks: i32, nb_layers: i32) -> Self {
Self { compact: compact, nb_datablocks: nd_datablocks, nb_layers: nb_layers, bits: bits, points: points }
pub fn new(
bits: &BitMatrix,
points: &Vec<ResultPoint>,
compact: bool,
nb_datablocks: i32,
nb_layers: i32,
) -> Self {
Self {
compact: compact,
nb_datablocks: nd_datablocks,
nb_layers: nb_layers,
bits: bits,
points: points,
}
}
pub fn get_nb_layers(&self) -> i32 {
@@ -68,11 +82,9 @@ impl AztecDetectorResult {
*
* @author David Olivier
*/
pub struct AztecReader {
}
pub struct AztecReader {}
impl Reader for AztecReader {
/**
* Locates and decodes a Data Matrix code in an image.
*
@@ -84,7 +96,11 @@ impl Reader for AztecReader {
return Ok(self.decode(image, null));
}*/
fn decode(&self, image: &BinaryBitmap, hints: &Map<DecodeHintType, _>) -> Result<Result, ReaderException> {
fn decode(
&self,
image: &BinaryBitmap,
hints: &Map<DecodeHintType, _>,
) -> Result<Result, ReaderException> {
let not_found_exception: NotFoundException = null;
let format_exception: FormatException = null;
let detector: Detector = Detector::new(&image.get_black_matrix());
@@ -137,14 +153,22 @@ impl Reader for AztecReader {
}
*/
if hints != null {
let rpcb: ResultPointCallback = hints.get(DecodeHintType::NEED_RESULT_POINT_CALLBACK) as ResultPointCallback;
let rpcb: ResultPointCallback =
hints.get(DecodeHintType::NEED_RESULT_POINT_CALLBACK) as ResultPointCallback;
if rpcb != null {
for point in points {
rpcb.found_possible_result_point(&point);
}
}
}
let result: Result = Result::new(&decoder_result.get_text(), &decoder_result.get_raw_bytes(), &decoder_result.get_num_bits(), points, BarcodeFormat::AZTEC, &System::current_time_millis());
let result: Result = Result::new(
&decoder_result.get_text(),
&decoder_result.get_raw_bytes(),
&decoder_result.get_num_bits(),
points,
BarcodeFormat::AZTEC,
&System::current_time_millis(),
);
let byte_segments: List<Vec<i8>> = decoder_result.get_byte_segments();
if byte_segments != null {
result.put_metadata(ResultMetadataType::BYTE_SEGMENTS, &byte_segments);
@@ -153,7 +177,10 @@ impl Reader for AztecReader {
if ec_level != null {
result.put_metadata(ResultMetadataType::ERROR_CORRECTION_LEVEL, &ec_level);
}
result.put_metadata(ResultMetadataType::SYMBOLOGY_IDENTIFIER, format!("]z{}", decoder_result.get_symbology_modifier()));
result.put_metadata(
ResultMetadataType::SYMBOLOGY_IDENTIFIER,
format!("]z{}", decoder_result.get_symbology_modifier()),
);
return Ok(result);
}
@@ -167,12 +194,17 @@ impl Reader for AztecReader {
/**
* Renders an Aztec code as a {@link BitMatrix}.
*/
pub struct AztecWriter {
}
pub struct AztecWriter {}
impl Writer for AztecWriter {
fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: Option<&HashMap<EncodeHintType, _>>) -> BitMatrix {
fn encode(
&self,
contents: &String,
format: &BarcodeFormat,
width: i32,
height: i32,
hints: Option<&HashMap<EncodeHintType, _>>,
) -> BitMatrix {
// Do not add any ECI code by default
let mut charset: Charset = null;
let ecc_percent: i32 = Encoder::DEFAULT_EC_PERCENT;
@@ -182,13 +214,22 @@ impl Writer for AztecWriter {
charset = Charset::for_name(&hints.get(EncodeHintType::CHARACTER_SET).to_string());
}
if hints.contains_key(EncodeHintType::ERROR_CORRECTION) {
ecc_percent = Integer::parse_int(&hints.get(EncodeHintType::ERROR_CORRECTION).to_string());
ecc_percent =
Integer::parse_int(&hints.get(EncodeHintType::ERROR_CORRECTION).to_string());
}
if hints.contains_key(EncodeHintType::AZTEC_LAYERS) {
layers = Integer::parse_int(&hints.get(EncodeHintType::AZTEC_LAYERS).to_string());
}
}
return ::encode(&contents, format, width, height, &charset, ecc_percent, layers);
return ::encode(
&contents,
format,
width,
height,
&charset,
ecc_percent,
layers,
);
}
/*
fn encode( contents: &String, format: &BarcodeFormat, width: i32, height: i32, charset: &Charset, ecc_percent: i32, layers: i32) -> BitMatrix {
@@ -198,8 +239,6 @@ impl Writer for AztecWriter {
let aztec: AztecCode = Encoder::encode(&contents, ecc_percent, layers, &charset);
return ::render_result(aztec, width, height);
}*/
}
impl AztecWriter {
@@ -235,7 +274,6 @@ impl AztecWriter {
output_x += multiple;
}
}
}
input_y += 1;
output_y += multiple;

View File

@@ -1,7 +1,7 @@
use create::FormatException;
use crate::aztec::AztecDetectorResult;
use crate::common::{BitMatrix,CharacterSetECI,DecoderResult};
use crate::common::reedsolomon::{GenericGF, ReedSolomonDecoder, ReedSolomonException};
use crate::common::{BitMatrix, CharacterSetECI, DecoderResult};
use create::FormatException;
/**
* <p>The main class which implements Aztec Code decoding -- as opposed to locating and extracting
@@ -10,50 +10,73 @@ use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonExcepti
* @author David Olivier
*/
const UPPER_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "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", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS", ]
;
const UPPER_TABLE: vec![Vec<String>; 32] = vec![
"CTRL_PS", " ", "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", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS",
];
const LOWER_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "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", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS", ]
;
const LOWER_TABLE: vec![Vec<String>; 32] = vec![
"CTRL_PS", " ", "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", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS",
];
const MIXED_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "\u{0001}", "\u{0002}", "\u{0003}", "\u{0004}", "\u{0005}", "\u{0006}", "\u{0007}", "\u{000b}", "\t", "\n", "\u{000d}", "\u{000f}", "\r", "\u{0021}", "\u{0022}", "\u{0023}", "\u{0024}", "\u{0025}", "@", "\\", "^", "_", "`", "|", "~", "\u{00b1}", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS", ]
;
const MIXED_TABLE: vec![Vec<String>; 32] = vec![
"CTRL_PS", " ", "\u{0001}", "\u{0002}", "\u{0003}", "\u{0004}", "\u{0005}", "\u{0006}",
"\u{0007}", "\u{000b}", "\t", "\n", "\u{000d}", "\u{000f}", "\r", "\u{0021}", "\u{0022}",
"\u{0023}", "\u{0024}", "\u{0025}", "@", "\\", "^", "_", "`", "|", "~", "\u{00b1}", "CTRL_LL",
"CTRL_UL", "CTRL_PL", "CTRL_BS",
];
const PUNCT_TABLE: vec![Vec<String>; 32] = vec!["FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL", ]
;
const PUNCT_TABLE: vec![Vec<String>; 32] = vec![
"FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*",
"+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL",
];
const DIGIT_TABLE: vec![Vec<String>; 16] = vec!["CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US", ]
;
const DIGIT_TABLE: vec![Vec<String>; 16] = vec![
"CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL",
"CTRL_US",
];
const DEFAULT_ENCODING: Charset = StandardCharsets::ISO_8859_1;
pub struct Decoder {
ddata: AztecDetectorResult
ddata: AztecDetectorResult,
}
enum Table {
UPPER(), LOWER(), MIXED(), DIGIT(), PUNCT(), BINARY()
UPPER(),
LOWER(),
MIXED(),
DIGIT(),
PUNCT(),
BINARY(),
}
impl Decoder {
pub fn decode(&self, detector_result: &AztecDetectorResult) -> Result<DecoderResult, FormatException> {
pub fn decode(
&self,
detector_result: &AztecDetectorResult,
) -> Result<DecoderResult, FormatException> {
self.ddata = detector_result;
let matrix: BitMatrix = detector_result.get_bits();
let rawbits: Vec<bool> = self.extract_bits(&matrix);
let corrected_bits: CorrectedBitsResult = self.correct_bits(&rawbits);
let raw_bytes: Vec<i8> = ::convert_bool_array_to_byte_array(corrected_bits.correctBits);
let result: String = ::get_encoded_data(corrected_bits.correctBits);
let decoder_result: DecoderResult = DecoderResult::new(&raw_bytes, &result, null, &String::format("%d%%", corrected_bits.ecLevel), None, None, None);
let decoder_result: DecoderResult = DecoderResult::new(
&raw_bytes,
&result,
null,
&String::format("%d%%", corrected_bits.ecLevel),
None,
None,
None,
);
decoder_result.set_num_bits(corrected_bits.correctBits.len());
return Ok(decoder_result);
}
// This method is used for testing the high-level encoder
pub fn high_level_decode( corrected_bits: &Vec<bool>) -> /* throws FormatException */Result<String, Rc<Exception>> {
pub fn high_level_decode(corrected_bits: &Vec<bool>) -> Result<String, Rc<Exception>> {
return Ok(::get_encoded_data(&corrected_bits));
}
@@ -62,7 +85,7 @@ impl Decoder {
*
* @return the decoded string
*/
fn get_encoded_data( corrected_bits: &Vec<bool>) -> /* throws FormatException */Result<String, Rc<Exception>> {
fn get_encoded_data(corrected_bits: &Vec<bool>) -> Result<String, Rc<Exception>> {
let end_index: i32 = corrected_bits.len();
// table most recently latched to
let latch_table: Table = Table::UPPER;
@@ -128,22 +151,18 @@ impl Decoder {
result.append(&decoded_bytes.to_string(&encoding.name()));
decoded_bytes.reset();
match n {
0 =>
{
0 => {
// translate FNC1 as ASCII 29
result.append(29 as char);
break;
}
7 =>
{
7 => {
// FLG(7) is reserved and illegal
return Err(FormatException::get_format_instance());
}
_ =>
{
_ => {
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode
let mut eci: i32 = 0;
if end_index - index < 4 * n {
@@ -158,7 +177,8 @@ impl Decoder {
}
eci = eci * 10 + (next_digit - 2);
}
let charset_e_c_i: CharacterSetECI = CharacterSetECI::get_character_set_e_c_i_by_value(eci);
let charset_e_c_i: CharacterSetECI =
CharacterSetECI::get_character_set_e_c_i_by_value(eci);
if charset_e_c_i == null {
return Err(FormatException::get_format_instance());
}
@@ -190,7 +210,6 @@ impl Decoder {
result.append(&decoded_bytes.to_string(&encoding.name()));
return Ok(result.to_string());
}
@@ -199,31 +218,23 @@ impl Decoder {
*/
fn get_table(t: char) -> Table {
match t {
'L' =>
{
'L' => {
return Table::LOWER;
}
'P' =>
{
'P' => {
return Table::PUNCT;
}
'M' =>
{
'M' => {
return Table::MIXED;
}
'D' =>
{
'D' => {
return Table::DIGIT;
}
'B' =>
{
'B' => {
return Table::BINARY;
}
'U' =>
{
}
_ =>
{
'U' => {}
_ => {
return Table::UPPER;
}
}
@@ -237,35 +248,28 @@ impl Decoder {
*/
fn get_character(table: &Table, code: i32) -> String {
match table {
UPPER =>
{
UPPER => {
return UPPER_TABLE[code];
}
LOWER =>
{
LOWER => {
return LOWER_TABLE[code];
}
MIXED =>
{
MIXED => {
return MIXED_TABLE[code];
}
PUNCT =>
{
PUNCT => {
return PUNCT_TABLE[code];
}
DIGIT =>
{
DIGIT => {
return DIGIT_TABLE[code];
}
_ =>
{
_ => {
// Should not reach here.
return Err(IllegalStateException::new("Bad table"));
}
}
}
/**
* <p>Performs RS error correction on an array of bits.</p>
*
@@ -311,7 +315,6 @@ impl Decoder {
let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(gf)?;
rs_decoder.decode(&data_words, num_codewords - num_data_codewords);
// Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing
let mask: i32 = (1 << codeword_size) - 1;
@@ -332,7 +335,8 @@ impl Decoder {
}
// Now, actually unpack the bits and remove the stuffing
let corrected_bits: [bool; num_data_codewords * codeword_size - stuffed_bits] = [false; num_data_codewords * codeword_size - stuffed_bits];
let corrected_bits: [bool; num_data_codewords * codeword_size - stuffed_bits] =
[false; num_data_codewords * codeword_size - stuffed_bits];
let mut index: i32 = 0;
{
let mut i: i32 = 0;
@@ -341,7 +345,12 @@ impl Decoder {
let data_word: i32 = data_words[i];
if data_word == 1 || data_word == mask - 1 {
// next codewordSize-1 bits are all zeros or all ones
Arrays::fill(&corrected_bits, index, index + codeword_size - 1, data_word > 1);
Arrays::fill(
&corrected_bits,
index,
index + codeword_size - 1,
data_word > 1,
);
index += codeword_size - 1;
} else {
{
@@ -353,14 +362,16 @@ impl Decoder {
bit -= 1;
}
}
}
}
i += 1;
}
}
return Ok(CorrectedBitsResult::new(&corrected_bits, 100 * (num_codewords - num_data_codewords) / num_codewords));
return Ok(CorrectedBitsResult::new(
&corrected_bits,
100 * (num_codewords - num_data_codewords) / num_codewords,
));
}
/**
@@ -374,7 +385,8 @@ impl Decoder {
// not including alignment lines
let base_matrix_size: i32 = (if compact { 11 } else { 14 }) + layers * 4;
let alignment_map: [i32; base_matrix_size] = [0; base_matrix_size];
let mut rawbits: [bool; ::total_bits_in_layer(layers, compact)] = [false; ::total_bits_in_layer(layers, compact)];
let mut rawbits: [bool; ::total_bits_in_layer(layers, compact)] =
[false; ::total_bits_in_layer(layers, compact)];
if compact {
{
let mut i: i32 = 0;
@@ -385,7 +397,6 @@ impl Decoder {
i += 1;
}
}
} else {
let matrix_size: i32 = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15);
let orig_center: i32 = base_matrix_size / 2;
@@ -401,7 +412,6 @@ impl Decoder {
i += 1;
}
}
}
{
let mut i: i32 = 0;
@@ -424,18 +434,35 @@ impl Decoder {
while k < 2 {
{
// left column
rawbits[row_offset + column_offset + k] = matrix.get(alignment_map[low + k], alignment_map[low + j]);
rawbits[row_offset + column_offset + k] = matrix.get(
alignment_map[low + k],
alignment_map[low + j],
);
// bottom row
rawbits[row_offset + 2 * row_size + column_offset + k] = matrix.get(alignment_map[low + j], alignment_map[high - k]);
rawbits
[row_offset + 2 * row_size + column_offset + k] =
matrix.get(
alignment_map[low + j],
alignment_map[high - k],
);
// right column
rawbits[row_offset + 4 * row_size + column_offset + k] = matrix.get(alignment_map[high - k], alignment_map[high - j]);
rawbits
[row_offset + 4 * row_size + column_offset + k] =
matrix.get(
alignment_map[high - k],
alignment_map[high - j],
);
// top row
rawbits[row_offset + 6 * row_size + column_offset + k] = matrix.get(alignment_map[high - j], alignment_map[low + k]);
rawbits
[row_offset + 6 * row_size + column_offset + k] =
matrix.get(
alignment_map[high - j],
alignment_map[low + k],
);
}
k += 1;
}
}
}
j += 1;
}
@@ -506,15 +533,16 @@ impl Decoder {
}
struct CorrectedBitsResult {
correct_bits: Vec<bool>,
ec_level: i32
ec_level: i32,
}
impl CorrectedBitsResult {
fn new(correct_bits: &Vec<bool>, ec_level: i32) -> Self {
Self { correct_bits: correct_bits, ec_level: ec_level }
Self {
correct_bits: correct_bits,
ec_level: ec_level,
}
}
}

View File

@@ -1,9 +1,8 @@
use crate::{NotFoundException,ResultPoint};
use crate::aztec::AztecDetectorResult;
use crate::common::{BitMatrix,GridSampler};
use crate::common::detector::{MathUtils, WhiteRectangleDetector};
use crate::common::reedsolomon::{GenericGF, ReedSolomonDecoder, ReedSolomonException};
use crate::common::{BitMatrix, GridSampler};
use crate::{NotFoundException, ResultPoint};
/**
* Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
@@ -13,14 +12,14 @@ use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonExcepti
* @author Frank Yellin
*/
const EXPECTED_CORNER_BITS: vec![Vec<i32>; 4] = vec![// 07340 XXX .XX X.. ...
const EXPECTED_CORNER_BITS: vec![Vec<i32>; 4] = vec![
// 07340 XXX .XX X.. ...
0xee0, // 00734 ... XXX .XX X..
0x1dc, // 04073 X.. ... XXX .XX
0x83b, // 03407 .XX X.. ... XXX
0x707, ]
;
0x707,
];
pub struct Detector {
image: BitMatrix,
compact: bool,
@@ -31,11 +30,10 @@ pub struct Detector {
nb_center_layers: i32,
shift: i32
shift: i32,
}
impl Detector {
pub fn new(image: &BitMatrix) -> Self {
let new_d: Self;
new_d.image = image;
@@ -50,7 +48,10 @@ impl Detector {
* @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException if no Aztec Code can be found
*/
pub fn detect(&self, is_mirror: Option<bool>) -> Result<AztecDetectorResult,NotFoundException> {
pub fn detect(
&self,
is_mirror: Option<bool>,
) -> Result<AztecDetectorResult, NotFoundException> {
// 1. Get the center of the aztec matrix
let p_center: Point = self.get_matrix_center();
// 2. Get the center points of the four diagonal points just outside the bull's eye
@@ -64,10 +65,22 @@ impl Detector {
// 3. Get the size of the matrix and other parameters from the bull's eye
self.extract_parameters(&bulls_eye_corners);
// 4. Sample the grid
let bits: BitMatrix = self.sample_grid(&self.image, bulls_eye_corners[self.shift % 4], bulls_eye_corners[(self.shift + 1) % 4], bulls_eye_corners[(self.shift + 2) % 4], bulls_eye_corners[(self.shift + 3) % 4]);
let bits: BitMatrix = self.sample_grid(
&self.image,
bulls_eye_corners[self.shift % 4],
bulls_eye_corners[(self.shift + 1) % 4],
bulls_eye_corners[(self.shift + 2) % 4],
bulls_eye_corners[(self.shift + 3) % 4],
);
// 5. Get the corners of the matrix.
let corners: Vec<ResultPoint> = self.get_matrix_corner_points(&bulls_eye_corners);
return Ok(AztecDetectorResult::new(&bits, &corners, self.compact, self.nb_data_blocks, self.nb_layers));
return Ok(AztecDetectorResult::new(
&bits,
&corners,
self.compact,
self.nb_data_blocks,
self.nb_layers,
));
}
/**
@@ -76,18 +89,26 @@ impl Detector {
* @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters
*/
fn extract_parameters(&self, bulls_eye_corners: &Vec<ResultPoint>) -> Result<(), NotFoundException> {
if !self.is_valid(bulls_eye_corners[0]) || !self.is_valid(bulls_eye_corners[1]) || !self.is_valid(bulls_eye_corners[2]) || !self.is_valid(bulls_eye_corners[3]) {
fn extract_parameters(
&self,
bulls_eye_corners: &Vec<ResultPoint>,
) -> Result<(), NotFoundException> {
if !self.is_valid(bulls_eye_corners[0])
|| !self.is_valid(bulls_eye_corners[1])
|| !self.is_valid(bulls_eye_corners[2])
|| !self.is_valid(bulls_eye_corners[3])
{
return Err(NotFoundException::get_not_found_instance());
}
let length: i32 = 2 * self.nb_center_layers;
// Get the bits around the bull's eye
let sides: vec![Vec<i32>; 4] = vec![// Right side
let sides: vec![Vec<i32>; 4] = vec![
// Right side
self.sample_line(&bulls_eye_corners[0], &bulls_eye_corners[1], length), // Bottom
self.sample_line(&bulls_eye_corners[1], &bulls_eye_corners[2], length), // Left side
self.sample_line(&bulls_eye_corners[2], &bulls_eye_corners[3], length), // Top
self.sample_line(&bulls_eye_corners[3], &bulls_eye_corners[0], length), ]
;
self.sample_line(&bulls_eye_corners[3], &bulls_eye_corners[0], length),
];
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
@@ -173,7 +194,10 @@ impl Detector {
* @param compact true if this is a compact Aztec code
* @throws NotFoundException if the array contains too many errors
*/
fn get_corrected_parameter_data( parameter_data: i64, compact: bool) -> /* throws NotFoundException */Result<i32, Rc<Exception>> {
fn get_corrected_parameter_data(
parameter_data: i64,
compact: bool,
) -> Result<i32, Rc<Exception>> {
let num_codewords: i32;
let num_data_codewords: i32;
if compact {
@@ -235,7 +259,7 @@ impl Detector {
* @return The corners of the bull-eye
* @throws NotFoundException If no valid bull-eye can be found
*/
fn get_bulls_eye_corners(&self, p_center: &Point) -> /* throws NotFoundException */Result<Vec<ResultPoint>, Rc<Exception>> {
fn get_bulls_eye_corners(&self, p_center: &Point) -> Result<Vec<ResultPoint>, Rc<Exception>> {
let mut pina: Point = p_center;
let mut pinb: Point = p_center;
let mut pinc: Point = p_center;
@@ -250,8 +274,12 @@ impl Detector {
let poutc: Point = self.get_first_different(&pinc, color, -1, 1);
let poutd: Point = self.get_first_different(&pind, color, -1, -1);
if self.nb_center_layers > 2 {
let q: f32 = ::distance(poutd, pouta) * self.nb_center_layers / (::distance(pind, pina) * (self.nb_center_layers + 2));
if q < 0.75 || q > 1.25 || !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd) {
let q: f32 = ::distance(poutd, pouta) * self.nb_center_layers
/ (::distance(pind, pina) * (self.nb_center_layers + 2));
if q < 0.75
|| q > 1.25
|| !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd)
{
break;
}
}
@@ -276,8 +304,11 @@ impl Detector {
let pincx: ResultPoint = ResultPoint::new(pinc.get_x() - 0.5f32, pinc.get_y() + 0.5f32);
let pindx: ResultPoint = ResultPoint::new(pind.get_x() - 0.5f32, pind.get_y() - 0.5f32);
// just outside the bull's eye.
return Ok(::expand_square( vec![pinax, pinbx, pincx, pindx, ]
, 2 * self.nb_center_layers - 3, 2 * self.nb_center_layers));
return Ok(::expand_square(
vec![pinax, pinbx, pincx, pindx],
2 * self.nb_center_layers - 3,
2 * self.nb_center_layers,
));
}
/**
@@ -295,7 +326,6 @@ impl Detector {
let corner_points_detector = WhiteRectangleDetector::new(&self.image, None, None, None);
if corner_points_detector.is_ok() {
let corner_points: Vec<ResultPoint> = corner_points_detector.detect();
point_a = corner_points[0];
@@ -305,19 +335,32 @@ impl Detector {
} else {
let cx: i32 = self.image.get_width() / 2;
let cy: i32 = self.image.get_height() / 2;
point_a = self.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1).to_result_point();
point_b = self.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1).to_result_point();
point_c = self.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1).to_result_point();
point_d = self.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1).to_result_point();
point_a = self
.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1)
.to_result_point();
point_b = self
.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1)
.to_result_point();
point_c = self
.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1)
.to_result_point();
point_d = self
.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1)
.to_result_point();
}
//Compute the center of the rectangle
let mut cx: i32 = MathUtils::round((point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32);
let mut cy: i32 = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32);
let mut cx: i32 = MathUtils::round(
(point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32,
);
let mut cy: i32 = MathUtils::round(
(point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32,
);
// in order to compute a more accurate center.
let tryResult1 = 0;
let corner_points_wrd = WhiteRectangleDetector::new(&self.image, Some(15), Some(cx), Some(cy));
let corner_points_wrd =
WhiteRectangleDetector::new(&self.image, Some(15), Some(cx), Some(cy));
if corner_points_wrd.is_ok() {
let corner_points: Vec<ResultPoint> = corner_points_wrd.detect();
point_a = corner_points[0];
@@ -325,15 +368,27 @@ impl Detector {
point_c = corner_points[2];
point_d = corner_points[3];
} else {
point_a = self.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1).to_result_point();
point_b = self.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1).to_result_point();
point_c = self.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1).to_result_point();
point_d = self.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1).to_result_point();
point_a = self
.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1)
.to_result_point();
point_b = self
.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1)
.to_result_point();
point_c = self
.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1)
.to_result_point();
point_d = self
.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1)
.to_result_point();
}
// Recompute the center of the rectangle
cx = MathUtils::round((point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32);
cy = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32);
cx = MathUtils::round(
(point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32,
);
cy = MathUtils::round(
(point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32,
);
return Point::new(cx, cy);
}
@@ -344,7 +399,11 @@ impl Detector {
* @return the array of aztec code corners
*/
fn get_matrix_corner_points(&self, bulls_eye_corners: &Vec<ResultPoint>) -> Vec<ResultPoint> {
return ::expand_square(bulls_eye_corners, 2 * self.nb_center_layers, &self.get_dimension());
return ::expand_square(
bulls_eye_corners,
2 * self.nb_center_layers,
&self.get_dimension(),
);
}
/**
@@ -352,12 +411,22 @@ impl Detector {
* topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
* diagonal just outside the bull's eye.
*/
fn sample_grid(&self, image: &BitMatrix, top_left: &ResultPoint, top_right: &ResultPoint, bottom_right: &ResultPoint, bottom_left: &ResultPoint) -> /* throws NotFoundException */Result<BitMatrix, Rc<Exception>> {
fn sample_grid(
&self,
image: &BitMatrix,
top_left: &ResultPoint,
top_right: &ResultPoint,
bottom_right: &ResultPoint,
bottom_left: &ResultPoint,
) -> Result<BitMatrix, Rc<Exception>> {
let sampler: GridSampler = GridSampler::get_instance();
let dimension: i32 = self.get_dimension();
let low: f32 = dimension / 2.0f32 - self.nb_center_layers;
let high: f32 = dimension / 2.0f32 + self.nb_center_layers;
return Ok(sampler.sample_grid(image, dimension, dimension, // topleft
return Ok(sampler.sample_grid(
image,
dimension,
dimension, // topleft
low, // topleft
low, // topright
high, // topright
@@ -365,7 +434,16 @@ impl Detector {
high, // bottomright
high, // bottomleft
low, // bottomleft
high, &top_left.get_x(), &top_left.get_y(), &top_right.get_x(), &top_right.get_y(), &bottom_right.get_x(), &bottom_right.get_y(), &bottom_left.get_x(), &bottom_left.get_y()));
high,
&top_left.get_x(),
&top_left.get_y(),
&top_right.get_x(),
&top_right.get_y(),
&bottom_right.get_x(),
&bottom_right.get_y(),
&bottom_left.get_x(),
&bottom_left.get_y(),
));
}
/**
@@ -388,7 +466,10 @@ impl Detector {
let mut i: i32 = 0;
while i < size {
{
if self.image.get(&MathUtils::round(px + i * dx), &MathUtils::round(py + i * dy)) {
if self.image.get(
&MathUtils::round(px + i * dx),
&MathUtils::round(py + i * dy),
) {
result |= 1 << (size - i - 1);
}
}
@@ -405,10 +486,25 @@ impl Detector {
*/
fn is_white_or_black_rectangle(&self, p1: &Point, p2: &Point, p3: &Point, p4: &Point) -> bool {
let corr: i32 = 3;
p1 = &Point::new(&Math::max(0, p1.get_x() - corr), &Math::min(self.image.get_height() - 1, p1.get_y() + corr));
p2 = &Point::new(&Math::max(0, p2.get_x() - corr), &Math::max(0, p2.get_y() - corr));
p3 = &Point::new(&Math::min(self.image.get_width() - 1, p3.get_x() + corr), &Math::max(0, &Math::min(self.image.get_height() - 1, p3.get_y() - corr)));
p4 = &Point::new(&Math::min(self.image.get_width() - 1, p4.get_x() + corr), &Math::min(self.image.get_height() - 1, p4.get_y() + corr));
p1 = &Point::new(
&Math::max(0, p1.get_x() - corr),
&Math::min(self.image.get_height() - 1, p1.get_y() + corr),
);
p2 = &Point::new(
&Math::max(0, p2.get_x() - corr),
&Math::max(0, p2.get_y() - corr),
);
p3 = &Point::new(
&Math::min(self.image.get_width() - 1, p3.get_x() + corr),
&Math::max(
0,
&Math::min(self.image.get_height() - 1, p3.get_y() - corr),
),
);
p4 = &Point::new(
&Math::min(self.image.get_width() - 1, p4.get_x() + corr),
&Math::min(self.image.get_height() - 1, p4.get_y() + corr),
);
let c_init: i32 = self.get_color(p4, p1);
if c_init == 0 {
return false;
@@ -460,7 +556,11 @@ impl Detector {
if err_ratio > 0.1f32 && err_ratio < 0.9f32 {
return 0;
}
return if (err_ratio <= 0.1f32) == color_model { 1 } else { -1 };
return if (err_ratio <= 0.1f32) == color_model {
1
} else {
-1
};
}
/**
@@ -494,7 +594,11 @@ impl Detector {
* @param newSide the new length of the size of the square in the target bit matrix
* @return the corners of the expanded square
*/
fn expand_square( corner_points: &Vec<ResultPoint>, old_side: i32, new_side: i32) -> Vec<ResultPoint> {
fn expand_square(
corner_points: &Vec<ResultPoint>,
old_side: i32,
new_side: i32,
) -> Vec<ResultPoint> {
let ratio: f32 = new_side / (2.0f32 * old_side);
let mut dx: f32 = corner_points[0].get_x() - corner_points[2].get_x();
let mut dy: f32 = corner_points[0].get_y() - corner_points[2].get_y();
@@ -508,8 +612,7 @@ impl Detector {
centery = (corner_points[1].get_y() + corner_points[3].get_y()) / 2.0f32;
let result1: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy);
let result3: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy);
return vec![result0, result1, result2, result3, ]
;
return vec![result0, result1, result2, result3];
}
fn is_valid_coords(&self, x: i32, y: i32) -> bool {
@@ -536,20 +639,15 @@ impl Detector {
}
return 4 * self.nb_layers + 2 * ((2 * self.nb_layers + 6) / 15) + 15;
}
}
struct Point {
x: i32,
y: i32
y: i32,
}
impl Point {
fn to_result_point(&self) -> ResultPoint {
return ResultPoint::new(self.x, self.y);
}

View File

@@ -1,14 +1,13 @@
use std::cmp::Ordering;
use std::fmt::format;
use crate::common::{BitArray,BitMatrix,CharacterSetECI};
use crate::common::reedsolomon::{GenericGF, ReedSolomonEncoder};
use crate::common::{BitArray, BitMatrix, CharacterSetECI};
// Token.java
const EMPTY: Token = SimpleToken::new(null, 0, 0);
pub trait Token {
fn new(previous: &Token) -> Token; /*{
let .previous = previous;
}*/
@@ -36,7 +35,6 @@ pub trait Token {
* @author Rustam Abdullaev
*/
pub struct AztecCode {
compact: bool,
size: i32,
@@ -45,11 +43,10 @@ pub struct AztecCode {
code_words: i32,
matrix: BitMatrix
matrix: BitMatrix,
}
impl AztecCode {
/**
* @return {@code true} if compact instead of full mode
*/
@@ -123,15 +120,14 @@ const MAX_NB_BITS: i32 = 32;
const MAX_NB_BITS_COMPACT: i32 = 4;
const WORD_SIZE: vec![Vec<i32>; 33] = vec![4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, ]
;
pub struct Encoder {
}
const WORD_SIZE: vec![Vec<i32>; 33] = vec![
4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12,
];
pub struct Encoder {}
impl Encoder {
fn new() -> Encoder {
}
fn new() -> Encoder {}
/**
* Encodes the given string content as an Aztec symbol (without ECI code)
@@ -153,7 +149,12 @@ impl Encoder {
* @return Aztec symbol matrix with metadata
*/
pub fn encode(data: &String, min_e_c_c_percent: i32, user_specified_layers: i32) -> AztecCode {
return ::encode(&data.get_bytes(StandardCharsets::ISO_8859_1), min_e_c_c_percent, user_specified_layers, null);
return ::encode(
&data.get_bytes(StandardCharsets::ISO_8859_1),
min_e_c_c_percent,
user_specified_layers,
null,
);
}
/**
@@ -168,8 +169,17 @@ impl Encoder {
* (Latin-1), the default encoding of the symbol.
* @return Aztec symbol matrix with metadata
*/
pub fn encode( data: &String, min_e_c_c_percent: i32, user_specified_layers: i32, charset: &Charset) -> AztecCode {
let bytes: Vec<i8> = data.get_bytes( if null != charset { charset } else { StandardCharsets::ISO_8859_1 });
pub fn encode(
data: &String,
min_e_c_c_percent: i32,
user_specified_layers: i32,
charset: &Charset,
) -> AztecCode {
let bytes: Vec<i8> = data.get_bytes(if null != charset {
charset
} else {
StandardCharsets::ISO_8859_1
});
return ::encode(&bytes, min_e_c_c_percent, user_specified_layers, &charset);
}
@@ -207,7 +217,12 @@ impl Encoder {
* default encoding of ISO/IEC 8859-1 will be assuming by readers.
* @return Aztec symbol matrix with metadata
*/
pub fn encode( data: &Vec<i8>, min_e_c_c_percent: i32, user_specified_layers: i32, charset: Option<&Charset>) -> AztecCode {
pub fn encode(
data: &Vec<i8>,
min_e_c_c_percent: i32,
user_specified_layers: i32,
charset: Option<&Charset>,
) -> AztecCode {
// High-level encode
let bits: BitArray = HighLevelEncoder::new(&data, charset).encode();
// stuff bits and choose symbol size
@@ -221,19 +236,33 @@ impl Encoder {
if user_specified_layers != DEFAULT_AZTEC_LAYERS {
compact = user_specified_layers < 0;
layers = Math::abs(user_specified_layers);
if layers > ( if compact { MAX_NB_BITS_COMPACT } else { MAX_NB_BITS }) {
return Err( IllegalArgumentException::new(&String::format("Illegal value %s for layers", user_specified_layers)));
if layers
> (if compact {
MAX_NB_BITS_COMPACT
} else {
MAX_NB_BITS
})
{
return Err(IllegalArgumentException::new(&String::format(
"Illegal value %s for layers",
user_specified_layers,
)));
}
total_bits_in_layer = self.total_bits_in_layer(layers, compact);
word_size = WORD_SIZE[layers];
let usable_bits_in_layers: i32 = total_bits_in_layer - (total_bits_in_layer % word_size);
let usable_bits_in_layers: i32 =
total_bits_in_layer - (total_bits_in_layer % word_size);
stuffed_bits = ::stuff_bits(bits, word_size);
if stuffed_bits.get_size() + ecc_bits > usable_bits_in_layers {
return Err( IllegalArgumentException::new("Data to large for user specified layer"));
return Err(IllegalArgumentException::new(
"Data to large for user specified layer",
));
}
if compact && stuffed_bits.get_size() > word_size * 64 {
// Compact format only allows 64 data words, though C4 can hold more words than that
return Err( IllegalArgumentException::new("Data to large for user specified layer"));
return Err(IllegalArgumentException::new(
"Data to large for user specified layer",
));
}
} else {
word_size = 0;
@@ -244,7 +273,9 @@ impl Encoder {
loop {
{
if i > MAX_NB_BITS {
return Err( IllegalArgumentException::new("Data too large for an Aztec code"));
return Err(IllegalArgumentException::new(
"Data too large for an Aztec code",
));
}
compact = i <= 3;
layers = if compact { i + 1 } else { i };
@@ -257,7 +288,8 @@ impl Encoder {
word_size = WORD_SIZE[layers];
stuffed_bits = ::stuff_bits(bits, word_size);
}
let usable_bits_in_layers: i32 = total_bits_in_layer - (total_bits_in_layer % word_size);
let usable_bits_in_layers: i32 =
total_bits_in_layer - (total_bits_in_layer % word_size);
if compact && stuffed_bits.get_size() > word_size * 64 {
// Compact format only allows 64 data words, though C4 can hold more words than that
continue;
@@ -269,12 +301,13 @@ impl Encoder {
i += 1;
}
}
}
let message_bits: BitArray = ::generate_check_words(stuffed_bits, total_bits_in_layer, word_size);
let message_bits: BitArray =
::generate_check_words(stuffed_bits, total_bits_in_layer, word_size);
// generate mode message
let message_size_in_words: i32 = stuffed_bits.get_size() / word_size;
let mode_message: BitArray = ::generate_mode_message(compact, layers, message_size_in_words);
let mode_message: BitArray =
::generate_mode_message(compact, layers, message_size_in_words);
// allocate symbol
// not including alignment lines
let base_matrix_size: i32 = (if compact { 11 } else { 14 }) + layers * 4;
@@ -292,7 +325,6 @@ impl Encoder {
i += 1;
}
}
} else {
matrix_size = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15);
let orig_center: i32 = base_matrix_size / 2;
@@ -308,7 +340,6 @@ impl Encoder {
i += 1;
}
}
}
let matrix: BitMatrix = BitMatrix::new(matrix_size);
// draw data bits
@@ -328,22 +359,39 @@ impl Encoder {
while k < 2 {
{
if message_bits.get(row_offset + column_offset + k) {
matrix.set(alignment_map[i * 2 + k], alignment_map[i * 2 + j]);
matrix.set(
alignment_map[i * 2 + k],
alignment_map[i * 2 + j],
);
}
if message_bits.get(row_offset + row_size * 2 + column_offset + k) {
matrix.set(alignment_map[i * 2 + j], alignment_map[base_matrix_size - 1 - i * 2 - k]);
if message_bits
.get(row_offset + row_size * 2 + column_offset + k)
{
matrix.set(
alignment_map[i * 2 + j],
alignment_map[base_matrix_size - 1 - i * 2 - k],
);
}
if message_bits.get(row_offset + row_size * 4 + column_offset + k) {
matrix.set(alignment_map[base_matrix_size - 1 - i * 2 - k], alignment_map[base_matrix_size - 1 - i * 2 - j]);
if message_bits
.get(row_offset + row_size * 4 + column_offset + k)
{
matrix.set(
alignment_map[base_matrix_size - 1 - i * 2 - k],
alignment_map[base_matrix_size - 1 - i * 2 - j],
);
}
if message_bits.get(row_offset + row_size * 6 + column_offset + k) {
matrix.set(alignment_map[base_matrix_size - 1 - i * 2 - j], alignment_map[i * 2 + k]);
if message_bits
.get(row_offset + row_size * 6 + column_offset + k)
{
matrix.set(
alignment_map[base_matrix_size - 1 - i * 2 - j],
alignment_map[i * 2 + k],
);
}
}
k += 1;
}
}
}
j += 1;
}
@@ -379,13 +427,11 @@ impl Encoder {
k += 2;
}
}
}
i += 15;
j += 16;
}
}
}
let aztec: AztecCode = AztecCode::new();
aztec.set_compact(compact);
@@ -413,7 +459,6 @@ impl Encoder {
j += 1;
}
}
}
i += 2;
}
@@ -441,7 +486,12 @@ impl Encoder {
return mode_message;
}
fn draw_mode_message( matrix: &BitMatrix, compact: bool, matrix_size: i32, mode_message: &BitArray) {
fn draw_mode_message(
matrix: &BitMatrix,
compact: bool,
matrix_size: i32,
mode_message: &BitArray,
) {
let center: i32 = matrix_size / 2;
if compact {
{
@@ -465,7 +515,6 @@ impl Encoder {
i += 1;
}
}
} else {
{
let mut i: i32 = 0;
@@ -488,7 +537,6 @@ impl Encoder {
i += 1;
}
}
}
}
@@ -522,7 +570,11 @@ impl Encoder {
let mut j: i32 = 0;
while j < word_size {
{
value |= if stuffed_bits.get(i * word_size + j) { (1 << word_size - j - 1) } else { 0 };
value |= if stuffed_bits.get(i * word_size + j) {
(1 << word_size - j - 1)
} else {
0
};
}
j += 1;
}
@@ -539,29 +591,26 @@ impl Encoder {
fn get_g_f(word_size: i32) -> GenericGF {
match word_size {
4 =>
{
4 => {
return GenericGF::AZTEC_PARAM;
}
6 =>
{
6 => {
return GenericGF::AZTEC_DATA_6;
}
8 =>
{
8 => {
return GenericGF::AZTEC_DATA_8;
}
10 =>
{
10 => {
return GenericGF::AZTEC_DATA_10;
}
12 =>
{
12 => {
return GenericGF::AZTEC_DATA_12;
}
_ =>
{
return Err( IllegalArgumentException::new(format!("Unsupported word size {}", word_size)));
_ => {
return Err(IllegalArgumentException::new(format!(
"Unsupported word size {}",
word_size
)));
}
}
}
@@ -616,7 +665,7 @@ struct BinaryShiftToken {
binary_shift_start: i32,
binary_shift_byte_count: i32
binary_shift_byte_count: i32,
}
impl Token for BinaryShiftToken {
@@ -646,21 +695,25 @@ impl Token for BinaryShiftToken {
i += 1;
}
}
}
fn to_string(&self) -> String {
return format!("<{}::{}>", self.binary_shift_start, (self.binary_shift_start + self.binary_shift_byte_count - 1));
return format!(
"<{}::{}>",
self.binary_shift_start,
(self.binary_shift_start + self.binary_shift_byte_count - 1)
);
}
}
impl BinaryShiftToken {
fn new(previous: &Token, binary_shift_start: i32, binary_shift_byte_count: i32) -> Self {
Self{ previous, binary_shift_start, binary_shift_byte_count}
Self {
previous,
binary_shift_start,
binary_shift_byte_count,
}
}
}
// HighLevelEncoder.java
@@ -677,8 +730,7 @@ impl BinaryShiftToken {
* @author Rustam Abdullaev
*/
const MODE_NAMES: vec![Vec<String>; 5] = vec!["UPPER", "LOWER", "DIGIT", "MIXED", "PUNCT", ]
;
const MODE_NAMES: vec![Vec<String>; 5] = vec!["UPPER", "LOWER", "DIGIT", "MIXED", "PUNCT"];
// 5 bits
const MODE_UPPER: i32 = 0;
@@ -700,32 +752,47 @@ const MODE_NAMES: vec![Vec<String>; 5] = vec!["UPPER", "LOWER", "DIGIT", "MIXED"
// be up to 14 bits. In the best possible case, we are already there!
// The high half-word of each entry gives the number of bits.
// The low half-word of each entry are the actual bits necessary to change
const LATCH_TABLE: vec![vec![Vec<Vec<i32>>; 5]; 5] = vec![vec![0, // UPPER -> LOWER
const LATCH_TABLE: vec![vec![Vec<Vec<i32>>; 5]; 5] = vec![
vec![
0, // UPPER -> LOWER
(5 << 16) + 28, // UPPER -> DIGIT
(5 << 16) + 30, // UPPER -> MIXED
(5 << 16) + 29, // UPPER -> MIXED -> PUNCT
(10 << 16) + (29 << 5) + 30, ]
, vec![// LOWER -> DIGIT -> UPPER
(9 << 16) + (30 << 4) + 14, 0, // LOWER -> DIGIT
(10 << 16) + (29 << 5) + 30,
],
vec![
// LOWER -> DIGIT -> UPPER
(9 << 16) + (30 << 4) + 14,
0, // LOWER -> DIGIT
(5 << 16) + 30, // LOWER -> MIXED
(5 << 16) + 29, // LOWER -> MIXED -> PUNCT
(10 << 16) + (29 << 5) + 30, ]
, vec![// DIGIT -> UPPER
(10 << 16) + (29 << 5) + 30,
],
vec![
// DIGIT -> UPPER
(4 << 16) + 14, // DIGIT -> UPPER -> LOWER
(9 << 16) + (14 << 5) + 28, 0, // DIGIT -> UPPER -> MIXED
(9 << 16) + (14 << 5) + 29, (14 << 16) + (14 << 10) + (29 << 5) + 30, ]
, vec![// MIXED -> UPPER
(9 << 16) + (14 << 5) + 28,
0, // DIGIT -> UPPER -> MIXED
(9 << 16) + (14 << 5) + 29,
(14 << 16) + (14 << 10) + (29 << 5) + 30,
],
vec![
// MIXED -> UPPER
(5 << 16) + 29, // MIXED -> LOWER
(5 << 16) + 28, // MIXED -> UPPER -> DIGIT
(10 << 16) + (29 << 5) + 30, 0, // MIXED -> PUNCT
(5 << 16) + 30, ]
, vec![// PUNCT -> UPPER
(10 << 16) + (29 << 5) + 30,
0, // MIXED -> PUNCT
(5 << 16) + 30,
],
vec![
// PUNCT -> UPPER
(5 << 16) + 31, // PUNCT -> UPPER -> LOWER
(10 << 16) + (31 << 5) + 28, // PUNCT -> UPPER -> DIGIT
(10 << 16) + (31 << 5) + 30, // PUNCT -> UPPER -> MIXED
(10 << 16) + (31 << 5) + 29, 0, ]
, ]
;
(10 << 16) + (31 << 5) + 29,
0,
],
];
// A reverse mapping from [mode][char] to the encoding for that character
// in that mode. An entry of 0 indicates no mapping exists.
@@ -736,14 +803,12 @@ const MODE_NAMES: vec![Vec<String>; 5] = vec!["UPPER", "LOWER", "DIGIT", "MIXED"
// mode shift codes, per table
const SHIFT_TABLE: [[i32; 6]; 6] = [[0; 6]; 6];
pub struct HighLevelEncoder {
text: Vec<i8>,
charset: Charset
charset: Charset,
}
impl HighLevelEncoder {
pub fn new(text: &Vec<i8>, charset: Option<&Charset>) -> Self {
CHAR_MAP[MODE_UPPER][' '] = 1;
{
@@ -780,8 +845,12 @@ impl HighLevelEncoder {
CHAR_MAP[MODE_DIGIT][','] = 12;
CHAR_MAP[MODE_DIGIT]['.'] = 13;
let mixed_table: vec![Vec<i32>; 28] = vec!['\0', ' ', '\u{0001}', '\u{0002}', '\u{0003}', '\u{0004}', '\u{0005}', '\u{0006}', '\u{0007}', '\u{000b}', '\t', '\n', '\u{000D}', '\u{000f}', '\r', '\u{0021}', '\u{0022}', '\u{0023}', '\u{0024}', '\u{0025}', '@', '\\', '^', '_', '`', '|', '~', '\u{00b1}', ]
;
let mixed_table: vec![Vec<i32>; 28] = vec![
'\0', ' ', '\u{0001}', '\u{0002}', '\u{0003}', '\u{0004}', '\u{0005}', '\u{0006}',
'\u{0007}', '\u{000b}', '\t', '\n', '\u{000D}', '\u{000f}', '\r', '\u{0021}',
'\u{0022}', '\u{0023}', '\u{0024}', '\u{0025}', '@', '\\', '^', '_', '`', '|', '~',
'\u{00b1}',
];
{
let mut i: i32 = 0;
while i < mixed_table.len() {
@@ -792,8 +861,10 @@ impl HighLevelEncoder {
}
}
let punct_table: vec![Vec<i32>; 31] = vec!['\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', ]
;
let punct_table: vec![Vec<i32>; 31] = vec![
'\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*',
'+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}',
];
{
let mut i: i32 = 0;
while i < punct_table.len() {
@@ -816,7 +887,10 @@ impl HighLevelEncoder {
SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15;
Self { text: text, charset: charset }
Self {
text: text,
charset: charset,
}
}
/**
@@ -827,7 +901,10 @@ impl HighLevelEncoder {
if self.charset != null {
let eci: CharacterSetECI = CharacterSetECI::get_character_set_e_c_i(&self.charset);
if null == eci {
return Err( IllegalArgumentException::new(format!("No ECI code for character set {}", self.charset)));
return Err(IllegalArgumentException::new(format!(
"No ECI code for character set {}",
self.charset
)));
}
initial_state = initial_state.append_f_l_gn(&eci.get_value());
}
@@ -837,30 +914,29 @@ impl HighLevelEncoder {
while index < self.text.len() {
{
let pair_code: i32;
let next_char: i32 = if index + 1 < self.text.len() { self.text[index + 1] } else { 0 };
let next_char: i32 = if index + 1 < self.text.len() {
self.text[index + 1]
} else {
0
};
match self.text[index] {
'\r' =>
{
'\r' => {
pair_code = if next_char == '\n' { 2 } else { 0 };
break;
}
'.' =>
{
'.' => {
pair_code = if next_char == ' ' { 3 } else { 0 };
break;
}
',' =>
{
',' => {
pair_code = if next_char == ' ' { 4 } else { 0 };
break;
}
':' =>
{
':' => {
pair_code = if next_char == ' ' { 5 } else { 0 };
break;
}
_ =>
{
_ => {
pair_code = 0;
}
}
@@ -879,7 +955,9 @@ impl HighLevelEncoder {
}
// We are left with a set of states. Find the shortest one.
let min_state = states.iter().min_by(|a,b| {
let min_state = states
.iter()
.min_by(|a, b| {
let c = a.get_bit_count() - b.get_bit_count();
if c > 0 {
Ordering::Greater
@@ -888,7 +966,8 @@ impl HighLevelEncoder {
} else {
Ordering::Equal
}
}).unwrap();
})
.unwrap();
/*let min_state: State = Collections::min(&states, Comparator<State>::new() {
pub fn compare(&self, a: &State, b: &State) -> i32 {
@@ -928,19 +1007,22 @@ impl HighLevelEncoder {
state_no_binary = state.end_binary_shift(index);
}
// Try generating the character by latching to its mode
if !char_in_current_table || mode == state.get_mode() || mode == MODE_DIGIT {
if !char_in_current_table || mode == state.get_mode() || mode == MODE_DIGIT
{
// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
let latch_state: State = state_no_binary.latch_and_append(mode, char_in_mode);
let latch_state: State =
state_no_binary.latch_and_append(mode, char_in_mode);
result.add(latch_state);
}
// Try generating the character by switching to its mode.
if !char_in_current_table && SHIFT_TABLE[state.get_mode()][mode] >= 0 {
// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
let shift_state: State = state_no_binary.shift_and_append(mode, char_in_mode);
let shift_state: State =
state_no_binary.shift_and_append(mode, char_in_mode);
result.add(shift_state);
}
}
@@ -958,7 +1040,11 @@ impl HighLevelEncoder {
}
}
fn update_state_list_for_pair( states: &Iterable<State>, index: i32, pair_code: i32) -> Vec<State> {
fn update_state_list_for_pair(
states: &Iterable<State>,
index: i32,
pair_code: i32,
) -> Vec<State> {
let result: Collection<State> = Vec::new();
for state in states {
::update_state_for_pair(state, index, pair_code, &result);
@@ -977,15 +1063,23 @@ impl HighLevelEncoder {
}
if pair_code == 3 || pair_code == 4 {
// both characters are in DIGITS. Sometimes better to just add two digits
let digit_state: State = state_no_binary.latch_and_append(MODE_DIGIT, // period or comma in DIGIT
16 - pair_code).latch_and_append(MODE_DIGIT, // space in DIGIT
1);
let digit_state: State = state_no_binary
.latch_and_append(
MODE_DIGIT, // period or comma in DIGIT
16 - pair_code,
)
.latch_and_append(
MODE_DIGIT, // space in DIGIT
1,
);
result.add(digit_state);
}
if state.get_binary_shift_byte_count() > 0 {
// It only makes sense to do the characters as binary if we're already
// in binary mode.
let binary_state: State = state.add_binary_shift_char(index).add_binary_shift_char(index + 1);
let binary_state: State = state
.add_binary_shift_char(index)
.add_binary_shift_char(index + 1);
result.add(binary_state);
}
}
@@ -1035,17 +1129,22 @@ impl Token for SimpleToken {
fn to_string(&self) -> String {
let mut value: i32 = self.value & ((1 << self.bit_count) - 1);
value |= 1 << self.bit_count;
return format!("<{}>",format!("{}",value | (1 << self.bit_count)).as_bytes()[1..]);
return format!(
"<{}>",
format!("{}", value | (1 << self.bit_count)).as_bytes()[1..]
);
//return '<' + Integer::to_binary_string(value | (1 << self.bit_count))::substring(1) + '>';
}
}
impl SimpleToken {
fn new(previous: &Token, value: i32, bit_count: i32) -> Self {
Self { previous, value, bit_count }
Self {
previous,
value,
bit_count,
}
}
}
// State.java
@@ -1057,7 +1156,6 @@ impl SimpleToken {
const INITIAL_STATE: State = State::new(Token::EMPTY, HighLevelEncoder::MODE_UPPER, 0, 0);
struct State {
// The current mode of the encoding (or the mode to which we'll return if
// we're in Binary Shift mode.
mode: i32,
@@ -1073,13 +1171,18 @@ struct State {
// The total number of bits generated (including Binary Shift).
bit_count: i32,
binary_shift_cost: i32
binary_shift_cost: i32,
}
impl State {
fn new(token: &Token, mode: i32, binary_bytes: i32, bit_count: i32) -> Self {
Self{ mode: mode, token: token, binary_shift_byte_count: binary_bytes, bit_count: bit_count, binary_shift_cost: ::calculate_binary_shift_cost(binary_bytes) }
Self {
mode: mode,
token: token,
binary_shift_byte_count: binary_bytes,
bit_count: bit_count,
binary_shift_cost: ::calculate_binary_shift_cost(binary_bytes),
}
}
fn get_mode(&self) -> i32 {
@@ -1107,7 +1210,9 @@ impl State {
// 0: FNC1
token = token.add(0, 3);
} else if eci > 999999 {
return Err( IllegalArgumentException::new("ECI code must be between 0 and 999999"));
return Err(IllegalArgumentException::new(
"ECI code must be between 0 and 999999",
));
} else {
let eci_digits: Vec<i8> = eci.to_string().as_bytes(); //Integer::to_string(eci)::get_bytes(StandardCharsets::ISO_8859_1);
// 1-6: number of ECI digits
@@ -1130,7 +1235,11 @@ impl State {
token = token.add(latch & 0xFFFF, latch >> 16);
bit_count += latch >> 16;
}
let latch_mode_bit_count: i32 = if mode == HighLevelEncoder::MODE_DIGIT { 4 } else { 5 };
let latch_mode_bit_count: i32 = if mode == HighLevelEncoder::MODE_DIGIT {
4
} else {
5
};
token = token.add(value, latch_mode_bit_count);
return State::new(&token, mode, 0, bit_count + latch_mode_bit_count);
}
@@ -1139,11 +1248,23 @@ impl State {
// to a different mode to output a single value.
fn shift_and_append(&self, mode: i32, value: i32) -> State {
let mut token: Token = self.token;
let this_mode_bit_count: i32 = if self.mode == HighLevelEncoder::MODE_DIGIT { 4 } else { 5 };
let this_mode_bit_count: i32 = if self.mode == HighLevelEncoder::MODE_DIGIT {
4
} else {
5
};
// Shifts exist only to UPPER and PUNCT, both with tokens size 5.
token = token.add(HighLevelEncoder::SHIFT_TABLE[self.mode][mode], this_mode_bit_count);
token = token.add(
HighLevelEncoder::SHIFT_TABLE[self.mode][mode],
this_mode_bit_count,
);
token = token.add(value, 5);
return State::new(&token, self.mode, 0, self.bitCount + this_mode_bit_count + 5);
return State::new(
&token,
self.mode,
0,
self.bitCount + this_mode_bit_count + 5,
);
}
// Create a new state representing this state, but an additional character
@@ -1158,8 +1279,22 @@ impl State {
bit_count += latch >> 16;
mode = HighLevelEncoder::MODE_UPPER;
}
let delta_bit_count: i32 = if (self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31) { 18 } else { if (self.binary_shift_byte_count == 62) { 9 } else { 8 } };
let mut result: State = State::new(&token, mode, self.binary_shift_byte_count + 1, bit_count + delta_bit_count);
let delta_bit_count: i32 =
if (self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31) {
18
} else {
if (self.binary_shift_byte_count == 62) {
9
} else {
8
}
};
let mut result: State = State::new(
&token,
mode,
self.binary_shift_byte_count + 1,
bit_count + delta_bit_count,
);
if result.binaryShiftByteCount == 2047 + 31 {
// The string is as long as it's allowed to be. We should end it.
result = result.end_binary_shift(index + 1);
@@ -1174,18 +1309,24 @@ impl State {
return self;
}
let mut token: Token = self.token;
token = token.add_binary_shift(index - self.binary_shift_byte_count, self.binary_shift_byte_count);
token = token.add_binary_shift(
index - self.binary_shift_byte_count,
self.binary_shift_byte_count,
);
return State::new(&token, self.mode, 0, self.bitCount);
}
// Returns true if "this" state is better (or equal) to be in than "that"
// state under all possible circumstances.
fn is_better_than_or_equal_to(&self, other: &State) -> bool {
let new_mode_bit_count: i32 = self.bitCount + (HighLevelEncoder::LATCH_TABLE[self.mode][other.mode] >> 16);
let new_mode_bit_count: i32 =
self.bitCount + (HighLevelEncoder::LATCH_TABLE[self.mode][other.mode] >> 16);
if self.binaryShiftByteCount < other.binaryShiftByteCount {
// add additional B/S encoding cost of other, if any
new_mode_bit_count += other.binaryShiftCost - self.binaryShiftCost;
} else if self.binaryShiftByteCount > other.binaryShiftByteCount && other.binaryShiftByteCount > 0 {
} else if self.binaryShiftByteCount > other.binaryShiftByteCount
&& other.binaryShiftByteCount > 0
{
// maximum possible additional cost (we end up exceeding the 31 byte boundary and other state can stay beneath it)
new_mode_bit_count += 10;
}
@@ -1220,7 +1361,12 @@ impl State {
}
pub fn to_string(&self) -> String {
return String::format("%s bits=%d bytes=%d", HighLevelEncoder::MODE_NAMES[self.mode], self.bit_count, self.binary_shift_byte_count);
return String::format(
"%s bits=%d bytes=%d",
HighLevelEncoder::MODE_NAMES[self.mode],
self.bit_count,
self.binary_shift_byte_count,
);
}
fn calculate_binary_shift_cost(binary_shift_byte_count: i32) -> i32 {