From 1035164fd75d8229c45aac6a1cf351d5a764d742 Mon Sep 17 00:00:00 2001 From: Henry Schimke Date: Wed, 17 Aug 2022 16:40:14 -0500 Subject: [PATCH] aztec red lines --- src/aztec.rs | 135 ++++++++++--------- src/aztec/decoder.rs | 110 ++++++---------- src/aztec/detector.rs | 238 +++++++++++++++++----------------- src/aztec/encoder.rs | 287 ++++++++++++++++++++--------------------- src/common.rs | 10 +- src/common/detector.rs | 22 ++-- src/lib.rs | 2 +- 7 files changed, 397 insertions(+), 407 deletions(-) diff --git a/src/aztec.rs b/src/aztec.rs index af92d38..6ef96f8 100644 --- a/src/aztec.rs +++ b/src/aztec.rs @@ -1,8 +1,8 @@ -pub mod decoder; +pub mod decoder; pub mod detector; pub mod encoder; -use crate::{ResultPoint,BarcodeFormat,EncodeHintType,Writer,Reader}; +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; @@ -25,20 +25,27 @@ pub struct AztecDetectorResult { nb_datablocks: i32, - nb_layers: i32 + nb_layers: i32, + + bits: BitMatrix, + + points: Vec, } impl DetectorResult for AztecDetectorResult { + fn get_bits(&self) -> BitMatrix { + return self.bits; + } + fn get_points(&self) -> Vec { + return self.points; + } } impl AztecDetectorResult { - pub fn new( bits: &BitMatrix, points: &Vec, compact: bool, nb_datablocks: i32, nb_layers: i32) -> AztecDetectorResult { - super(bits, points); - let .compact = compact; - let .nbDatablocks = nb_datablocks; - let .nbLayers = nb_layers; + pub fn new( bits: &BitMatrix, points: &Vec, 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 { @@ -73,20 +80,25 @@ impl Reader for AztecReader { * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded */ - pub fn decode(&self, image: &BinaryBitmap) -> /* throws NotFoundException, FormatException */Result> { + /*fn decode(&self, image: &BinaryBitmap) -> /* throws NotFoundException, FormatException */Result> { return Ok(self.decode(image, null)); - } + }*/ - pub fn decode(&self, image: &BinaryBitmap, hints: &Map) -> /* throws NotFoundException, FormatException */Result> { + fn decode(&self, image: &BinaryBitmap, hints: &Map) -> Result { let not_found_exception: NotFoundException = null; let format_exception: FormatException = null; let detector: Detector = Detector::new(&image.get_black_matrix()); let mut points: Vec = null; let decoder_result: DecoderResult = null; - let tryResult1 = 0; + + let detector_result: AztecDetectorResult = detector.detect(Some(false))?; + points = detector_result.get_points()?; + decoder_result = Decoder::new().decode(detector_result); + /* + let tryResult1 = 0; 'try1: loop { { - let detector_result: AztecDetectorResult = detector.detect(false); + let detector_result: AztecDetectorResult = detector.detect(Some(false)); points = detector_result.get_points(); decoder_result = Decoder::new().decode(detector_result); } @@ -123,11 +135,12 @@ impl Reader for AztecReader { } } + */ if hints != null { let rpcb: ResultPointCallback = hints.get(DecodeHintType::NEED_RESULT_POINT_CALLBACK) as ResultPointCallback; if rpcb != null { - for let point: ResultPoint in points { - rpcb.found_possible_result_point(point); + for point in points { + rpcb.found_possible_result_point(&point); } } } @@ -144,7 +157,7 @@ impl Reader for AztecReader { return Ok(result); } - pub fn reset(&self) { + fn reset(&self) { // do nothing } } @@ -159,11 +172,7 @@ pub struct AztecWriter { impl Writer for AztecWriter { - pub fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32) -> BitMatrix { - return ::encode(&contents, format, width, height, null); - } - - pub fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: &Map) -> BitMatrix { + fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: Option<&HashMap>) -> BitMatrix { // Do not add any ECI code by default let mut charset: Charset = null; let ecc_percent: i32 = Encoder::DEFAULT_EC_PERCENT; @@ -181,52 +190,58 @@ impl Writer for AztecWriter { } 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 { if format != BarcodeFormat::AZTEC { - throw IllegalArgumentException::new(format!("Can only encode AZTEC, but got {}", format)); + return Err( IllegalArgumentException::new(format!("Can only encode AZTEC, but got {}", format))); } let aztec: AztecCode = Encoder::encode(&contents, ecc_percent, layers, &charset); return ::render_result(aztec, width, height); - } + }*/ + +} + +impl AztecWriter { fn render_result( code: &AztecCode, width: i32, height: i32) -> BitMatrix { - let input: BitMatrix = code.get_matrix(); - if input == null { - throw IllegalStateException::new(); + let input: BitMatrix = code.get_matrix(); + if input == null { + return Err( IllegalStateException::new()); + } + let input_width: i32 = input.get_width(); + let input_height: i32 = input.get_height(); + let output_width: i32 = Math::max(width, input_width); + let output_height: i32 = Math::max(height, input_height); + let multiple: i32 = Math::min(output_width / input_width, output_height / input_height); + let left_padding: i32 = (output_width - (input_width * multiple)) / 2; + let top_padding: i32 = (output_height - (input_height * multiple)) / 2; + let output: BitMatrix = BitMatrix::new(output_width, output_height); + { + let input_y: i32 = 0; + let output_y: i32 = top_padding; + while input_y < input_height { + { + // Write the contents of this row of the barcode + { + let input_x: i32 = 0; + let output_x: i32 = left_padding; + while input_x < input_width { + { + if input.get(input_x, input_y) { + output.set_region(output_x, output_y, multiple, multiple); + } + } + input_x += 1; + output_x += multiple; + } + } + + } + input_y += 1; + output_y += multiple; + } } - let input_width: i32 = input.get_width(); - let input_height: i32 = input.get_height(); - let output_width: i32 = Math::max(width, input_width); - let output_height: i32 = Math::max(height, input_height); - let multiple: i32 = Math::min(output_width / input_width, output_height / input_height); - let left_padding: i32 = (output_width - (input_width * multiple)) / 2; - let top_padding: i32 = (output_height - (input_height * multiple)) / 2; - let output: BitMatrix = BitMatrix::new(output_width, output_height); - { - let input_y: i32 = 0, let output_y: i32 = top_padding; - while input_y < input_height { - { - // Write the contents of this row of the barcode - { - let input_x: i32 = 0, let output_x: i32 = left_padding; - while input_x < input_width { - { - if input.get(input_x, input_y) { - output.set_region(output_x, output_y, multiple, multiple); - } - } - input_x += 1; - output_x += multiple; - } - } - } - input_y += 1; - output_y += multiple; - } - } - - return output; - } + return output; + } } \ No newline at end of file diff --git a/src/aztec/decoder.rs b/src/aztec/decoder.rs index 60ea8a2..b12817d 100644 --- a/src/aztec/decoder.rs +++ b/src/aztec/decoder.rs @@ -1,4 +1,4 @@ -use create::FormatException; +use create::FormatException; use crate::aztec::AztecDetectorResult; use crate::common::{BitMatrix,CharacterSetECI,DecoderResult}; use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonException}; @@ -16,7 +16,7 @@ const UPPER_TABLE: vec![Vec; 32] = vec!["CTRL_PS", " ", "A", "B", "C", " const LOWER_TABLE: vec![Vec; 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; 32] = vec!["CTRL_PS", " ", "\1", "\2", "\3", "\4", "\5", "\6", "\7", "\b", "\t", "\n", "\13", "\f", "\r", "\33", "\34", "\35", "\36", "\37", "@", "\\", "^", "_", "`", "|", "~", "\177", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS", ] + const MIXED_TABLE: vec![Vec; 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; 32] = vec!["FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL", ] @@ -28,24 +28,26 @@ const UPPER_TABLE: vec![Vec; 32] = vec!["CTRL_PS", " ", "A", "B", "C", " const DEFAULT_ENCODING: Charset = StandardCharsets::ISO_8859_1; pub struct Decoder { - let mut ddata: AztecDetectorResult; + ddata: AztecDetectorResult +} + +enum Table { + + UPPER(), LOWER(), MIXED(), DIGIT(), PUNCT(), BINARY() } impl Decoder { - enum Table { + - UPPER(), LOWER(), MIXED(), DIGIT(), PUNCT(), BINARY() - } - - pub fn decode(&self, detector_result: &AztecDetectorResult) -> /* throws FormatException */Result> { + pub fn decode(&self, detector_result: &AztecDetectorResult) -> Result { self.ddata = detector_result; let matrix: BitMatrix = detector_result.get_bits(); - let rawbits: Vec = self.extract_bits(matrix); + let rawbits: Vec = self.extract_bits(&matrix); let corrected_bits: CorrectedBitsResult = self.correct_bits(&rawbits); let raw_bytes: Vec = ::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)); + 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); } @@ -123,17 +125,9 @@ impl Decoder { index += 3; // flush bytes, FLG changes state let tryResult1 = 0; - 'try1: loop { - { + result.append(&decoded_bytes.to_string(&encoding.name())); - } - break 'try1 - } - match tryResult1 { - catch ( uee: &UnsupportedEncodingException) { - throw IllegalStateException::new(&uee); - } 0 => break - } + decoded_bytes.reset(); match n { @@ -146,7 +140,7 @@ impl Decoder { 7 => { // FLG(7) is reserved and illegal - throw FormatException::get_format_instance(); + return Err( FormatException::get_format_instance()); } _ => { @@ -155,18 +149,18 @@ impl Decoder { if end_index - index < 4 * n { break; } - while n -= 1 !!!check!!! post decrement > 0 { + while (n -= 1) > 0 { let next_digit: i32 = ::read_code(&corrected_bits, index, 4); index += 4; if next_digit < 2 || next_digit > 11 { // Not a decimal digit - throw FormatException::get_format_instance(); + return Err( FormatException::get_format_instance()); } eci = eci * 10 + (next_digit - 2); } let charset_e_c_i: CharacterSetECI = CharacterSetECI::get_character_set_e_c_i_by_value(eci); if charset_e_c_i == null { - throw FormatException::get_format_instance(); + return Err( FormatException::get_format_instance()); } encoding = charset_e_c_i.get_charset(); } @@ -193,18 +187,9 @@ impl Decoder { } } } - let tryResult1 = 0; - 'try1: loop { - { + result.append(&decoded_bytes.to_string(&encoding.name())); - } - break 'try1 - } - match tryResult1 { - catch ( uee: &UnsupportedEncodingException) { - throw IllegalStateException::new(&uee); - } 0 => break - } + return Ok(result.to_string()); } @@ -275,26 +260,11 @@ impl Decoder { _ => { // Should not reach here. - throw IllegalStateException::new("Bad table"); + return Err( IllegalStateException::new("Bad table")); } } } - struct CorrectedBitsResult { - - let correct_bits: Vec; - - let ec_level: i32; - } - - impl CorrectedBitsResult { - - fn new( correct_bits: &Vec, ec_level: i32) -> CorrectedBitsResult { - let .correctBits = correct_bits; - let .ecLevel = ec_level; - } - } - /** *

Performs RS error correction on an array of bits.

@@ -302,7 +272,7 @@ impl Decoder { * @return the corrected array * @throws FormatException if the input contains too many errors */ - fn correct_bits(&self, rawbits: &Vec) -> /* throws FormatException */Result> { + fn correct_bits(&self, rawbits: &Vec) -> Result { let mut gf: GenericGF; let codeword_size: i32; if self.ddata.get_nb_layers() <= 2 { @@ -321,7 +291,7 @@ impl Decoder { let num_data_codewords: i32 = self.ddata.get_nb_datablocks(); let num_codewords: i32 = rawbits.len() / codeword_size; if num_codewords < num_data_codewords { - throw FormatException::get_format_instance(); + return Err( FormatException::get_format_instance()); } let mut offset: i32 = rawbits.len() % codeword_size; let data_words: [i32; num_codewords] = [0; num_codewords]; @@ -337,18 +307,10 @@ impl Decoder { } let tryResult1 = 0; - 'try1: loop { - { - let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(gf); + + let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(gf)?; rs_decoder.decode(&data_words, num_codewords - num_data_codewords); - } - break 'try1 - } - match tryResult1 { - catch ( ex: &ReedSolomonException) { - throw FormatException::get_format_instance(ex); - } 0 => break - } + // Now perform the unstuffing operation. // First, count how many bits are going to be thrown out as stuffing @@ -360,7 +322,7 @@ impl Decoder { { let data_word: i32 = data_words[i]; if data_word == 0 || data_word == mask { - throw FormatException::get_format_instance(); + return Err( FormatException::get_format_instance()); } else if data_word == 1 || data_word == mask - 1 { stuffed_bits += 1; } @@ -386,7 +348,7 @@ impl Decoder { let mut bit: i32 = codeword_size - 1; while bit >= 0 { { - corrected_bits[index += 1 !!!check!!! post increment] = (data_word & (1 << bit)) != 0; + corrected_bits[index += 1 ] = (data_word & (1 << bit)) != 0; } bit -= 1; } @@ -442,7 +404,8 @@ impl Decoder { } { - let mut i: i32 = 0, let row_offset: i32 = 0; + let mut i: i32 = 0; + let row_offset: i32 = 0; while i < layers { { let row_size: i32 = (layers - i) * 4 + ( if compact { 9 } else { 12 }); @@ -542,3 +505,16 @@ impl Decoder { } } +struct CorrectedBitsResult { + + correct_bits: Vec, + + ec_level: i32 +} + +impl CorrectedBitsResult { + + fn new( correct_bits: &Vec, ec_level: i32) -> Self { + Self { correct_bits: correct_bits, ec_level: ec_level } + } +} \ No newline at end of file diff --git a/src/aztec/detector.rs b/src/aztec/detector.rs index 139897c..dac8169 100644 --- a/src/aztec/detector.rs +++ b/src/aztec/detector.rs @@ -1,4 +1,4 @@ -use crate::{NotFoundException,ResultPoint}; +use crate::{NotFoundException,ResultPoint}; use crate::aztec::AztecDetectorResult; use crate::common::{BitMatrix,GridSampler}; use crate::common::detector::{MathUtils,WhiteRectangleDetector}; @@ -21,27 +21,26 @@ const EXPECTED_CORNER_BITS: vec![Vec; 4] = vec![// 07340 XXX .XX X.. ... ; pub struct Detector { - let image: BitMatrix; + image: BitMatrix, - let mut compact: bool; + compact: bool, - let nb_layers: i32; + nb_layers: i32, - let nb_data_blocks: i32; + nb_data_blocks: i32, - let nb_center_layers: i32; + nb_center_layers: i32, - let mut shift: i32; + shift: i32 } impl Detector { - pub fn new( image: &BitMatrix) -> Detector { - let .image = image; - } + pub fn new( image: &BitMatrix) -> Self { + let new_d : Self; + new_d.image = image; - pub fn detect(&self) -> /* throws NotFoundException */Result> { - return Ok(self.detect(false)); + new_d } /** @@ -51,24 +50,24 @@ 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: bool) -> /* throws NotFoundException */Result> { + pub fn detect(&self, is_mirror: Option) -> Result { // 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 // [topRight, bottomRight, bottomLeft, topLeft] - let bulls_eye_corners: Vec = self.get_bulls_eye_corners(p_center); - if is_mirror { + let bulls_eye_corners: Vec = self.get_bulls_eye_corners(&p_center); + if is_mirror.unwrap_or(false) { let temp: ResultPoint = bulls_eye_corners[0]; bulls_eye_corners[0] = bulls_eye_corners[2]; bulls_eye_corners[2] = temp; } // 3. Get the size of the matrix and other parameters from the bull's eye - self.extract_parameters(bulls_eye_corners); + 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 = self.get_matrix_corner_points(bulls_eye_corners); - return Ok(AztecDetectorResult::new(bits, corners, self.compact, self.nb_data_blocks, self.nb_layers)); + let corners: Vec = self.get_matrix_corner_points(&bulls_eye_corners); + return Ok(AztecDetectorResult::new(&bits, &corners, self.compact, self.nb_data_blocks, self.nb_layers)); } /** @@ -77,17 +76,17 @@ 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) -> /* throws NotFoundException */Result> { + fn extract_parameters(&self, bulls_eye_corners: &Vec) -> 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]) { - throw NotFoundException::get_not_found_instance(); + 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; 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[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), ] ; // bullsEyeCorners[shift] is the corner of the bulls'eye that has three // orientation marks. @@ -127,9 +126,11 @@ impl Detector { self.nb_layers = (corrected_data >> 11) + 1; self.nb_data_blocks = (corrected_data & 0x7FF) + 1; } + + Ok(()) } - fn get_rotation( sides: &Vec, length: i32) -> /* throws NotFoundException */Result> { + fn get_rotation( sides: &Vec, length: i32) -> Result { // In a normal pattern, we expect to See // ** .* D A // * * @@ -140,7 +141,7 @@ impl Detector { // Grab the 3 bits from each of the sides the form the locator pattern and concatenate // into a 12-bit integer. Start with the bit at A let corner_bits: i32 = 0; - for let side: i32 in sides { + for side in sides { // XX......X where X's are orientation marks let t: i32 = ((side >> (length - 2)) << 1) + (side & 1); corner_bits = (corner_bits << 3) + t; @@ -162,7 +163,7 @@ impl Detector { } } - throw NotFoundException::get_not_found_instance(); + return Err(NotFoundException::get_not_found_instance()); } /** @@ -196,11 +197,11 @@ impl Detector { } let tryResult1 = 0; - 'try1: loop { - { + /*'try1: loop { + {*/ let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(GenericGF::AZTEC_PARAM); rs_decoder.decode(¶meter_words, num_e_c_codewords); - } + /*} break 'try1 } match tryResult1 { @@ -208,6 +209,7 @@ impl Detector { throw NotFoundException::get_not_found_instance(); } 0 => break } + */ // Toss the error correction. Just return the data as an integer let mut result: i32 = 0; @@ -243,13 +245,13 @@ impl Detector { self.nb_center_layers = 1; while self.nb_center_layers < 9 { { - let pouta: Point = self.get_first_different(pina, color, 1, -1); - let poutb: Point = self.get_first_different(pinb, color, 1, 1); - let poutc: Point = self.get_first_different(pinc, color, -1, 1); - let poutd: Point = self.get_first_different(pind, color, -1, -1); + let pouta: Point = self.get_first_different(&pina, color, 1, -1); + let poutb: Point = self.get_first_different(&pinb, color, 1, 1); + 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) { + if q < 0.75 || q > 1.25 || !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd) { break; } } @@ -264,17 +266,17 @@ impl Detector { } if self.nb_center_layers != 5 && self.nb_center_layers != 7 { - throw NotFoundException::get_not_found_instance(); + return Err( NotFoundException::get_not_found_instance()); } self.compact = self.nb_center_layers == 5; // Expand the square by .5 pixel in each direction so that we're on the border // between the white square and the black square - let pinax: ResultPoint = ResultPoint::new(pina.get_x() + 0.5f, pina.get_y() - 0.5f); - let pinbx: ResultPoint = ResultPoint::new(pinb.get_x() + 0.5f, pinb.get_y() + 0.5f); - let pincx: ResultPoint = ResultPoint::new(pinc.get_x() - 0.5f, pinc.get_y() + 0.5f); - let pindx: ResultPoint = ResultPoint::new(pind.get_x() - 0.5f, pind.get_y() - 0.5f); + let pinax: ResultPoint = ResultPoint::new(pina.get_x() + 0.5f32, pina.get_y() - 0.5f32); + let pinbx: ResultPoint = ResultPoint::new(pinb.get_x() + 0.5f32, pinb.get_y() + 0.5f32); + 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![ResultPoint; 4] = vec![pinax, pinbx, pincx, pindx, ] + return Ok(::expand_square( vec![pinax, pinbx, pincx, pindx, ] , 2 * self.nb_center_layers - 3, 2 * self.nb_center_layers)); } @@ -290,54 +292,48 @@ impl Detector { let point_d: ResultPoint; //Get a white rectangle that can be the border of the matrix in center bull's eye or let tryResult1 = 0; - 'try1: loop { - { - let corner_points: Vec = WhiteRectangleDetector::new(self.image).detect(); + + let corner_points_detector = WhiteRectangleDetector::new(&self.image, None, None, None); + if corner_points_detector.is_ok() { + + let corner_points: Vec = corner_points_detector.detect(); + point_a = corner_points[0]; point_b = corner_points[1]; point_c = corner_points[2]; point_d = corner_points[3]; - } - break 'try1 - } - match tryResult1 { - catch ( e: &NotFoundException) { - 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(); - } 0 => break + }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(); } //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.0f); - let mut cy: i32 = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f); + 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; - 'try1: loop { - { - let corner_points: Vec = WhiteRectangleDetector::new(self.image, 15, cx, cy).detect(); + + let corner_points_wrd = WhiteRectangleDetector::new(&self.image, Some(15), Some(cx), Some(cy)); + if corner_points_wrd.is_ok() { + let corner_points: Vec = corner_points_wrd.detect(); point_a = corner_points[0]; point_b = corner_points[1]; point_c = corner_points[2]; point_d = corner_points[3]; - } - break 'try1 - } - match tryResult1 { - catch ( e: &NotFoundException) { - 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(); - } 0 => break + } 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(); } // 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.0f); - cy = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f); + 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); } @@ -359,8 +355,8 @@ impl Detector { fn sample_grid(&self, image: &BitMatrix, top_left: &ResultPoint, top_right: &ResultPoint, bottom_right: &ResultPoint, bottom_left: &ResultPoint) -> /* throws NotFoundException */Result> { let sampler: GridSampler = GridSampler::get_instance(); let dimension: i32 = self.get_dimension(); - let low: f32 = dimension / 2.0f - self.nb_center_layers; - let high: f32 = dimension / 2.0f + self.nb_center_layers; + 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 low, // topleft low, // topright @@ -409,10 +405,10 @@ 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; @@ -436,7 +432,7 @@ impl Detector { */ fn get_color(&self, p1: &Point, p2: &Point) -> i32 { let d: f32 = ::distance(p1, p2); - if d == 0.0f { + if d == 0.0f32 { return 0; } let dx: f32 = (p2.get_x() - p1.get_x()) / d; @@ -461,10 +457,10 @@ impl Detector { } let err_ratio: f32 = error / d; - if err_ratio > 0.1f && err_ratio < 0.9f { + if err_ratio > 0.1f32 && err_ratio < 0.9f32 { return 0; } - return if (err_ratio <= 0.1f) == color_model { 1 } else { -1 }; + return if (err_ratio <= 0.1f32) == color_model { 1 } else { -1 }; } /** @@ -499,28 +495,28 @@ impl Detector { * @return the corners of the expanded square */ fn expand_square( corner_points: &Vec, old_side: i32, new_side: i32) -> Vec { - let ratio: f32 = new_side / (2.0f * old_side); + 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(); - let mut centerx: f32 = (corner_points[0].get_x() + corner_points[2].get_x()) / 2.0f; - let mut centery: f32 = (corner_points[0].get_y() + corner_points[2].get_y()) / 2.0f; + let mut centerx: f32 = (corner_points[0].get_x() + corner_points[2].get_x()) / 2.0f32; + let mut centery: f32 = (corner_points[0].get_y() + corner_points[2].get_y()) / 2.0f32; let result0: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy); let result2: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy); dx = corner_points[1].get_x() - corner_points[3].get_x(); dy = corner_points[1].get_y() - corner_points[3].get_y(); - centerx = (corner_points[1].get_x() + corner_points[3].get_x()) / 2.0f; - centery = (corner_points[1].get_y() + corner_points[3].get_y()) / 2.0f; + centerx = (corner_points[1].get_x() + corner_points[3].get_x()) / 2.0f32; + 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![ResultPoint; 4] = vec![result0, result1, result2, result3, ] + return vec![result0, result1, result2, result3, ] ; } - fn is_valid(&self, x: i32, y: i32) -> bool { + fn is_valid_coords(&self, x: i32, y: i32) -> bool { return x >= 0 && x < self.image.get_width() && y >= 0 && y < self.image.get_height(); } - fn is_valid(&self, point: &ResultPoint) -> bool { + fn is_valid_rp(&self, point: &ResultPoint) -> bool { let x: i32 = MathUtils::round(&point.get_x()); let y: i32 = MathUtils::round(&point.get_y()); return self.is_valid(x, y); @@ -541,36 +537,36 @@ impl Detector { return 4 * self.nb_layers + 2 * ((2 * self.nb_layers + 6) / 15) + 15; } - struct Point { - - let x: i32; - - let y: i32; - } - - impl Point { - - fn to_result_point(&self) -> ResultPoint { - return ResultPoint::new(self.x, self.y); - } - - fn new( x: i32, y: i32) -> Point { - let .x = x; - let .y = y; - } - - fn get_x(&self) -> i32 { - return self.x; - } - - fn get_y(&self) -> i32 { - return self.y; - } - - pub fn to_string(&self) -> String { - return format!("<{} {}>", self.x, self.y); - } - } + } +struct Point { + + x: i32, + + y: i32 +} + +impl Point { + + fn to_result_point(&self) -> ResultPoint { + return ResultPoint::new(self.x, self.y); + } + + fn new( x: i32, y: i32) -> Self { + Self { x: x, y: y } + } + + fn get_x(&self) -> i32 { + return self.x; + } + + fn get_y(&self) -> i32 { + return self.y; + } + + pub fn to_string(&self) -> String { + return format!("<{} {}>", self.x, self.y); + } +} \ No newline at end of file diff --git a/src/aztec/encoder.rs b/src/aztec/encoder.rs index 1109331..f6590f7 100644 --- a/src/aztec/encoder.rs +++ b/src/aztec/encoder.rs @@ -1,4 +1,7 @@ -use crate::common::{BitArray,BitMatrix,CharacterSetECI}; +use std::cmp::Ordering; +use std::fmt::format; + +use crate::common::{BitArray,BitMatrix,CharacterSetECI}; use crate::common::reedsolomon::{GenericGF,ReedSolomonEncoder}; // Token.java @@ -6,13 +9,13 @@ const EMPTY: Token = SimpleToken::new(null, 0, 0); pub trait Token { - fn new( previous: &Token) -> Token { + fn new( previous: &Token) -> Token ; /*{ let .previous = previous; - } + }*/ - fn get_previous(&self) -> Token { + fn get_previous(&self) -> Token ; /*{ return self.previous; - } + }*/ fn add(&self, value: i32, bit_count: i32) -> Token { return SimpleToken::new(self, value, bit_count); @@ -34,15 +37,15 @@ pub trait Token { */ pub struct AztecCode { - let compact: bool; + compact: bool, - let size: i32; + size: i32, - let layers: i32; + layers: i32, - let code_words: i32; + code_words: i32, - let matrix: BitMatrix; + matrix: BitMatrix } impl AztecCode { @@ -204,9 +207,9 @@ 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, min_e_c_c_percent: i32, user_specified_layers: i32, charset: &Charset) -> AztecCode { + pub fn encode( data: &Vec, 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(); + let bits: BitArray = HighLevelEncoder::new(&data, charset).encode(); // stuff bits and choose symbol size let ecc_bits: i32 = bits.get_size() * min_e_c_c_percent / 100 + 11; let total_size_bits: i32 = bits.get_size() + ecc_bits; @@ -219,18 +222,18 @@ impl Encoder { compact = user_specified_layers < 0; layers = Math::abs(user_specified_layers); if layers > ( if compact { MAX_NB_BITS_COMPACT } else { MAX_NB_BITS }) { - throw IllegalArgumentException::new(&String::format("Illegal value %s for layers", user_specified_layers)); + 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); stuffed_bits = ::stuff_bits(bits, word_size); if stuffed_bits.get_size() + ecc_bits > usable_bits_in_layers { - throw 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 - throw IllegalArgumentException::new("Data to large for user specified layer"); + return Err( IllegalArgumentException::new("Data to large for user specified layer")); } } else { word_size = 0; @@ -241,7 +244,7 @@ impl Encoder { loop { { if i > MAX_NB_BITS { - throw 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 }; @@ -310,7 +313,8 @@ impl Encoder { let matrix: BitMatrix = BitMatrix::new(matrix_size); // draw data bits { - let mut i: i32 = 0, let row_offset: i32 = 0; + let mut i: i32 = 0; + let row_offset: i32 = 0; while i < layers { { let row_size: i32 = (layers - i) * 4 + ( if compact { 9 } else { 12 }); @@ -359,7 +363,8 @@ impl Encoder { } else { ::draw_bulls_eye(matrix, matrix_size / 2, 7); { - let mut i: i32 = 0, let mut j: i32 = 0; + let mut i: i32 = 0; + let mut j: i32 = 0; while i < base_matrix_size / 2 - 1 { { { @@ -387,7 +392,7 @@ impl Encoder { aztec.set_size(matrix_size); aztec.set_layers(layers); aztec.set_code_words(message_size_in_words); - aztec.set_matrix(matrix); + aztec.set_matrix(&matrix); return aztec; } @@ -497,7 +502,7 @@ impl Encoder { let start_pad: i32 = total_bits % word_size; let message_bits: BitArray = BitArray::new(); message_bits.append_bits(0, start_pad); - for let message_word: i32 in message_words { + for message_word in message_words { message_bits.append_bits(message_word, word_size); } return message_bits; @@ -556,7 +561,7 @@ impl Encoder { } _ => { - throw IllegalArgumentException::new(format!("Unsupported word size {}", word_size)); + return Err( IllegalArgumentException::new(format!("Unsupported word size {}", word_size))); } } } @@ -606,15 +611,16 @@ impl Encoder { // BinaryShiftToken.java struct BinaryShiftToken { - super: Token; + //super: Token; + previous: dyn Token, - let binary_shift_start: i32; + binary_shift_start: i32, - let binary_shift_byte_count: i32; + binary_shift_byte_count: i32 } impl Token for BinaryShiftToken { - pub fn append_to(&self, bit_array: &BitArray, text: &Vec) { + fn append_to(&self, bit_array: &BitArray, text: &Vec) { let bsbc: i32 = self.binary_shift_byte_count; { let mut i: i32 = 0; @@ -643,17 +649,15 @@ impl Token for BinaryShiftToken { } - pub fn to_string(&self) -> String { + fn to_string(&self) -> String { 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) -> BinaryShiftToken { - super(previous); - let .binaryShiftStart = binary_shift_start; - let .binaryShiftByteCount = binary_shift_byte_count; + fn new( previous: &Token, binary_shift_start: i32, binary_shift_byte_count: i32) -> Self { + Self{ previous, binary_shift_start, binary_shift_byte_count} } @@ -733,79 +737,76 @@ const MODE_NAMES: vec![Vec; 5] = vec!["UPPER", "LOWER", "DIGIT", "MIXED" const SHIFT_TABLE: [[i32; 6]; 6] = [[0; 6]; 6]; pub struct HighLevelEncoder { - let text: Vec; + text: Vec, - let mut charset: Charset; + charset: Charset } impl HighLevelEncoder { - static { + pub fn new( text: &Vec, charset: Option<&Charset>) -> Self { CHAR_MAP[MODE_UPPER][' '] = 1; - { - let mut c: i32 = 'A'; - while c <= 'Z' { - { - CHAR_MAP[MODE_UPPER][c] = c - 'A' + 2; - } - c += 1; - } - } + { + let mut c: i32 = 'A'; + while c <= 'Z' { + { + CHAR_MAP[MODE_UPPER][c] = c - 'A' + 2; + } + c += 1; + } + } - CHAR_MAP[MODE_LOWER][' '] = 1; - { - let mut c: i32 = 'a'; - while c <= 'z' { - { - CHAR_MAP[MODE_LOWER][c] = c - 'a' + 2; - } - c += 1; - } - } + CHAR_MAP[MODE_LOWER][' '] = 1; + { + let mut c: i32 = 'a'; + while c <= 'z' { + { + CHAR_MAP[MODE_LOWER][c] = c - 'a' + 2; + } + c += 1; + } + } - CHAR_MAP[MODE_DIGIT][' '] = 1; - { - let mut c: i32 = '0'; - while c <= '9' { - { - CHAR_MAP[MODE_DIGIT][c] = c - '0' + 2; - } - c += 1; - } - } + CHAR_MAP[MODE_DIGIT][' '] = 1; + { + let mut c: i32 = '0'; + while c <= '9' { + { + CHAR_MAP[MODE_DIGIT][c] = c - '0' + 2; + } + c += 1; + } + } - CHAR_MAP[MODE_DIGIT][','] = 12; - CHAR_MAP[MODE_DIGIT]['.'] = 13; - let mixed_table: vec![Vec; 28] = vec!['\0', ' ', '\1', '\2', '\3', '\4', '\5', '\6', '\7', '\b', '\t', '\n', '\13', '\f', '\r', '\33', '\34', '\35', '\36', '\37', '@', '\\', '^', '_', '`', '|', '~', '\177', ] - ; - { - let mut i: i32 = 0; - while i < mixed_table.len() { - { - CHAR_MAP[MODE_MIXED][mixed_table[i]] = i; - } - i += 1; - } - } + CHAR_MAP[MODE_DIGIT][','] = 12; + CHAR_MAP[MODE_DIGIT]['.'] = 13; + let mixed_table: vec![Vec; 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() { + { + CHAR_MAP[MODE_MIXED][mixed_table[i]] = i; + } + i += 1; + } + } - let punct_table: vec![Vec; 31] = vec!['\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', ] - ; - { - let mut i: i32 = 0; - while i < punct_table.len() { - { - if punct_table[i] > 0 { - CHAR_MAP[MODE_PUNCT][punct_table[i]] = i; - } - } - i += 1; - } - } + let punct_table: vec![Vec; 31] = vec!['\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', ] + ; + { + let mut i: i32 = 0; + while i < punct_table.len() { + { + if punct_table[i] > 0 { + CHAR_MAP[MODE_PUNCT][punct_table[i]] = i; + } + } + i += 1; + } + } - } - - static { - for let table: Vec in SHIFT_TABLE { + for table in SHIFT_TABLE { Arrays::fill(&table, -1); } SHIFT_TABLE[MODE_UPPER][MODE_PUNCT] = 0; @@ -814,16 +815,8 @@ impl HighLevelEncoder { SHIFT_TABLE[MODE_MIXED][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15; - } - pub fn new( text: &Vec) -> HighLevelEncoder { - let .text = text; - let .charset = null; - } - - pub fn new( text: &Vec, charset: &Charset) -> HighLevelEncoder { - let .text = text; - let .charset = charset; + Self { text: text, charset: charset } } /** @@ -834,7 +827,7 @@ impl HighLevelEncoder { if self.charset != null { let eci: CharacterSetECI = CharacterSetECI::get_character_set_e_c_i(&self.charset); if null == eci { - throw 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()); } @@ -886,12 +879,22 @@ impl HighLevelEncoder { } // We are left with a set of states. Find the shortest one. - let min_state: State = Collections::min(&states, Comparator::new() { + let min_state = states.iter().min_by(|a,b| { + let c = a.get_bit_count() - b.get_bit_count(); + if c > 0 { + Ordering::Greater + } else if c < 0 { + Ordering::Less + }else { + Ordering::Equal + } + }).unwrap(); + /*let min_state: State = Collections::min(&states, Comparator::new() { pub fn compare(&self, a: &State, b: &State) -> i32 { return a.get_bit_count() - b.get_bit_count(); } - }); + });*/ // Convert it to a bit array, and return. return min_state.to_bit_array(&self.text); } @@ -899,9 +902,9 @@ impl HighLevelEncoder { // We update a set of states for a new character by updating each state // for the new character, merging the results, and then removing the // non-optimal states. - fn update_state_list_for_char(&self, states: &Iterable, index: i32) -> Collection { - let result: Collection = LinkedList<>::new(); - for let state: State in states { + fn update_state_list_for_char(&self, states: &Vec, index: i32) -> Vec { + let result: Vec = Vec::new(); + for state in states { self.update_state_for_char(state, index, &result); } return ::simplify_states(&result); @@ -910,7 +913,7 @@ impl HighLevelEncoder { // Return a set of states that represent the possible ways of updating this // state for the next character. The resulting set of states are added to // the "result" list. - fn update_state_for_char(&self, state: &State, index: i32, result: &Collection) { + fn update_state_for_char(&self, state: &State, index: i32, result: &Vec) { let ch: char = (self.text[index] & 0xFF) as char; let char_in_current_table: bool = CHAR_MAP[state.get_mode()][ch] > 0; let state_no_binary: State = null; @@ -955,15 +958,15 @@ impl HighLevelEncoder { } } - fn update_state_list_for_pair( states: &Iterable, index: i32, pair_code: i32) -> Collection { - let result: Collection = LinkedList<>::new(); - for let state: State in states { + fn update_state_list_for_pair( states: &Iterable, index: i32, pair_code: i32) -> Vec { + let result: Collection = Vec::new(); + for state in states { ::update_state_for_pair(state, index, pair_code, &result); } return ::simplify_states(&result); } - fn update_state_for_pair( state: &State, index: i32, pair_code: i32, result: &Collection) { + fn update_state_for_pair( state: &State, index: i32, pair_code: i32, result: &Vec) { let state_no_binary: State = state.end_binary_shift(index); // Possibility 1. Latch to MODE_PUNCT, and then append this code result.add(&state_no_binary.latch_and_append(MODE_PUNCT, pair_code)); @@ -988,8 +991,8 @@ impl HighLevelEncoder { } fn simplify_states( states: &Iterable) -> Collection { - let result: Deque = LinkedList<>::new(); - for let new_state: State in states { + let result: Deque = Vec::new(); + for new_state in states { let mut add: bool = true; { let iterator: Iterator = result.iterator(); @@ -999,7 +1002,7 @@ impl HighLevelEncoder { add = false; break; } - if new_state.is_better_than_or_equal_to(old_state) { + if new_state.is_better_than_or_equal_to(&old_state) { iterator.remove(); } } @@ -1015,12 +1018,13 @@ impl HighLevelEncoder { // SimpleToken.java struct SimpleToken { - super: Token; + //super: Token; + previous :dyn Token, // For normal words, indicates value and bitCount - let value: i16; + value: i16, - let bit_count: i16; + bit_count: i16, } impl Token for SimpleToken { @@ -1028,19 +1032,18 @@ impl Token for SimpleToken { bit_array.append_bits(self.value, self.bit_count); } - pub fn to_string(&self) -> String { + fn to_string(&self) -> String { let mut value: i32 = self.value & ((1 << self.bit_count) - 1); value |= 1 << self.bit_count; - return '<' + Integer::to_binary_string(value | (1 << self.bit_count))::substring(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) -> SimpleToken { - super(previous); - let .value = value as i16; - let .bitCount = bit_count as i16; + fn new( previous: &Token, value: i32, bit_count: i32) -> Self { + Self { previous, value, bit_count } } } @@ -1057,30 +1060,26 @@ struct State { // The current mode of the encoding (or the mode to which we'll return if // we're in Binary Shift mode. - let mode: i32; + mode: i32, // The list of tokens that we output. If we are in Binary Shift mode, this // token list does *not* yet included the token for those bytes - let token: Token; + token: Token, // If non-zero, the number of most recent bytes that should be output // in Binary Shift mode. - let binary_shift_byte_count: i32; + binary_shift_byte_count: i32, // The total number of bits generated (including Binary Shift). - let bit_count: i32; + bit_count: i32, - let binary_shift_cost: i32; + binary_shift_cost: i32 } impl State { - fn new( token: &Token, mode: i32, binary_bytes: i32, bit_count: i32) -> State { - let .token = token; - let .mode = mode; - let .binaryShiftByteCount = binary_bytes; - let .bitCount = bit_count; - let .binaryShiftCost = ::calculate_binary_shift_cost(binary_bytes); + 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) } } fn get_mode(&self) -> i32 { @@ -1108,17 +1107,17 @@ impl State { // 0: FNC1 token = token.add(0, 3); } else if eci > 999999 { - throw 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 = Integer::to_string(eci)::get_bytes(StandardCharsets::ISO_8859_1); + let eci_digits: Vec = eci.to_string().as_bytes();//Integer::to_string(eci)::get_bytes(StandardCharsets::ISO_8859_1); // 1-6: number of ECI digits token = token.add(eci_digits.len(), 3); - for let eci_digit: i8 in eci_digits { + for eci_digit in eci_digits { token = token.add(eci_digit - '0' + 2, 4); } bits_added += eci_digits.len() * 4; } - return State::new(token, self.mode, 0, self.bit_count + bits_added); + return State::new(&token, self.mode, 0, self.bit_count + bits_added); } // Create a new state representing this state with a latch to a (not @@ -1133,7 +1132,7 @@ impl State { } 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); + return State::new(&token, mode, 0, bit_count + latch_mode_bit_count); } // Create a new state representing this state, with a temporary shift @@ -1144,7 +1143,7 @@ impl State { // 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(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 @@ -1160,7 +1159,7 @@ impl State { 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 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); @@ -1176,7 +1175,7 @@ impl State { } let mut token: Token = self.token; 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); + return State::new(&token, self.mode, 0, self.bitCount); } // Returns true if "this" state is better (or equal) to be in than "that" @@ -1194,7 +1193,7 @@ impl State { } fn to_bit_array(&self, text: &Vec) -> BitArray { - let symbols: List = ArrayList<>::new(); + let symbols: List = Vec::new(); { let mut token: Token = self.end_binary_shift(text.len()).token; while token != null { diff --git a/src/common.rs b/src/common.rs index b69d79b..741fea8 100644 --- a/src/common.rs +++ b/src/common.rs @@ -2168,7 +2168,8 @@ impl GridSampler for DefaultGridSampler { * * @author Sean Owen */ -pub struct DetectorResult { + +/* pub struct DetectorResult { bits: BitMatrix, points: Vec, @@ -2190,6 +2191,13 @@ impl DetectorResult { return self.points; } } +*/ + +pub trait DetectorResult { + //pub fn new(bits: &BitMatrix, points: &Vec) -> Self; + pub fn get_bits(&self) -> BitMatrix; + pub fn get_points(&self) -> Vec; +} // ECIEncoderSet.java /** diff --git a/src/common/detector.rs b/src/common/detector.rs index 7a566ea..d253f9b 100644 --- a/src/common/detector.rs +++ b/src/common/detector.rs @@ -386,15 +386,6 @@ pub struct WhiteRectangleDetector { } impl WhiteRectangleDetector { - pub fn new(image: &BitMatrix) -> Result { - this( - image, - INIT_SIZE, - image.get_width() / 2, - image.get_height() / 2, - ) - } - /** * @param image barcode image to find a rectangle in * @param initSize initial size of search area around center @@ -404,22 +395,27 @@ impl WhiteRectangleDetector { */ pub fn new( image: &BitMatrix, - init_size: i32, - x: i32, - y: i32, + init_size: Option, + x_in: Option, + y_in: Option, ) -> Result { let mut new_wrd: Self; + let x = x_in.unwrap_or(image.get_width() / 2); + let y = y_in.unwrap_or(image.get_height() / 2); + new_wrd.image = image; new_wrd.height = image.get_height(); new_wrd.width = image.get_width(); - let halfsize: i32 = init_size / 2; + let halfsize: i32 = init_size.unwrap_or(INIT_SIZE) / 2; new_wrd.left_init = x - halfsize; new_wrd.right_init = x + halfsize; new_wrd.up_init = y - halfsize; new_wrd.down_init = y + halfsize; + if up_init < 0 || left_init < 0 || down_init >= height || right_init >= width { return Err(NotFoundException::get_not_found_instance()); } + Ok(new_wrd) } diff --git a/src/lib.rs b/src/lib.rs index a10a9d1..9c9d853 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -798,7 +798,7 @@ pub trait Writer { * @return {@link BitMatrix} representing encoded barcode image * @throws WriterException if contents cannot be encoded legally in a format */ - fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: &HashMap) -> Result ; + fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: Option<&HashMap>) -> Result ; }