decode tests pass

This commit is contained in:
Henry Schimke
2022-12-26 11:38:54 -06:00
parent f07d546083
commit 9d215d9f99
6 changed files with 406 additions and 300 deletions

View File

@@ -27,6 +27,7 @@ num = "0.4.0"
[dev-dependencies] [dev-dependencies]
java-properties = "1.4.1" java-properties = "1.4.1"
java-rand = "0.2.0"
[features] [features]
default = ["image"] default = ["image"]

View File

@@ -59,13 +59,14 @@ impl MultipleBarcodeReader for QRCodeMultiReader {
)?; )?;
let mut points = detectorRXingResult.getPoints().clone(); let mut points = detectorRXingResult.getPoints().clone();
// If the code was mirrored: swap the bottom-left and the top-right points. // If the code was mirrored: swap the bottom-left and the top-right points.
if let Some( other) = decoderRXingResult.getOther(){ if let Some(other) = decoderRXingResult.getOther() {
if other.is::<QRCodeDecoderMetaData>() { if other.is::<QRCodeDecoderMetaData>() {
(other (other
.downcast::<QRCodeDecoderMetaData>() .downcast::<QRCodeDecoderMetaData>()
.expect("must downcast to QRCodeDecoderMetaData")) .expect("must downcast to QRCodeDecoderMetaData"))
.applyMirroredCorrection(&mut points); .applyMirroredCorrection(&mut points);
}} }
}
// if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) { // if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) {
// ((QRCodeDecoderMetaData) decoderRXingResult.getOther()).applyMirroredCorrection(points); // ((QRCodeDecoderMetaData) decoderRXingResult.getOther()).applyMirroredCorrection(points);
// } // }

View File

@@ -180,9 +180,13 @@ pub fn decode(codewords: &[u32], ecLevel: &str) -> Result<DecoderRXingResult, Ex
} }
} }
} }
result = result.build_result();
if result.is_empty() && resultMetadata.getFileId().is_empty() { if result.is_empty() && resultMetadata.getFileId().is_empty() {
return Err(Exceptions::FormatException("".to_owned())); return Err(Exceptions::FormatException("".to_owned()));
} }
let mut decoderRXingResult = DecoderRXingResult::new( let mut decoderRXingResult = DecoderRXingResult::new(
Vec::new(), Vec::new(),
result.to_string(), result.to_string(),
@@ -254,36 +258,43 @@ pub fn decodeMacroBlock(
MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME => { MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME => {
let mut fileName = ECIStringBuilder::new(); let mut fileName = ECIStringBuilder::new();
codeIndex = textCompaction(codewords, codeIndex + 1, &mut fileName)?; codeIndex = textCompaction(codewords, codeIndex + 1, &mut fileName)?;
fileName = fileName.build_result();
resultMetadata.setFileName(fileName.to_string()); resultMetadata.setFileName(fileName.to_string());
} }
MACRO_PDF417_OPTIONAL_FIELD_SENDER => { MACRO_PDF417_OPTIONAL_FIELD_SENDER => {
let mut sender = ECIStringBuilder::new(); let mut sender = ECIStringBuilder::new();
codeIndex = textCompaction(codewords, codeIndex + 1, &mut sender)?; codeIndex = textCompaction(codewords, codeIndex + 1, &mut sender)?;
sender = sender.build_result();
resultMetadata.setSender(sender.to_string()); resultMetadata.setSender(sender.to_string());
} }
MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE => { MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE => {
let mut addressee = ECIStringBuilder::new(); let mut addressee = ECIStringBuilder::new();
codeIndex = textCompaction(codewords, codeIndex + 1, &mut addressee)?; codeIndex = textCompaction(codewords, codeIndex + 1, &mut addressee)?;
addressee = addressee.build_result();
resultMetadata.setAddressee(addressee.to_string()); resultMetadata.setAddressee(addressee.to_string());
} }
MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT => { MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT => {
let mut segmentCount = ECIStringBuilder::new(); let mut segmentCount = ECIStringBuilder::new();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut segmentCount)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut segmentCount)?;
segmentCount = segmentCount.build_result();
resultMetadata.setSegmentCount(segmentCount.to_string().parse().unwrap()); resultMetadata.setSegmentCount(segmentCount.to_string().parse().unwrap());
} }
MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP => { MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP => {
let mut timestamp = ECIStringBuilder::new(); let mut timestamp = ECIStringBuilder::new();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut timestamp)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut timestamp)?;
timestamp = timestamp.build_result();
resultMetadata.setTimestamp(timestamp.to_string().parse().unwrap()); resultMetadata.setTimestamp(timestamp.to_string().parse().unwrap());
} }
MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM => { MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM => {
let mut checksum = ECIStringBuilder::new(); let mut checksum = ECIStringBuilder::new();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut checksum)?;
checksum = checksum.build_result();
resultMetadata.setChecksum(checksum.to_string().parse().unwrap()); resultMetadata.setChecksum(checksum.to_string().parse().unwrap());
} }
MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE => { MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE => {
let mut fileSize = ECIStringBuilder::new(); let mut fileSize = ECIStringBuilder::new();
codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?; codeIndex = numericCompaction(codewords, codeIndex + 1, &mut fileSize)?;
fileSize = fileSize.build_result();
resultMetadata.setFileSize(fileSize.to_string().parse().unwrap()); resultMetadata.setFileSize(fileSize.to_string().parse().unwrap());
} }
_ => return Err(Exceptions::FormatException("".to_owned())), _ => return Err(Exceptions::FormatException("".to_owned())),

View File

@@ -14,31 +14,31 @@
* limitations under the License. * limitations under the License.
*/ */
use encoding::{EncodingRef, Encoding}; use encoding::{Encoding, EncodingRef};
use rand::{self, Rng}; use java_rand;
use rand::rngs::ThreadRng;
use crate::pdf417::PDF417RXingResultMetadata;
use crate::pdf417::decoder::decoded_bit_stream_parser; use crate::pdf417::decoder::decoded_bit_stream_parser;
use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction}; use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction};
use crate::pdf417::PDF417RXingResultMetadata;
/** /**
* Tests {@link DecodedBitStreamParser}. * Tests {@link DecodedBitStreamParser}.
*/ */
/**
* Tests the first sample given in ISO/IEC 15438:2015(E) - Annex H.4
*/
#[test]
fn testStandardSample1() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes: [u32; 23] = [
20, 928, 111, 100, 17, 53, 923, 1, 111, 104, 923, 3, 64, 416, 34, 923, 4, 258, 446, 67,
// we should never reach these
1000, 1000, 1000,
];
/** decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata)
* Tests the first sample given in ISO/IEC 15438:2015(E) - Annex H.4 .expect("decode");
*/
#[test]
fn testStandardSample1() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes:[u32;23] = [20, 928, 111, 100, 17, 53, 923, 1, 111, 104, 923, 3, 64, 416, 34, 923, 4, 258, 446, 67,
// we should never reach these
1000, 1000, 1000];
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2,&mut resultMetadata);
assert_eq!(0, resultMetadata.getSegmentIndex()); assert_eq!(0, resultMetadata.getSegmentIndex());
assert_eq!("017053", resultMetadata.getFileId()); assert_eq!("017053", resultMetadata.getFileId());
@@ -48,23 +48,30 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
assert_eq!("ISO CH", resultMetadata.getAddressee()); assert_eq!("ISO CH", resultMetadata.getAddressee());
let optionalData = resultMetadata.getOptionalData(); let optionalData = resultMetadata.getOptionalData();
assert_eq!( 1, optionalData[0],"first element of optional array should be the first field identifier");
assert_eq!( assert_eq!(
67, optionalData[optionalData.len() - 1],"last element of optional array should be the last codeword of the last field"); 1, optionalData[0],
} "first element of optional array should be the first field identifier"
);
assert_eq!(
67,
optionalData[optionalData.len() - 1],
"last element of optional array should be the last codeword of the last field"
);
}
/**
* Tests the second given in ISO/IEC 15438:2015(E) - Annex H.4
*/
#[test]
fn testStandardSample2() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes: [u32; 14] = [
11, 928, 111, 103, 17, 53, 923, 1, 111, 104, 922, // we should never reach these
1000, 1000, 1000,
];
/** decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata)
* Tests the second given in ISO/IEC 15438:2015(E) - Annex H.4 .expect("decode");
*/
#[test]
fn testStandardSample2() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes :[u32;14]= [11, 928, 111, 103, 17, 53, 923, 1, 111, 104, 922,
// we should never reach these
1000, 1000, 1000];
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata);
assert_eq!(3, resultMetadata.getSegmentIndex()); assert_eq!(3, resultMetadata.getSegmentIndex());
assert_eq!("017053", resultMetadata.getFileId()); assert_eq!("017053", resultMetadata.getFileId());
@@ -73,24 +80,28 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
assert!(resultMetadata.getAddressee().is_empty()); assert!(resultMetadata.getAddressee().is_empty());
assert!(resultMetadata.getSender().is_empty()); assert!(resultMetadata.getSender().is_empty());
let optionalData = resultMetadata.getOptionalData(); let optionalData = resultMetadata.getOptionalData();
assert_eq!( 1, optionalData[0],"first element of optional array should be the first field identifier");
assert_eq!( assert_eq!(
104, optionalData[optionalData.len() - 1],"last element of optional array should be the last codeword of the last field"); 1, optionalData[0],
} "first element of optional array should be the first field identifier"
);
assert_eq!(
104,
optionalData[optionalData.len() - 1],
"last element of optional array should be the last codeword of the last field"
);
}
/**
* Tests the example given in ISO/IEC 15438:2015(E) - Annex H.6
*/
#[test]
fn testStandardSample3() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes = [7_u32, 928, 111, 100, 100, 200, 300, 0]; // Final dummy ECC codeword required to avoid ArrayIndexOutOfBounds
/** decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata)
* Tests the example given in ISO/IEC 15438:2015(E) - Annex H.6 .expect("decode");
*/
#[test]
fn testStandardSample3() {
let mut resultMetadata = PDF417RXingResultMetadata::default();
let sampleCodes = [7_u32, 928, 111, 100, 100, 200, 300,
0]; // Final dummy ECC codeword required to avoid ArrayIndexOutOfBounds
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata);
assert_eq!(0, resultMetadata.getSegmentIndex()); assert_eq!(0, resultMetadata.getSegmentIndex());
assert_eq!("100200300", resultMetadata.getFileId()); assert_eq!("100200300", resultMetadata.getFileId());
@@ -103,17 +114,20 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
// Check that symbol containing no data except Macro is accepted (see note in Annex H.2) // Check that symbol containing no data except Macro is accepted (see note in Annex H.2)
let decoderRXingResult = decoded_bit_stream_parser::decode(&sampleCodes, "0").expect("decode"); let decoderRXingResult = decoded_bit_stream_parser::decode(&sampleCodes, "0").expect("decode");
assert_eq!("", decoderRXingResult.getText()); assert_eq!("", decoderRXingResult.getText());
assert!(!decoderRXingResult.getOther().is_some()); assert!(decoderRXingResult.getOther().is_some());
} }
#[test] #[test]
fn testSampleWithFilename() { fn testSampleWithFilename() {
let sampleCodes = [23_u32, 477, 928, 111, 100, 0, 252, 21, 86, 923, 0, 815, 251, 133, 12, 148, 537, 593, let sampleCodes = [
599, 923, 1, 111, 102, 98, 311, 355, 522, 920, 779, 40, 628, 33, 749, 267, 506, 213, 928, 465, 248, 23_u32, 477, 928, 111, 100, 0, 252, 21, 86, 923, 0, 815, 251, 133, 12, 148, 537, 593, 599,
493, 72, 780, 699, 780, 493, 755, 84, 198, 628, 368, 156, 198, 809, 19, 113]; 923, 1, 111, 102, 98, 311, 355, 522, 920, 779, 40, 628, 33, 749, 267, 506, 213, 928, 465,
let mut resultMetadata = PDF417RXingResultMetadata::default(); 248, 493, 72, 780, 699, 780, 493, 755, 84, 198, 628, 368, 156, 198, 809, 19, 113,
];
let mut resultMetadata = PDF417RXingResultMetadata::default();
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata).expect("decode"); decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata)
.expect("decode");
assert_eq!(0, resultMetadata.getSegmentIndex()); assert_eq!(0, resultMetadata.getSegmentIndex());
assert_eq!("000252021086", resultMetadata.getFileId()); assert_eq!("000252021086", resultMetadata.getFileId());
@@ -122,80 +136,91 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
assert!(resultMetadata.getAddressee().is_empty()); assert!(resultMetadata.getAddressee().is_empty());
assert!(resultMetadata.getSender().is_empty()); assert!(resultMetadata.getSender().is_empty());
assert_eq!("filename.txt", resultMetadata.getFileName()); assert_eq!("filename.txt", resultMetadata.getFileName());
} }
#[test] #[test]
fn testSampleWithNumericValues() { fn testSampleWithNumericValues() {
let sampleCodes = [25_u32, 477, 928, 111, 100, 0, 252, 21, 86, 923, 2, 2, 0, 1, 0, 0, 0, 923, 5, 130, 923, let sampleCodes = [
6, 1, 500, 13, 0]; 25_u32, 477, 928, 111, 100, 0, 252, 21, 86, 923, 2, 2, 0, 1, 0, 0, 0, 923, 5, 130, 923, 6,
let mut resultMetadata = PDF417RXingResultMetadata::default(); 1, 500, 13, 0,
];
let mut resultMetadata = PDF417RXingResultMetadata::default();
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata).expect("decode"); decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata)
.expect("decode");
assert_eq!(0, resultMetadata.getSegmentIndex()); assert_eq!(0, resultMetadata.getSegmentIndex());
assert_eq!("000252021086", resultMetadata.getFileId()); assert_eq!("000252021086", resultMetadata.getFileId());
assert!( !resultMetadata.isLastSegment() ); assert!(!resultMetadata.isLastSegment());
assert_eq!(180980729000000, resultMetadata.getTimestamp()); assert_eq!(180980729000000, resultMetadata.getTimestamp());
assert_eq!(30, resultMetadata.getFileSize()); assert_eq!(30, resultMetadata.getFileSize());
assert_eq!(260013, resultMetadata.getChecksum()); assert_eq!(260013, resultMetadata.getChecksum());
} }
#[test] #[test]
fn testSampleWithMacroTerminatorOnly() { fn testSampleWithMacroTerminatorOnly() {
let sampleCodes = [7_u32, 477, 928, 222, 198, 0, 922]; let sampleCodes = [7_u32, 477, 928, 222, 198, 0, 922];
let mut resultMetadata = PDF417RXingResultMetadata::default(); let mut resultMetadata = PDF417RXingResultMetadata::default();
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata).expect("decode"); decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 3, &mut resultMetadata)
.expect("decode");
assert_eq!(99998, resultMetadata.getSegmentIndex()); assert_eq!(99998, resultMetadata.getSegmentIndex());
assert_eq!("000", resultMetadata.getFileId()); assert_eq!("000", resultMetadata.getFileId());
assert!(resultMetadata.isLastSegment()); assert!(resultMetadata.isLastSegment());
assert_eq!(-1, resultMetadata.getSegmentCount()); assert_eq!(-1, resultMetadata.getSegmentCount());
assert!(resultMetadata.getOptionalData().is_empty()); assert!(resultMetadata.getOptionalData().is_empty());
} }
#[test] #[test]
#[should_panic] #[should_panic]
fn testSampleWithBadSequenceIndexMacro() { fn testSampleWithBadSequenceIndexMacro() {
let sampleCodes = [3_u32, 928, 222, 0]; let sampleCodes = [3_u32, 928, 222, 0];
let mut resultMetadata = PDF417RXingResultMetadata::default(); let mut resultMetadata = PDF417RXingResultMetadata::default();
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata).expect("decode"); decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata)
} .expect("decode");
}
#[test] #[test]
#[should_panic] #[should_panic]
fn testSampleWithNoFileIdMacro() { fn testSampleWithNoFileIdMacro() {
let sampleCodes = [4_u32, 928, 222, 198, 0]; let sampleCodes = [4_u32, 928, 222, 198, 0];
let mut resultMetadata = PDF417RXingResultMetadata::default(); let mut resultMetadata = PDF417RXingResultMetadata::default();
decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata).expect("decode"); decoded_bit_stream_parser::decodeMacroBlock(&sampleCodes, 2, &mut resultMetadata)
} .expect("decode");
}
#[test] #[test]
#[should_panic] #[should_panic]
fn testSampleWithNoDataNoMacro() { fn testSampleWithNoDataNoMacro() {
let sampleCodes = [3_u32, 899, 899, 0]; let sampleCodes = [3_u32, 899, 899, 0];
decoded_bit_stream_parser::decode(&sampleCodes, "0").expect("decode"); decoded_bit_stream_parser::decode(&sampleCodes, "0").expect("decode");
} }
#[test] #[test]
fn testUppercase() { fn testUppercase() {
//encodeDecode("", 0); //encodeDecode("", 0);
performEncodeTest('A', &[ 3, 4, 5, 6, 4, 4, 5, 5]); performEncodeTest('A', &[3, 4, 5, 6, 4, 4, 5, 5]);
} }
#[test] #[test]
fn testNumeric() { fn testNumeric() {
performEncodeTest('1', &[ 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10]); performEncodeTest(
} '1',
&[
2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10,
],
);
}
#[test] #[test]
fn testByte(){ fn testByte() {
performEncodeTest('\u{00c4}', &[ 3, 4, 5, 6, 7, 7, 8]); performEncodeTest('\u{00c4}', &[3, 4, 5, 6, 7, 7, 8]);
} }
#[test] #[test]
fn testUppercaseLowercaseMix1(){ fn testUppercaseLowercaseMix1() {
encodeDecodeWithLength("aA", 4); encodeDecodeWithLength("aA", 4);
encodeDecodeWithLength("aAa", 5); encodeDecodeWithLength("aAa", 5);
encodeDecodeWithLength("Aa", 4); encodeDecodeWithLength("Aa", 4);
@@ -206,249 +231,315 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
encodeDecodeWithLength("AaAaA", 5); encodeDecodeWithLength("AaAaA", 5);
encodeDecodeWithLength("AaaAaaA", 6); encodeDecodeWithLength("AaaAaaA", 6);
encodeDecodeWithLength("AaaAAaaA", 7); encodeDecodeWithLength("AaaAAaaA", 7);
} }
#[test] #[test]
fn testPunctuation(){ fn testPunctuation() {
performEncodeTest(';', &[ 3, 4, 5, 6, 6, 7, 8]); performEncodeTest(';', &[3, 4, 5, 6, 6, 7, 8]);
encodeDecodeWithLength(";;;;;;;;;;;;;;;;", 17); encodeDecodeWithLength(";;;;;;;;;;;;;;;;", 17);
} }
#[test] #[test]
fn testUppercaseLowercaseMix2(){ fn testUppercaseLowercaseMix2() {
performPermutationTest(&['A', 'a'], 10, 8972); performPermutationTest(&['A', 'a'], 10, 8972);
} }
#[test] #[test]
fn testUppercaseNumericMix() { fn testUppercaseNumericMix() {
performPermutationTest(&['A', '1'], 14, 192510); performPermutationTest(&['A', '1'], 14, 192510);
} }
#[test] #[test]
fn testUppercaseMixedMix() { fn testUppercaseMixedMix() {
performPermutationTest(&['A', '1', ' ', ';'], 7, 106060); performPermutationTest(&['A', '1', ' ', ';'], 7, 106060);
} }
#[test] #[test]
fn testUppercasePunctuationMix(){ fn testUppercasePunctuationMix() {
performPermutationTest(&['A', ';'], 10, 8967); performPermutationTest(&['A', ';'], 10, 8967);
} }
#[test] #[test]
fn testUppercaseByteMix() { fn testUppercaseByteMix() {
performPermutationTest(&['A', '\u{00c4}'], 10, 11222); performPermutationTest(&['A', '\u{00c4}'], 10, 11222);
} }
#[test] #[test]
fn testLowercaseByteMix(){ fn testLowercaseByteMix() {
performPermutationTest(&['a', '\u{00c4}'], 10, 11233); performPermutationTest(&['a', '\u{00c4}'], 10, 11233);
} }
#[test] #[test]
fn testUppercaseLowercaseNumericMix(){ fn testUppercaseLowercaseNumericMix() {
performPermutationTest(&['A', 'a', '1'], 7, 15491); performPermutationTest(&['A', 'a', '1'], 7, 15491);
} }
#[test] #[test]
fn testUppercaseLowercasePunctuationMix() { fn testUppercaseLowercasePunctuationMix() {
performPermutationTest(&['A', 'a', ';'], 7, 15491); performPermutationTest(&['A', 'a', ';'], 7, 15491);
} }
#[test] #[test]
fn testUppercaseLowercaseByteMix() { fn testUppercaseLowercaseByteMix() {
performPermutationTest(&['A', 'a', '\u{00c4}'], 7, 17288); performPermutationTest(&['A', 'a', '\u{00c4}'], 7, 17288);
} }
#[test] #[test]
fn testLowercasePunctuationByteMix(){ fn testLowercasePunctuationByteMix() {
performPermutationTest(&['a', ';', '\u{00c4}'], 7, 17427); performPermutationTest(&['a', ';', '\u{00c4}'], 7, 17427);
} }
#[test] #[test]
fn testUppercaseLowercaseNumericPunctuationMix(){ fn testUppercaseLowercaseNumericPunctuationMix() {
performPermutationTest(&['A', 'a', '1', ';'], 7, 120479); performPermutationTest(&['A', 'a', '1', ';'], 7, 120479);
} }
#[test] #[test]
fn testBinaryData() { fn testBinaryData() {
// let bytes = [0_u8;500]; let mut bytes = [0_u8; 500];
// let random = rand::thread_rng(); // let random = rand::thread_rng();
let mut random = java_rand::Random::new(0);
let mut total = 0; let mut total = 0;
for i in 0..10000 { for _i in 0..10000 {
// for (int i = 0; i < 10000; i++) { // for (int i = 0; i < 10000; i++) {
let bytes = gen_500_random_bytes(); // let bytes = gen_500_random_bytes();
random.next_bytes(&mut bytes);
total += encodeDecode(&encoding::all::ISO_8859_1.decode(&bytes, encoding::DecoderTrap::Strict).expect("decode bytes"));
total += encodeDecode(
&encoding::all::ISO_8859_1
.decode(&bytes, encoding::DecoderTrap::Strict)
.expect("decode bytes"),
);
} }
assert_eq!(4190044, total); assert_eq!(4190044, total);
} }
fn gen_500_random_bytes() -> [u8;500] { // fn gen_500_random_bytes() -> [u8;500] {
let mut bytes = [0_u8;500]; // let mut bytes = [0_u8;500];
let mut random = rand::thread_rng(); // let mut random = rand::thread_rng();
for i in 0..500 { // for i in 0..500 {
bytes[i] = random.gen(); // bytes[i] = random.gen();
} // }
bytes // bytes
} // }
#[test] #[test]
fn testECIEnglishHiragana(){ fn testECIEnglishHiragana() {
//multi ECI UTF-8, UTF-16 and ISO-8859-1 //multi ECI UTF-8, UTF-16 and ISO-8859-1
performECITest(&['a', '1', '\u{3040}'], &mut [20.0, 1.0, 10.0], 105825, 110914); performECITest(
} &['a', '1', '\u{3040}'],
&mut [20.0, 1.0, 10.0],
105825,
110914,
);
}
#[test] #[test]
fn testECIEnglishKatakana() { fn testECIEnglishKatakana() {
//multi ECI UTF-8, UTF-16 and ISO-8859-1 //multi ECI UTF-8, UTF-16 and ISO-8859-1
performECITest(&['a', '1', '\u{30a0}'], &mut [20.0, 1.0, 10.0], 109177, 110914); performECITest(
} &['a', '1', '\u{30a0}'],
&mut [20.0, 1.0, 10.0],
109177,
110914,
);
}
#[test] #[test]
fn testECIEnglishHalfWidthKatakana(){ fn testECIEnglishHalfWidthKatakana() {
//single ECI //single ECI
performECITest(&['a', '1', '\u{ff80}'], &mut [20.0, 1.0, 10.0], 80617, 110914); performECITest(
} &['a', '1', '\u{ff80}'],
&mut [20.0, 1.0, 10.0],
80617,
110914,
);
}
#[test] #[test]
fn testECIEnglishChinese() { fn testECIEnglishChinese() {
//single ECI //single ECI
performECITest(&['a', '1', '\u{4e00}'], &mut [20.0, 1.0, 10.0], 95797, 110914); performECITest(
} &['a', '1', '\u{4e00}'],
&mut [20.0, 1.0, 10.0],
95797,
110914,
);
}
#[test] #[test]
fn testECIGermanCyrillic(){ fn testECIGermanCyrillic() {
//single ECI since the German Umlaut is in ISO-8859-1 //single ECI since the German Umlaut is in ISO-8859-1
performECITest(&['a', '1', '\u{00c4}', '\u{042f}'], &mut [20.0, 1.0, 1.0, 10.0], 80755, 96007); performECITest(
} &['a', '1', '\u{00c4}', '\u{042f}'],
&mut [20.0, 1.0, 1.0, 10.0],
80755,
96007,
);
}
#[test] #[test]
fn testECIEnglishCzechCyrillic1() { fn testECIEnglishCzechCyrillic1() {
//multi ECI between ISO-8859-2 and ISO-8859-5 //multi ECI between ISO-8859-2 and ISO-8859-5
performECITest(&['a', '1', '\u{010c}', '\u{042f}'], &mut [10.0, 1.0, 10.0, 10.0], 102824, 124525); performECITest(
} &['a', '1', '\u{010c}', '\u{042f}'],
&mut [10.0, 1.0, 10.0, 10.0],
102824,
124525,
);
}
#[test] #[test]
fn testECIEnglishCzechCyrillic2() { fn testECIEnglishCzechCyrillic2() {
//multi ECI between ISO-8859-2 and ISO-8859-5 //multi ECI between ISO-8859-2 and ISO-8859-5
performECITest(&['a', '1', '\u{010c}', '\u{042f}'], &mut [40.0, 1.0, 10.0, 10.0], 81321, 88236); performECITest(
} &['a', '1', '\u{010c}', '\u{042f}'],
&mut [40.0, 1.0, 10.0, 10.0],
81321,
88236,
);
}
#[test] #[test]
fn testECIEnglishArabicCyrillic() { fn testECIEnglishArabicCyrillic() {
//multi ECI between UTF-8 (ISO-8859-6 is excluded in CharacterSetECI) and ISO-8859-5 //multi ECI between UTF-8 (ISO-8859-6 is excluded in CharacterSetECI) and ISO-8859-5
performECITest(&['a', '1', '\u{0620}', '\u{042f}'], &mut [10.0, 1.0, 10.0, 10.0], 118510, 124525); performECITest(
} &['a', '1', '\u{0620}', '\u{042f}'],
&mut [10.0, 1.0, 10.0, 10.0],
118510,
124525,
);
}
#[test] #[test]
fn testBinaryMultiECI() { fn testBinaryMultiECI() {
//Test the cases described in 5.5.5.3 "ECI and Byte Compaction mode using latch 924 and 901" //Test the cases described in 5.5.5.3 "ECI and Byte Compaction mode using latch 924 and 901"
performDecodeTest(&[5, 927, 4, 913, 200], "\u{010c}"); performDecodeTest(&[5, 927, 4, 913, 200], "\u{010c}");
performDecodeTest(&[9, 927, 4, 913, 200, 927, 7, 913, 207], "\u{010c}\u{042f}"); performDecodeTest(&[9, 927, 4, 913, 200, 927, 7, 913, 207], "\u{010c}\u{042f}");
performDecodeTest(&[9, 927, 4, 901, 200, 927, 7, 901, 207], "\u{010c}\u{042f}"); performDecodeTest(&[9, 927, 4, 901, 200, 927, 7, 901, 207], "\u{010c}\u{042f}");
performDecodeTest(&[8, 927, 4, 901, 200, 927, 7, 207], "\u{010c}\u{042f}"); performDecodeTest(&[8, 927, 4, 901, 200, 927, 7, 207], "\u{010c}\u{042f}");
performDecodeTest(&[14, 927, 4, 901, 200, 927, 7, 207, 927, 4, 200, 927, 7, 207], performDecodeTest(
"\u{010c}\u{042f}\u{010c}\u{042f}"); &[14, 927, 4, 901, 200, 927, 7, 207, 927, 4, 200, 927, 7, 207],
"\u{010c}\u{042f}\u{010c}\u{042f}",
);
performDecodeTest(&[16, 927, 4, 924, 336, 432, 197, 51, 300, 927, 7, 348, 231, 311, 858, 567], performDecodeTest(&[16, 927, 4, 924, 336, 432, 197, 51, 300, 927, 7, 348, 231, 311, 858, 567],
"\u{010c}\u{010c}\u{010c}\u{010c}\u{010c}\u{010c}\u{042f}\u{042f}\u{042f}\u{042f}\u{042f}\u{042f}"); "\u{010c}\u{010c}\u{010c}\u{010c}\u{010c}\u{010c}\u{042f}\u{042f}\u{042f}\u{042f}\u{042f}\u{042f}");
} }
fn encodeDecodeWithLength( input:&str, expectedLength:u32) { fn encodeDecodeWithLength(input: &str, expectedLength: u32) {
assert_eq!(expectedLength, encodeDecode(input)); assert_eq!(expectedLength, encodeDecode(input));
} }
fn encodeDecode( input:&str) -> u32 { fn encodeDecode(input: &str) -> u32 {
return encodeDecodeWithAll(input, None, false, true); return encodeDecodeWithAll(input, None, false, true);
} }
fn encodeDecodeWithAll( input:&str, charset:Option<EncodingRef>, autoECI:bool, decode:bool) fn encodeDecodeWithAll(
-> u32 { input: &str,
let s = pdf_417_high_level_encoder_test_adapter::encodeHighLevel(input, Compaction::AUTO, charset, autoECI).expect("encode"); charset: Option<EncodingRef>,
autoECI: bool,
decode: bool,
) -> u32 {
let s = pdf_417_high_level_encoder_test_adapter::encodeHighLevel(
input,
Compaction::AUTO,
charset,
autoECI,
)
.expect("encode");
if decode { if decode {
let mut codewords = vec![0_u32;s.chars().count() + 1]; let mut codewords = vec![0_u32; s.chars().count() + 1];
codewords[0] = codewords.len() as u32; codewords[0] = codewords.len() as u32;
for i in 1..codewords.len() { for i in 1..codewords.len() {
// for (int i = 1; i < codewords.length; i++) { // for (int i = 1; i < codewords.length; i++) {
codewords[i] = s.chars().nth(i - 1).unwrap() as u32; codewords[i] = s.chars().nth(i - 1).unwrap() as u32;
} }
performDecodeTest(&codewords, input); performDecodeTest(&codewords, input);
} }
s.chars().count() as u32 + 1 s.chars().count() as u32 + 1
} }
fn getEndIndex( length:u32, chars:&[char]) -> u32{ fn getEndIndex(length: u32, chars: &[char]) -> u32 {
let decimalLength : f64 = (chars.len() as f64).log10(); //Math.log10(chars.length); let decimalLength: f64 = (chars.len() as f64).log10(); //Math.log10(chars.length);
(decimalLength*length as f64).powi(10).ceil() as u32 10_f64.powf((decimalLength * length as f64)).ceil() as u32
// (decimalLength*length as f64).powi(10).ceil() as u32
// (decimalLength*length as f64).powi(10).ceil() as u32
// Math.ceil(Math.pow(10, decimalLength * length)) // Math.ceil(Math.pow(10, decimalLength * length))
} }
fn generatePermutation( index:u32, length:u32, chars:&[char]) -> String{ fn generatePermutation(index: u32, length: u32, chars: &[char]) -> String {
let N = chars.len() as u32; let N = chars.len();
// let baseNNumber = Integer.toString(index, N); // let baseNNumber = Integer.toString(index, N);
let mut baseNNumber= int_to_string(index,N); let mut baseNNumber = int_to_string(index, N);
while baseNNumber.chars().count() < length as usize { while baseNNumber.chars().count() < length as usize {
baseNNumber.insert(0, '0'); baseNNumber.insert(0, '0');
// baseNNumber = "0" + baseNNumber; // baseNNumber = "0" + baseNNumber;
} }
let mut prefix = String::from(""); let mut prefix = String::from("");
for ch in baseNNumber.chars() { for ch in baseNNumber.chars() {
prefix.push(chars[ch as usize - '0' as usize]); prefix.push(chars[(ch as isize - '0' as isize) as usize]);
} }
// for i in 0..baseNNumber.chars().count() { // for i in 0..baseNNumber.chars().count() {
// // for (int i = 0; i < baseNNumber.length(); i++) { // // for (int i = 0; i < baseNNumber.length(); i++) {
// prefix += chars[baseNNumber.charAt(i) - '0']; // prefix += chars[baseNNumber.charAt(i) - '0'];
// } // }
prefix prefix
} }
fn performPermutationTest( chars:&[char], length:u32, expectedTotal:u32) { fn performPermutationTest(chars: &[char], length: u32, expectedTotal: u32) {
let endIndex = getEndIndex(length, chars); let endIndex = getEndIndex(length, chars);
let mut total = 0; let mut total = 0;
for i in 0..endIndex { for i in 0..endIndex {
// for (int i = 0; i < endIndex; i++) { // for (int i = 0; i < endIndex; i++) {
total += encodeDecode(&generatePermutation(i, length, chars)); total += encodeDecode(&generatePermutation(i, length, chars));
} }
assert_eq!(expectedTotal, total); assert_eq!(expectedTotal, total);
} }
fn performEncodeTest( c:char, expectedLengths:&[u32]) { fn performEncodeTest(c: char, expectedLengths: &[u32]) {
for i in 0..expectedLengths.len() { for i in 0..expectedLengths.len() {
// for (int i = 0; i < expectedLengths.length; i++) { // for (int i = 0; i < expectedLengths.length; i++) {
let mut sb = String::new();//new StringBuilder(); let mut sb = String::new(); //new StringBuilder();
for j in 0..=i { for _j in 0..=i {
// for (int j = 0; j <= i; j++) { // for (int j = 0; j <= i; j++) {
sb.push(c); sb.push(c);
} }
encodeDecodeWithLength(&sb, expectedLengths[i]); encodeDecodeWithLength(&sb, expectedLengths[i]);
} }
} }
fn performDecodeTest(codewords:&[u32], expectedRXingResult:&str) { fn performDecodeTest(codewords: &[u32], expectedRXingResult: &str) {
let result = decoded_bit_stream_parser::decode(codewords, "0").expect("decode"); let result = decoded_bit_stream_parser::decode(codewords, "0").expect("decode");
assert_eq!(expectedRXingResult, result.getText()); assert_eq!(expectedRXingResult, result.getText());
} }
fn performECITest( chars:&[char], fn performECITest(
weights:&mut [f32], chars: &[char],
expectedMinLength:u32, weights: &mut [f32],
expectedUTFLength:u32) { expectedMinLength: u32,
let mut random = rand::thread_rng(); expectedUTFLength: u32,
) {
let mut random = java_rand::Random::new(0);
let mut minLength = 0; let mut minLength = 0;
let mut utfLength = 0; let mut utfLength = 0;
for i in 0..1000 { for _i in 0..1000 {
// for (int i = 0; i < 1000; i++) { // for (int i = 0; i < 1000; i++) {
let s = generateText(&mut random, 100, chars, weights); let s = generateText(&mut random, 100, chars, weights);
minLength += encodeDecodeWithAll(&s, None, true, true); minLength += encodeDecodeWithAll(&s, None, true, true);
utfLength += encodeDecodeWithAll(&s, Some(encoding::all::UTF_8), false, true); utfLength += encodeDecodeWithAll(&s, Some(encoding::all::UTF_8), false, true);
} }
assert_eq!(expectedMinLength, minLength); assert_eq!(expectedMinLength, minLength);
assert_eq!(expectedUTFLength, utfLength); assert_eq!(expectedUTFLength, utfLength);
} }
fn generateText( random:&mut ThreadRng, maxWidth:u32, chars:&[char], weights:&mut [f32]) -> String{ fn generateText(
let mut result = String::new();//new StringBuilder(); random: &mut java_rand::Random,
maxWidth: u32,
chars: &[char],
weights: &mut [f32],
) -> String {
let mut result = String::new(); //new StringBuilder();
let maxWordWidth = 7; let maxWordWidth = 7;
let mut total = 0.0; let mut total = 0.0;
// for (int i = 0; i < weights.length; i++) { // for (int i = 0; i < weights.length; i++) {
@@ -457,47 +548,47 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
total += weights.iter().sum::<f32>(); total += weights.iter().sum::<f32>();
for i in 0..weights.len() { for i in 0..weights.len() {
// for (int i = 0; i < weights.length; i++) { // for (int i = 0; i < weights.length; i++) {
weights[i] /= total; weights[i] /= total;
} }
let mut cnt = 0; let mut cnt = 0;
loop { loop {
let mut maxValue = 0.0; let mut maxValue = 0.0;
let mut maxIndex = 0; let mut maxIndex = 0;
for j in 0..weights.len() { for j in 0..weights.len() {
// for (int j = 0; j < weights.length; j++) { // for (int j = 0; j < weights.length; j++) {
let value = random.gen::<f32>() * weights[j]; let value = random.next_f32() * weights[j];
if value > maxValue { if value > maxValue {
maxValue = value; maxValue = value;
maxIndex = j; maxIndex = j;
}
} }
} let wordLength = maxWordWidth as f32 * random.next_f32();
let wordLength = (maxWordWidth as f32 * random.gen::<f32>()) as i32; if wordLength > 0.0 && result.chars().count() > 0 {
if wordLength > 0 && result.chars().count() > 0 { result.push(' ');
result.push(' ');
}
for j in 0..wordLength {
// for (int j = 0; j < wordLength; j++) {
let mut c = chars[maxIndex];
if j == 0 && c >= 'a' && c <= 'z' && random.gen::<bool>() {
c = char::from_u32(c as u32- 'a' as u32 + 'A' as u32).unwrap();
} }
result.push(c); for j in 0..wordLength.ceil() as u32 {
} // for (int j = 0; j < wordLength; j++) {
if cnt % 2 != 0 && random.gen_bool(0.51) { let mut c = chars[maxIndex];
result.push('.'); if j == 0 && c >= 'a' && c <= 'z' && random.next_bool() {
} c = char::from_u32(c as u32 - 'a' as u32 + 'A' as u32).unwrap();
cnt+=1; }
result.push(c);
}
if cnt % 2 != 0 && random.next_bool() {
result.push('.');
}
cnt += 1;
if !(result.chars().count() < (maxWidth as isize - maxWordWidth as isize) as usize) { break } if !(result.chars().count() < (maxWidth as isize - maxWordWidth as isize) as usize) {
break;
}
} //while (result.length() < maxWidth - maxWordWidth); } //while (result.length() < maxWidth - maxWordWidth);
result result
} }
fn int_to_string(x: u32, radix: usize) -> String {
fn int_to_string(x: u32, radix: u32) -> String {
let mut x = x;
// Handle the special case of 0 // Handle the special case of 0
if x == 0 { if x == 0 {
return "0".to_string(); return "0".to_string();
@@ -506,12 +597,12 @@ use crate::pdf417::encoder::{pdf_417_high_level_encoder_test_adapter, Compaction
// Build the string by repeatedly dividing the number by the radix and // Build the string by repeatedly dividing the number by the radix and
// adding the remainder to the beginning of the string // adding the remainder to the beginning of the string
let mut s = String::new(); let mut s = String::new();
let mut x = x as usize;
while x > 0 { while x > 0 {
let remainder = (x % radix) as u8; let remainder = (x % radix) as u8;
s = (remainder as char).to_string() + &s; s = (remainder).to_string() + &s;
x /= radix; x /= radix;
} }
s s
} }

View File

@@ -316,10 +316,11 @@ pub fn encodeHighLevel(
} }
}; //.getBytes(encoding))}; }; //.getBytes(encoding))};
// if let Some(byts) = bytes { // if let Some(byts) = bytes {
let bytes_ok = if let Some(_) = bytes { true } else { false }; let bytes_ok = bytes.is_some(); //if let Some(_) = bytes { true } else { false };
if ((bytes_ok && b == 1) if (bytes_ok && b == 1)
|| (!bytes_ok && bytes.as_ref().unwrap().len() == 1)) /*((bytes_ok && b == 1)
&& encodingMode == TEXT_COMPACTION || (!bytes_ok && bytes.as_ref().unwrap().len() == 1))*/
&& (encodingMode == TEXT_COMPACTION)
{ {
//Switch for one byte (instead of latch) //Switch for one byte (instead of latch)
if autoECI { if autoECI {
@@ -406,7 +407,7 @@ fn encodeText<T: ECIInput + ?Sized>(
} else { } else {
tmp.push(29 as char); //ps tmp.push(29 as char); //ps
tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap());
break; //break;
} }
} }
} }
@@ -423,7 +424,7 @@ fn encodeText<T: ECIInput + ?Sized>(
tmp.push(27 as char); //as tmp.push(27 as char); //as
tmp.push(char::from_u32(ch as u32 - 65).unwrap()); tmp.push(char::from_u32(ch as u32 - 65).unwrap());
//space cannot happen here, it is also in "Lower" //space cannot happen here, it is also in "Lower"
break; //break;
} else if isMixed(ch) { } else if isMixed(ch) {
submode = SUBMODE_MIXED; submode = SUBMODE_MIXED;
tmp.push(28 as char); //ml tmp.push(28 as char); //ml
@@ -431,7 +432,7 @@ fn encodeText<T: ECIInput + ?Sized>(
} else { } else {
tmp.push(29 as char); //ps tmp.push(29 as char); //ps
tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap()); tmp.push(char::from_u32(PUNCTUATION[ch as usize] as u32).unwrap());
break; //break;
} }
} }
} }

View File

@@ -75,14 +75,15 @@ impl Reader for QRCodeReader {
// If the code was mirrored: swap the bottom-left and the top-right points. // If the code was mirrored: swap the bottom-left and the top-right points.
if let Some(other) = decoderRXingResult.getOther() { if let Some(other) = decoderRXingResult.getOther() {
if other.is::<QRCodeDecoderMetaData>() { if other.is::<QRCodeDecoderMetaData>() {
// if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) { // if (decoderRXingResult.getOther() instanceof QRCodeDecoderMetaData) {
other other
.downcast_ref::<QRCodeDecoderMetaData>() .downcast_ref::<QRCodeDecoderMetaData>()
.unwrap() .unwrap()
.applyMirroredCorrection(&mut points); .applyMirroredCorrection(&mut points);
// ((QRCodeDecoderMetaData) decoderRXingResult.getOther()).applyMirroredCorrection(points); // ((QRCodeDecoderMetaData) decoderRXingResult.getOther()).applyMirroredCorrection(points);
}} }
}
let mut result = RXingResult::new( let mut result = RXingResult::new(
decoderRXingResult.getText(), decoderRXingResult.getText(),