mirror of
https://github.com/starovoid/rxing.git
synced 2026-07-26 04:12:34 +00:00
mostly passing
This commit is contained in:
@@ -106,58 +106,57 @@ X X X X X X X X X X
|
||||
X X X
|
||||
X X X X X X X X X X
|
||||
X X X X X X X X X X
|
||||
" );
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn testEncode2() {
|
||||
testEncode(
|
||||
r"Aztec Code is a public domain 2D matrix barcode symbology
|
||||
of nominally square symbols built on a square grid with a
|
||||
distinctive square bullseye pattern at their center.",
|
||||
"Aztec Code is a public domain 2D matrix barcode symbology of nominally square symbols built on a square grid with a distinctive square bullseye pattern at their center.",
|
||||
false,
|
||||
6,
|
||||
r" X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X X X X
|
||||
X X X X X X X X X X X X X
|
||||
",
|
||||
);
|
||||
}
|
||||
@@ -170,6 +169,7 @@ fn testAztecWriter() {
|
||||
testWriter("Espa\u{00F1}ol", Some(ISO_8859_1), 25, true, 1); // Explicit ISO-8859-1
|
||||
testWriter("\u{20AC} 1 sample data.", Some(WINDOWS_1252), 25, true, 2); // ISO-8859-1 can't encode Euro; Windows-1252 can
|
||||
testWriter("\u{20AC} 1 sample data.", Some(ISO_8859_15), 25, true, 2);
|
||||
testWriter("\u{20AC} 1 sample data.", Some(ISO_8859_15), 0, true, 2);
|
||||
testWriter("\u{20AC} 1 sample data.", Some(UTF_8), 25, true, 2);
|
||||
testWriter("\u{20AC} 1 sample data.", Some(UTF_8), 100, true, 3);
|
||||
testWriter("\u{20AC} 1 sample data.", Some(UTF_8), 300, true, 4);
|
||||
@@ -191,8 +191,8 @@ fn testAztecWriter() {
|
||||
encoder::DEFAULT_AZTEC_LAYERS,
|
||||
)
|
||||
.expect("encode should succeed");
|
||||
let expectedMatrix = aztec.getMatrix();
|
||||
assert_eq!(&matrix, expectedMatrix);
|
||||
let expected_matrix = aztec.getMatrix();
|
||||
assert_eq!(&matrix, expected_matrix);
|
||||
}
|
||||
|
||||
// synthetic tests (encode-decode round-trip)
|
||||
@@ -234,12 +234,7 @@ Four score and seven our forefathers brought forth"#,
|
||||
#[test]
|
||||
fn testEncodeDecode10() {
|
||||
testEncodeDecode(
|
||||
r"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam
|
||||
cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum
|
||||
est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue
|
||||
auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla
|
||||
ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id
|
||||
elementum sapien dolor et diam.",
|
||||
"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id elementum sapien dolor et diam.",
|
||||
false,
|
||||
10,
|
||||
);
|
||||
@@ -248,27 +243,27 @@ fn testEncodeDecode10() {
|
||||
#[test]
|
||||
fn testEncodeDecode23() {
|
||||
testEncodeDecode(
|
||||
"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam
|
||||
cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum
|
||||
est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue
|
||||
auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla
|
||||
ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id
|
||||
elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend.
|
||||
Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus
|
||||
justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu
|
||||
tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus
|
||||
quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec
|
||||
laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida
|
||||
justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec
|
||||
lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar
|
||||
nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat
|
||||
eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra
|
||||
fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo
|
||||
diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla
|
||||
ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit
|
||||
felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo
|
||||
"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam\
|
||||
cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum\
|
||||
est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue\
|
||||
auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla\
|
||||
ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id\
|
||||
elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend.\
|
||||
Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus\
|
||||
justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu\
|
||||
tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus\
|
||||
quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec\
|
||||
laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida\
|
||||
justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec\
|
||||
lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar\
|
||||
nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat\
|
||||
eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra\
|
||||
fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo\
|
||||
diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla\
|
||||
ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum\
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.\
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit\
|
||||
felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo\
|
||||
erat pulvinar nisi, id elementum sapien dolor et diam.",
|
||||
false,
|
||||
23,
|
||||
@@ -278,42 +273,42 @@ fn testEncodeDecode23() {
|
||||
#[test]
|
||||
fn testEncodeDecode31() {
|
||||
testEncodeDecode(
|
||||
"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam
|
||||
cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum
|
||||
est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue
|
||||
auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla
|
||||
ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id
|
||||
elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend.
|
||||
Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus
|
||||
justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu
|
||||
tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus
|
||||
quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec
|
||||
laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida,
|
||||
justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec
|
||||
lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar
|
||||
nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat
|
||||
eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra
|
||||
fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo
|
||||
diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla
|
||||
ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit
|
||||
felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo
|
||||
erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit
|
||||
placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at
|
||||
pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est.
|
||||
Ut justo diam, lobortis eu tristique ac, p.In ut magna vel mauris malesuada
|
||||
dictum. Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id
|
||||
justo rutrum sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum
|
||||
sit amet. Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat,
|
||||
eget hendrerit felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet
|
||||
laoreet, justo erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac
|
||||
nunc sodales elit placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula,
|
||||
massa at pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus
|
||||
sed est. Ut justo diam, lobortis eu tris. In ut magna vel mauris malesuada dictum.
|
||||
Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget
|
||||
"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam\
|
||||
cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum\
|
||||
est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue\
|
||||
auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla\
|
||||
ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id\
|
||||
elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend.\
|
||||
Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus\
|
||||
justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu\
|
||||
tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus\
|
||||
quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec\
|
||||
laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida,\
|
||||
justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec\
|
||||
lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar\
|
||||
nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat\
|
||||
eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra\
|
||||
fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo\
|
||||
diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla\
|
||||
ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum\
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.\
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit\
|
||||
felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo\
|
||||
erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit\
|
||||
placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at\
|
||||
pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est.\
|
||||
Ut justo diam, lobortis eu tristique ac, p.In ut magna vel mauris malesuada\
|
||||
dictum. Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id\
|
||||
justo rutrum sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum\
|
||||
sit amet. Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat,\
|
||||
eget hendrerit felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet\
|
||||
laoreet, justo erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac\
|
||||
nunc sodales elit placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula,\
|
||||
massa at pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus\
|
||||
sed est. Ut justo diam, lobortis eu tris. In ut magna vel mauris malesuada dictum.\
|
||||
Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum\
|
||||
sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet.\
|
||||
Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget\
|
||||
hendrerit felis turpis nec lorem.",
|
||||
false,
|
||||
31,
|
||||
@@ -363,7 +358,7 @@ fn testStuffBitsTest() {
|
||||
".....X ...XXX XX..XX ..X... ..X.X. X..... X.X... ....X. X..... X....X X..X.. .....X X.X..X XXX.XX .XXXXX");
|
||||
}
|
||||
|
||||
#[test] // Adding a binary shift character that shouldn't be there.
|
||||
#[test]
|
||||
fn testHighLevelEncode() {
|
||||
testHighLevelEncodeString(
|
||||
"A. b.",
|
||||
@@ -436,6 +431,9 @@ fn testHighLevelEncodeBinary() {
|
||||
"XXXX. ..XX .X.. .X.X .XX. XXX. XXXXX ....X ........",
|
||||
);
|
||||
|
||||
testHighLevelEncodeStringUtf8("\u{20AC} 1 sample data.",
|
||||
"...........X..X..X...XXXXX...XXXXX...X.X.....X.X.X.XX..XXXX....X..XX...XXXX.XXX..X.X.....X..XXX.X...X.XX.X..XX.....X..X.X...X.X.X.X...X.XXXX.XX.X");
|
||||
|
||||
// Create a string in which every character requires binary
|
||||
let mut sb = String::new();
|
||||
for i in 0..3000 {
|
||||
@@ -466,69 +464,101 @@ fn testHighLevelEncodeBinary() {
|
||||
};
|
||||
// ( (i <= 31) ? 10 : (i <= 62) ? 20 : (i <= 2078) ? 21 : 31);
|
||||
// Verify that we are correct about the length.
|
||||
let substring_for_test : String = sb.chars().take(i).collect();
|
||||
let substring_for_test: String = sb.chars().take(i).collect();
|
||||
testHighLevelEncodeStringCount(&substring_for_test, expected_length as u32);
|
||||
if i != 1 && i != 32 && i != 2079 {
|
||||
// The addition of an 'a' at the beginning or end gets merged into the binary code
|
||||
// in those cases where adding another binary character only adds 8 or 9 bits to the result.
|
||||
// So we exclude the border cases i=1,32,2079
|
||||
// A lower case letter at the beginning will be merged into binary mode
|
||||
let substring_for_sub_test : String = sb.chars().take(i-1).collect();
|
||||
testHighLevelEncodeStringCount(&format!("a{}", &substring_for_sub_test), expected_length as u32);
|
||||
let substring_for_sub_test: String = sb.chars().take(i - 1).collect();
|
||||
testHighLevelEncodeStringCount(
|
||||
&format!("a{}", &substring_for_sub_test),
|
||||
expected_length as u32,
|
||||
);
|
||||
// A lower case letter at the end will also be merged into binary mode
|
||||
testHighLevelEncodeStringCount(&format!("{}a", &substring_for_sub_test), expected_length as u32);
|
||||
testHighLevelEncodeStringCount(
|
||||
&format!("{}a", &substring_for_sub_test),
|
||||
expected_length as u32,
|
||||
);
|
||||
}
|
||||
// A lower case letter at both ends will enough to latch us into LOWER.
|
||||
testHighLevelEncodeStringCount(&format!("a{}b", &substring_for_test), expected_length as u32 + 15);
|
||||
testHighLevelEncodeStringCount(
|
||||
&format!("a{}b", &substring_for_test),
|
||||
expected_length as u32 + 15,
|
||||
);
|
||||
}
|
||||
|
||||
sb.clear();
|
||||
|
||||
sb.push('A');
|
||||
for _i in 0..31 {
|
||||
// sb.push('A');
|
||||
for _i in 0..32 {
|
||||
// for (int i = 0; i < 32; i++) {
|
||||
sb.push('§'); // § forces binary encoding
|
||||
}
|
||||
// sb.replace_range(sb.char_indices().nth(1).map(|(pos, ch)| pos..pos+ch.len_utf8()).unwrap(), "A");
|
||||
sb.replace_range(
|
||||
sb.char_indices()
|
||||
.nth(1)
|
||||
.map(|(pos, ch)| pos..pos + ch.len_utf8())
|
||||
.unwrap(),
|
||||
"A",
|
||||
);
|
||||
// sb.setCharAt(1, 'A');
|
||||
// expect B/S(1) A B/S(30)
|
||||
testHighLevelEncodeStringCount(&sb, 5 + 20 + 31 * 8);
|
||||
|
||||
sb.clear();
|
||||
|
||||
sb.push('A');
|
||||
for _i in 0..30 {
|
||||
// sb.push('A');
|
||||
for _i in 0..31 {
|
||||
// for (int i = 0; i < 31; i++) {
|
||||
sb.push('§');
|
||||
}
|
||||
// sb.replace_range(1..2, "A");
|
||||
sb.replace_range(
|
||||
sb.char_indices()
|
||||
.nth(1)
|
||||
.map(|(pos, ch)| pos..pos + ch.len_utf8())
|
||||
.unwrap(),
|
||||
"A",
|
||||
);
|
||||
// sb.setCharAt(1, 'A');
|
||||
// expect B/S(31)
|
||||
testHighLevelEncodeStringCount(&sb, 10 + 31 * 8);
|
||||
|
||||
sb.clear();
|
||||
|
||||
sb.push('A');
|
||||
for _i in 0..33 {
|
||||
// sb.push('A');
|
||||
for _i in 0..34 {
|
||||
// for (int i = 0; i < 34; i++) {
|
||||
sb.push('§');
|
||||
}
|
||||
//sb.replace_range(1..2, "A");
|
||||
sb.replace_range(
|
||||
sb.char_indices()
|
||||
.nth(1)
|
||||
.map(|(pos, ch)| pos..pos + ch.len_utf8())
|
||||
.unwrap(),
|
||||
"A",
|
||||
);
|
||||
// sb.setCharAt(1, 'A');
|
||||
// expect B/S(31) B/S(3)
|
||||
testHighLevelEncodeStringCount(&sb, 20 + 34 * 8);
|
||||
|
||||
sb.clear();
|
||||
for _i in 0..30 {
|
||||
// for (int i = 0; i < 64; i++) {
|
||||
sb.push('§');
|
||||
}
|
||||
sb.push('A');
|
||||
for _i in 31..64 {
|
||||
|
||||
for _i in 0..64 {
|
||||
// for (int i = 0; i < 64; i++) {
|
||||
sb.push('§');
|
||||
}
|
||||
//sb.replace_range(30..31, "A");
|
||||
sb.replace_range(
|
||||
sb.char_indices()
|
||||
.nth(30)
|
||||
.map(|(pos, ch)| pos..pos + ch.len_utf8())
|
||||
.unwrap(),
|
||||
"A",
|
||||
);
|
||||
// sb.setCharAt(30, 'A');
|
||||
// expect B/S(64)
|
||||
testHighLevelEncodeStringCount(&sb, 21 + 64 * 8);
|
||||
@@ -573,12 +603,12 @@ fn testUserSpecifiedLayers() {
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn testUserSpecifiedLayers2() {
|
||||
doTestUserSpecifiedLayers(1);
|
||||
doTestUserSpecifiedLayers(-1);
|
||||
}
|
||||
|
||||
fn doTestUserSpecifiedLayers(userSpecifiedLayers: usize) {
|
||||
fn doTestUserSpecifiedLayers(userSpecifiedLayers: i32) {
|
||||
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
let mut aztec = encoder::encode(alphabet, 25, 2).expect("should encode");
|
||||
let mut aztec = encoder::encode(alphabet, 25, -2).expect("should encode");
|
||||
assert_eq!(2, aztec.getLayers());
|
||||
assert!(aztec.isCompact());
|
||||
|
||||
@@ -586,7 +616,7 @@ fn doTestUserSpecifiedLayers(userSpecifiedLayers: usize) {
|
||||
assert_eq!(32, aztec.getLayers());
|
||||
assert!(!aztec.isCompact());
|
||||
|
||||
encoder::encode(alphabet, 25, userSpecifiedLayers as u32).expect("encode");
|
||||
encoder::encode(alphabet, 25, userSpecifiedLayers).expect("encode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -597,7 +627,7 @@ fn testBorderCompact4CaseFailed() {
|
||||
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
// encodes as 26 * 5 * 4 = 520 bits of data
|
||||
let alphabet4 = format!("{}{}{}{}", alphabet, alphabet, alphabet, alphabet);
|
||||
encoder::encode(&alphabet4, 0, 4).expect("encode");
|
||||
encoder::encode(&alphabet4, 0, -4).expect("encode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -633,9 +663,10 @@ fn testEncode(data: &str, compact: bool, layers: u32, expected: &str) {
|
||||
);
|
||||
assert_eq!(layers, aztec.getLayers(), "Unexpected nr. of layers");
|
||||
let matrix = aztec.getMatrix();
|
||||
|
||||
// let mut xored = BitMatrix::parse_strings(&stripSpace(expected), "X ", " ").expect("should parse");
|
||||
// xored.xor(matrix).expect("should xor");
|
||||
assert_eq!(expected, matrix.to_string(), "encode({}) failed", data );
|
||||
assert_eq!(expected, matrix.to_string(), "encode({}) failed", data);
|
||||
}
|
||||
|
||||
fn testEncodeDecode(data: &str, compact: bool, layers: u32) {
|
||||
@@ -688,7 +719,7 @@ fn testEncodeDecode(data: &str, compact: bool, layers: u32) {
|
||||
fn testWriter(
|
||||
data: &str,
|
||||
charset: Option<EncodingRef>,
|
||||
eccPercent: u32,
|
||||
ecc_percent: u32,
|
||||
compact: bool,
|
||||
layers: u32,
|
||||
) {
|
||||
@@ -705,22 +736,18 @@ fn testWriter(
|
||||
// }
|
||||
hints.insert(
|
||||
EncodeHintType::ERROR_CORRECTION,
|
||||
EncodeHintValue::ErrorCorrection(eccPercent.to_string()),
|
||||
EncodeHintValue::ErrorCorrection(ecc_percent.to_string()),
|
||||
);
|
||||
let writer = AztecWriter {};
|
||||
let mut matrix = AztecWriter::encode_with_hints(data, &BarcodeFormat::AZTEC, 0, 0, &hints)
|
||||
.expect("encoder created");
|
||||
let cset = match charset {
|
||||
Some(cs) => cs,
|
||||
None => encoding::all::ISO_8859_1,
|
||||
};
|
||||
let aztec = encoder::encode_with_charset(
|
||||
data,
|
||||
eccPercent,
|
||||
encoder::DEFAULT_AZTEC_LAYERS,
|
||||
cset,
|
||||
)
|
||||
.expect("encode should encode");
|
||||
|
||||
let cset = match charset {
|
||||
Some(cs) => cs,
|
||||
None => encoding::all::ISO_8859_1,
|
||||
};
|
||||
let aztec =
|
||||
encoder::encode_with_charset(data, ecc_percent, encoder::DEFAULT_AZTEC_LAYERS, cset)
|
||||
.expect("encode should encode");
|
||||
assert_eq!(
|
||||
compact,
|
||||
aztec.isCompact(),
|
||||
@@ -729,6 +756,7 @@ fn testWriter(
|
||||
assert_eq!(layers, aztec.getLayers(), "Unexpected nr. of layers");
|
||||
let matrix2 = aztec.getMatrix();
|
||||
assert_eq!(&matrix, matrix2);
|
||||
|
||||
let mut r = AztecDetectorRXingResult::new(
|
||||
matrix.clone(),
|
||||
NO_POINTS,
|
||||
@@ -736,12 +764,14 @@ fn testWriter(
|
||||
aztec.getCodeWords(),
|
||||
aztec.getLayers(),
|
||||
);
|
||||
|
||||
let mut res = decoder::decode(&r).expect("should decode");
|
||||
assert_eq!(data, res.getText());
|
||||
|
||||
// Check error correction by introducing up to eccPercent/2 errors
|
||||
let ecWords = aztec.getCodeWords() * eccPercent / 100 / 2;
|
||||
let ec_words = aztec.getCodeWords() * ecc_percent / 100 / 2;
|
||||
let mut random = getPseudoRandom();
|
||||
for _i in 0..ecWords {
|
||||
for _i in 0..ec_words {
|
||||
// for (int i = 0; i < ecWords; i++) {
|
||||
// don't touch the core
|
||||
let x = if random.gen_bool(0.50) {
|
||||
@@ -791,6 +821,30 @@ fn testStuffBits(wordSize: usize, bits: &str, expected: &str) {
|
||||
);
|
||||
}
|
||||
|
||||
fn testHighLevelEncodeStringUtf8(s: &str, expectedBits: &str) {
|
||||
let bits = HighLevelEncoder::with_charset(
|
||||
encoding::all::UTF_8
|
||||
.encode(s, encoding::EncoderTrap::Strict)
|
||||
.expect("should encode to bytes"),
|
||||
encoding::all::UTF_8,
|
||||
)
|
||||
.encode()
|
||||
.expect("high level ok");
|
||||
// let bits = HighLevelEncoder::new(s.getBytes(StandardCharsets.ISO_8859_1)).encode();
|
||||
let receivedBits = stripSpace(&bits.to_string());
|
||||
assert_eq!(
|
||||
s,
|
||||
decoder::highLevelDecode(&toBooleanArray(&bits)).expect("must decode")
|
||||
);
|
||||
// dbg!(s, decoder::highLevelDecode(&toBooleanArray(&bits)).expect("must decode"));
|
||||
assert_eq!(
|
||||
stripSpace(expectedBits),
|
||||
receivedBits,
|
||||
"highLevelEncode() failed for input string: {}",
|
||||
s
|
||||
);
|
||||
}
|
||||
|
||||
fn testHighLevelEncodeString(s: &str, expectedBits: &str) {
|
||||
let bits = HighLevelEncoder::new(
|
||||
encoding::all::ISO_8859_1
|
||||
@@ -823,19 +877,20 @@ fn testHighLevelEncodeStringCount(s: &str, expectedReceivedBits: u32) {
|
||||
.expect("high level ok");
|
||||
//let bits = HighLevelEncoder::new(s.getBytes(StandardCharsets.ISO_8859_1)).encode().unwrap();
|
||||
let receivedBitCount = stripSpace(&bits.to_string()).len();
|
||||
// dbg!(s, decoder::highLevelDecode(&toBooleanArray(&bits)).expect("should decode"));
|
||||
assert_eq!(
|
||||
s,
|
||||
decoder::highLevelDecode(&toBooleanArray(&bits)).expect("should decode")
|
||||
);
|
||||
assert!(
|
||||
expectedReceivedBits as usize >= receivedBitCount,
|
||||
"encode size too high ({} >= {}) failed for input string: {}",
|
||||
expectedReceivedBits, receivedBitCount,
|
||||
s
|
||||
);
|
||||
// assert_eq!(
|
||||
// expectedReceivedBits as usize, receivedBitCount,
|
||||
// "highLevelEncode() failed for input string: {}",
|
||||
// assert!(
|
||||
// expectedReceivedBits as usize >= receivedBitCount,
|
||||
// "encode size too high ({} >= {}) failed for input string: {}",
|
||||
// expectedReceivedBits, receivedBitCount,
|
||||
// s
|
||||
// );
|
||||
assert_eq!(
|
||||
expectedReceivedBits as usize, receivedBitCount,
|
||||
"highLevelEncode() failed for input string: {} with byte count ({}!={})",
|
||||
s, expectedReceivedBits, receivedBitCount
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::{any::Any, collections::HashMap};
|
||||
|
||||
use encoding::EncodingRef;
|
||||
|
||||
@@ -48,14 +48,18 @@ impl Writer for AztecWriter {
|
||||
hints: &std::collections::HashMap<crate::EncodeHintType, crate::EncodeHintValue>,
|
||||
) -> Result<crate::common::BitMatrix, crate::exceptions::Exceptions> {
|
||||
let mut charset = None; // Do not add any ECI code by default
|
||||
let mut eccPercent = encoder::DEFAULT_EC_PERCENT;
|
||||
let mut ecc_percent = encoder::DEFAULT_EC_PERCENT;
|
||||
let mut layers = encoder::DEFAULT_AZTEC_LAYERS;
|
||||
if hints.contains_key(&EncodeHintType::CHARACTER_SET) {
|
||||
if let EncodeHintValue::CharacterSet(cset_name) = hints
|
||||
.get(&EncodeHintType::CHARACTER_SET)
|
||||
.expect("already knonw presence")
|
||||
{
|
||||
charset = Some(encoding::label::encoding_from_whatwg_label(cset_name).unwrap());
|
||||
if cset_name != "iso-8859-1" {
|
||||
charset = Some(encoding::label::encoding_from_whatwg_label(cset_name).unwrap());
|
||||
}
|
||||
// dbg!(cset_name);
|
||||
// dbg!(encoding::label::encoding_from_whatwg_label(cset_name).unwrap().name(), encoding::label::encoding_from_whatwg_label(cset_name).unwrap().whatwg_name());
|
||||
}
|
||||
// charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
|
||||
}
|
||||
@@ -64,7 +68,7 @@ impl Writer for AztecWriter {
|
||||
.get(&EncodeHintType::ERROR_CORRECTION)
|
||||
.expect("key exists")
|
||||
{
|
||||
eccPercent = ecc_level.parse().expect("should convert to int");
|
||||
ecc_percent = ecc_level.parse().expect("should convert to int");
|
||||
}
|
||||
// eccPercent = Integer.parseInt(hints.get(EncodeHintType::ERROR_CORRECTION).toString());
|
||||
}
|
||||
@@ -83,7 +87,7 @@ impl Writer for AztecWriter {
|
||||
width as u32,
|
||||
height as u32,
|
||||
charset,
|
||||
eccPercent,
|
||||
ecc_percent,
|
||||
layers,
|
||||
)
|
||||
}
|
||||
@@ -95,8 +99,8 @@ fn encode(
|
||||
width: u32,
|
||||
height: u32,
|
||||
charset: Option<EncodingRef>,
|
||||
eccPercent: u32,
|
||||
layers: u32,
|
||||
ecc_percent: u32,
|
||||
layers: i32,
|
||||
) -> Result<BitMatrix, Exceptions> {
|
||||
if format != BarcodeFormat::AZTEC {
|
||||
return Err(Exceptions::IllegalArgumentException(format!(
|
||||
@@ -105,9 +109,10 @@ fn encode(
|
||||
)));
|
||||
}
|
||||
let aztec = if let Some(cset) = charset {
|
||||
encoder::encode_with_charset(contents, eccPercent, layers, cset)?
|
||||
// dbg!(cset.name(), cset.whatwg_name());
|
||||
encoder::encode_with_charset(contents, ecc_percent, layers, cset)?
|
||||
} else {
|
||||
encoder::encode(contents, eccPercent, layers)?
|
||||
encoder::encode(contents, ecc_percent, layers)?
|
||||
};
|
||||
renderRXingResult(&aztec, width, height)
|
||||
}
|
||||
@@ -117,33 +122,33 @@ fn renderRXingResult(code: &AztecCode, width: u32, height: u32) -> Result<BitMat
|
||||
// if input == null {
|
||||
// throw new IllegalStateException();
|
||||
// }
|
||||
let inputWidth = input.getWidth();
|
||||
let inputHeight = input.getHeight();
|
||||
let outputWidth = width.max(inputWidth);
|
||||
let outputHeight = height.max(inputHeight);
|
||||
let input_width = input.getWidth();
|
||||
let input_height = input.getHeight();
|
||||
let output_width = width.max(input_width);
|
||||
let output_height = height.max(input_height);
|
||||
|
||||
let multiple = (outputWidth / inputWidth).min(outputHeight / inputHeight);
|
||||
let leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
|
||||
let topPadding = (outputHeight - (inputHeight * multiple)) / 2;
|
||||
let multiple = (output_width / input_width).min(output_height / input_height);
|
||||
let left_padding = (output_width - (input_width * multiple)) / 2;
|
||||
let top_padding = (output_height - (input_height * multiple)) / 2;
|
||||
|
||||
let mut output = BitMatrix::new(outputWidth, outputHeight)?;
|
||||
let mut output = BitMatrix::new(output_width, output_height)?;
|
||||
|
||||
let mut inputY = 0;
|
||||
let mut outputY = topPadding;
|
||||
while inputY < inputHeight {
|
||||
let mut inputX = 0;
|
||||
let mut outputX = leftPadding;
|
||||
while inputX < inputWidth {
|
||||
if input.get(inputX, inputY) {
|
||||
output.setRegion(outputX, outputY, multiple, multiple);
|
||||
let mut input_y = 0;
|
||||
let mut output_y = top_padding;
|
||||
while input_y < input_height {
|
||||
let mut input_x = 0;
|
||||
let mut output_x = left_padding;
|
||||
while input_x < input_width {
|
||||
if input.get(input_x, input_y) {
|
||||
output.setRegion(output_x, output_y, multiple, multiple)?;
|
||||
}
|
||||
|
||||
inputX += 1;
|
||||
outputX += multiple;
|
||||
input_x += 1;
|
||||
output_x += multiple;
|
||||
}
|
||||
|
||||
inputY += 1;
|
||||
outputY += multiple
|
||||
input_y += 1;
|
||||
output_y += multiple
|
||||
}
|
||||
// for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
|
||||
// // Write the contents of this row of the barcode
|
||||
|
||||
@@ -14,28 +14,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// package com.google.zxing.aztec.decoder;
|
||||
|
||||
// import com.google.zxing.FormatException;
|
||||
// import com.google.zxing.aztec.AztecDetectorRXingResult;
|
||||
// import com.google.zxing.common.BitMatrix;
|
||||
// import com.google.zxing.common.CharacterSetECI;
|
||||
// import com.google.zxing.common.DecoderRXingResult;
|
||||
// import com.google.zxing.common.reedsolomon.GenericGF;
|
||||
// import com.google.zxing.common.reedsolomon.ReedSolomonDecoder;
|
||||
// import com.google.zxing.common.reedsolomon.ReedSolomonException;
|
||||
|
||||
// import java.io.ByteArrayOutputStream;
|
||||
// import java.io.UnsupportedEncodingException;
|
||||
// import java.nio.charset.Charset;
|
||||
// import java.nio.charset.StandardCharsets;
|
||||
// import java.util.Arrays;
|
||||
|
||||
use encoding::Encoding;
|
||||
|
||||
use crate::{
|
||||
common::{
|
||||
self,
|
||||
reedsolomon::{
|
||||
get_predefined_genericgf, GenericGF, PredefinedGenericGF, ReedSolomonDecoder,
|
||||
},
|
||||
@@ -53,7 +36,7 @@ use super::AztecDetectorResult::AztecDetectorRXingResult;
|
||||
* @author David Olivier
|
||||
*/
|
||||
|
||||
#[derive(PartialEq, Eq,Copy,Clone)]
|
||||
#[derive(PartialEq, Eq, Copy, Clone)]
|
||||
enum Table {
|
||||
UPPER,
|
||||
LOWER,
|
||||
@@ -75,8 +58,8 @@ const LOWER_TABLE: [&str; 32] = [
|
||||
|
||||
const MIXED_TABLE: [&str; 32] = [
|
||||
"CTRL_PS", " ", "\u{1}", "\u{2}", "\u{3}", "\u{4}", "\u{5}", "\u{6}", "\u{7}", "\u{8}", "\t",
|
||||
"\n", "\u{13}", "\u{0c}", "\r", "\u{33}", "\u{34}", "\u{35}", "\u{36}", "\u{37}", "@", "\\",
|
||||
"^", "_", "`", "|", "~", "\u{177}", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS",
|
||||
"\n", "\u{000b}", "\u{000c}", "\r", "\u{001b}", "\u{001c}", "\u{001d}", "\u{001e}", "\u{001f}",
|
||||
"@", "\\", "^", "_", "`", "|", "~", "\u{007f}", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS",
|
||||
];
|
||||
|
||||
const PUNCT_TABLE: [&str; 32] = [
|
||||
@@ -98,24 +81,24 @@ pub fn decode(
|
||||
) -> Result<DecoderRXingResult, Exceptions> {
|
||||
//let mut detectorRXingResult = detectorRXingResult.clone();
|
||||
let matrix = detectorRXingResult.getBits();
|
||||
let rawbits = extractBits(&detectorRXingResult, matrix);
|
||||
let correctedBits = correctBits(&detectorRXingResult, &rawbits)?;
|
||||
let rawBytes = convertBoolArrayToByteArray(&correctedBits.correctBits);
|
||||
let result = getEncodedData(&correctedBits.correctBits);
|
||||
let mut decoderRXingResult = DecoderRXingResult::new(
|
||||
rawBytes,
|
||||
let rawbits = extract_bits(&detectorRXingResult, matrix);
|
||||
let corrected_bits = correct_bits(&detectorRXingResult, &rawbits)?;
|
||||
let raw_bytes = convertBoolArrayToByteArray(&corrected_bits.correct_bits);
|
||||
let result = get_encoded_data(&corrected_bits.correct_bits);
|
||||
let mut decoder_rxing_result = DecoderRXingResult::new(
|
||||
raw_bytes,
|
||||
result?,
|
||||
Vec::new(),
|
||||
format!("{}%", correctedBits.ecLevel),
|
||||
format!("{}%", corrected_bits.ec_level),
|
||||
);
|
||||
decoderRXingResult.setNumBits(correctedBits.correctBits.len());
|
||||
decoder_rxing_result.setNumBits(corrected_bits.correct_bits.len());
|
||||
|
||||
Ok(decoderRXingResult)
|
||||
Ok(decoder_rxing_result)
|
||||
}
|
||||
|
||||
/// This method is used for testing the high-level encoder
|
||||
pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String, Exceptions> {
|
||||
getEncodedData(correctedBits)
|
||||
get_encoded_data(correctedBits)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,8 +106,8 @@ pub fn highLevelDecode(correctedBits: &[bool]) -> Result<String, Exceptions> {
|
||||
*
|
||||
* @return the decoded string
|
||||
*/
|
||||
fn getEncodedData(corrected_bits: &[bool]) -> Result<String, Exceptions> {
|
||||
let endIndex = corrected_bits.len();
|
||||
fn get_encoded_data(corrected_bits: &[bool]) -> Result<String, Exceptions> {
|
||||
let end_index = corrected_bits.len();
|
||||
let mut latch_table = Table::UPPER; // table most recently latched to
|
||||
let mut shift_table = Table::UPPER; // table to use for the next read
|
||||
|
||||
@@ -136,30 +119,30 @@ fn getEncodedData(corrected_bits: &[bool]) -> Result<String, Exceptions> {
|
||||
// when character encoding changes (ECI) or input ends.
|
||||
let mut decoded_bytes: Vec<u8> = Vec::new();
|
||||
// let mut encdr: &'static dyn encoding::Encoding = encoding::all::UTF_8;
|
||||
let mut encdr: &'static dyn encoding::Encoding = encoding::all::ISO_8859_1;
|
||||
let mut encdr: &'static dyn encoding::Encoding = encoding::all::ISO_8859_1;
|
||||
|
||||
let mut index = 0;
|
||||
while index < endIndex {
|
||||
while index < end_index {
|
||||
if shift_table == Table::BINARY {
|
||||
if endIndex - index < 5 {
|
||||
if end_index - index < 5 {
|
||||
break;
|
||||
}
|
||||
let mut length = readCode(corrected_bits, index, 5);
|
||||
let mut length = read_code(corrected_bits, index, 5);
|
||||
index += 5;
|
||||
if length == 0 {
|
||||
if endIndex - index < 11 {
|
||||
if end_index - index < 11 {
|
||||
break;
|
||||
}
|
||||
length = readCode(corrected_bits, index, 11) + 31;
|
||||
length = read_code(corrected_bits, index, 11) + 31;
|
||||
index += 11;
|
||||
}
|
||||
for _charCount in 0..length {
|
||||
for _char_count in 0..length {
|
||||
// for (int charCount = 0; charCount < length; charCount++) {
|
||||
if endIndex - index < 8 {
|
||||
index = endIndex; // Force outer loop to exit
|
||||
if end_index - index < 8 {
|
||||
index = end_index; // Force outer loop to exit
|
||||
break;
|
||||
}
|
||||
let code = readCode(corrected_bits, index, 8);
|
||||
let code = read_code(corrected_bits, index, 8);
|
||||
decoded_bytes.push(code as u8);
|
||||
index += 8;
|
||||
}
|
||||
@@ -167,21 +150,25 @@ fn getEncodedData(corrected_bits: &[bool]) -> Result<String, Exceptions> {
|
||||
shift_table = latch_table;
|
||||
} else {
|
||||
let size = if shift_table == Table::DIGIT { 4 } else { 5 };
|
||||
if endIndex - index < size {
|
||||
if end_index - index < size {
|
||||
break;
|
||||
}
|
||||
let code = readCode(corrected_bits, index, size);
|
||||
let code = read_code(corrected_bits, index, size);
|
||||
index += size;
|
||||
let str = getCharacter(shift_table, code)?;
|
||||
let str = get_character(shift_table, code)?;
|
||||
if "FLG(n)" == str {
|
||||
if endIndex - index < 3 {
|
||||
if end_index - index < 3 {
|
||||
break;
|
||||
}
|
||||
let mut n = readCode(corrected_bits, index, 3);
|
||||
let mut n = read_code(corrected_bits, index, 3);
|
||||
index += 3;
|
||||
// flush bytes, FLG changes state
|
||||
// try {
|
||||
result.push_str(&encdr.decode(&decoded_bytes, encoding::DecoderTrap::Strict).unwrap());
|
||||
result.push_str(
|
||||
&encdr
|
||||
.decode(&decoded_bytes, encoding::DecoderTrap::Strict)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
// result.push_str(&String::from_utf8(decoded_bytes.clone()).unwrap());
|
||||
// result.append(decodedBytes.toString(encoding.name()));
|
||||
@@ -199,28 +186,28 @@ fn getEncodedData(corrected_bits: &[bool]) -> Result<String, Exceptions> {
|
||||
_ => {
|
||||
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode
|
||||
let mut eci = 0;
|
||||
if endIndex - index < 4 * (n as usize) {
|
||||
if end_index - index < 4 * (n as usize) {
|
||||
break;
|
||||
}
|
||||
while n > 0 {
|
||||
//while (n-- > 0) {
|
||||
let nextDigit = readCode(corrected_bits, index, 4);
|
||||
let next_digit = read_code(corrected_bits, index, 4);
|
||||
index += 4;
|
||||
if nextDigit < 2 || nextDigit > 11 {
|
||||
if next_digit < 2 || next_digit > 11 {
|
||||
return Err(Exceptions::FormatException(
|
||||
"Not a decimal digit".to_owned(),
|
||||
)); // Not a decimal digit
|
||||
}
|
||||
eci = eci * 10 + (nextDigit - 2);
|
||||
eci = eci * 10 + (next_digit - 2);
|
||||
n -= 1;
|
||||
}
|
||||
let charsetECI = CharacterSetECI::getCharacterSetECIByValue(eci);
|
||||
if charsetECI.is_err() {
|
||||
let charset_eci = CharacterSetECI::getCharacterSetECIByValue(eci);
|
||||
if charset_eci.is_err() {
|
||||
return Err(Exceptions::FormatException(
|
||||
"Charset must exist".to_owned(),
|
||||
));
|
||||
}
|
||||
encdr = CharacterSetECI::getCharset(&charsetECI?);
|
||||
encdr = CharacterSetECI::getCharset(&charset_eci?);
|
||||
// encdr = charsetECI?::getCharset();
|
||||
}
|
||||
}
|
||||
@@ -324,7 +311,7 @@ fn getTable(t: char) -> Table {
|
||||
* @param table the table used
|
||||
* @param code the code of the character
|
||||
*/
|
||||
fn getCharacter(table: Table, code: u32) -> Result<&'static str, Exceptions> {
|
||||
fn get_character(table: Table, code: u32) -> Result<&'static str, Exceptions> {
|
||||
match table {
|
||||
Table::UPPER => Ok(UPPER_TABLE[code as usize]),
|
||||
Table::LOWER => Ok(LOWER_TABLE[code as usize]),
|
||||
@@ -350,14 +337,14 @@ fn getCharacter(table: Table, code: u32) -> Result<&'static str, Exceptions> {
|
||||
}
|
||||
|
||||
struct CorrectedBitsRXingResult {
|
||||
correctBits: Vec<bool>,
|
||||
ecLevel: u32,
|
||||
correct_bits: Vec<bool>,
|
||||
ec_level: u32,
|
||||
}
|
||||
impl CorrectedBitsRXingResult {
|
||||
pub fn new(correctBits: Vec<bool>, ecLevel: u32) -> Self {
|
||||
pub fn new(correct_bits: Vec<bool>, ec_level: u32) -> Self {
|
||||
Self {
|
||||
correctBits,
|
||||
ecLevel,
|
||||
correct_bits,
|
||||
ec_level,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -368,49 +355,49 @@ impl CorrectedBitsRXingResult {
|
||||
* @return the corrected array
|
||||
* @throws FormatException if the input contains too many errors
|
||||
*/
|
||||
fn correctBits(
|
||||
ddata: &&AztecDetectorRXingResult,
|
||||
fn correct_bits(
|
||||
ddata: &AztecDetectorRXingResult,
|
||||
rawbits: &[bool],
|
||||
) -> Result<CorrectedBitsRXingResult, Exceptions> {
|
||||
let gf: GenericGF;
|
||||
let codewordSize;
|
||||
let codeword_size;
|
||||
|
||||
if ddata.getNbLayers() <= 2 {
|
||||
codewordSize = 6;
|
||||
codeword_size = 6;
|
||||
gf = get_predefined_genericgf(PredefinedGenericGF::AztecData6); //GenericGF.AZTEC_DATA_6;
|
||||
} else if ddata.getNbLayers() <= 8 {
|
||||
codewordSize = 8;
|
||||
codeword_size = 8;
|
||||
gf = get_predefined_genericgf(PredefinedGenericGF::AztecData8); //GenericGF.AZTEC_DATA_8;
|
||||
} else if ddata.getNbLayers() <= 22 {
|
||||
codewordSize = 10;
|
||||
codeword_size = 10;
|
||||
gf = get_predefined_genericgf(PredefinedGenericGF::AztecData10); //GenericGF.AZTEC_DATA_10;
|
||||
} else {
|
||||
codewordSize = 12;
|
||||
codeword_size = 12;
|
||||
gf = get_predefined_genericgf(PredefinedGenericGF::AztecData12); //GenericGF.AZTEC_DATA_12;
|
||||
}
|
||||
|
||||
let numDataCodewords = ddata.getNbDatablocks();
|
||||
let numCodewords = rawbits.len() / codewordSize;
|
||||
if numCodewords < numDataCodewords as usize {
|
||||
let num_data_codewords = ddata.getNbDatablocks();
|
||||
let num_codewords = rawbits.len() / codeword_size;
|
||||
if num_codewords < num_data_codewords as usize {
|
||||
return Err(Exceptions::FormatException(format!(
|
||||
"numCodewords {}< numDataCodewords{}",
|
||||
numCodewords, numDataCodewords
|
||||
num_codewords, num_data_codewords
|
||||
)));
|
||||
}
|
||||
let mut offset = rawbits.len() % codewordSize;
|
||||
let mut offset = rawbits.len() % codeword_size;
|
||||
|
||||
let mut dataWords = vec![0i32; numCodewords];
|
||||
for i in 0..numCodewords {
|
||||
let mut data_words = vec![0i32; num_codewords];
|
||||
for i in 0..num_codewords {
|
||||
// for (int i = 0; i < numCodewords; i++, offset += codewordSize) {
|
||||
dataWords[i] = readCode(rawbits, offset, codewordSize) as i32;
|
||||
offset += codewordSize;
|
||||
data_words[i] = read_code(rawbits, offset, codeword_size) as i32;
|
||||
offset += codeword_size;
|
||||
}
|
||||
|
||||
//try {
|
||||
let rs_decoder = ReedSolomonDecoder::new(gf);
|
||||
rs_decoder.decode(
|
||||
&mut dataWords,
|
||||
(numCodewords - numDataCodewords as usize) as i32,
|
||||
&mut data_words,
|
||||
(num_codewords - num_data_codewords as usize) as i32,
|
||||
)?;
|
||||
//} catch (ReedSolomonException ex) {
|
||||
//throw FormatException.getFormatInstance(ex);
|
||||
@@ -418,47 +405,47 @@ fn correctBits(
|
||||
|
||||
// Now perform the unstuffing operation.
|
||||
// First, count how many bits are going to be thrown out as stuffing
|
||||
let mask = (1 << codewordSize) - 1;
|
||||
let mut stuffedBits = 0;
|
||||
for i in 0..numDataCodewords as usize {
|
||||
let mask = (1 << codeword_size) - 1;
|
||||
let mut stuffed_bits = 0;
|
||||
for i in 0..num_data_codewords as usize {
|
||||
// for (int i = 0; i < numDataCodewords; i++) {
|
||||
let dataWord = dataWords[i];
|
||||
if dataWord == 0 || dataWord == mask {
|
||||
let data_word = data_words[i];
|
||||
if data_word == 0 || data_word == mask {
|
||||
return Err(Exceptions::FormatException(
|
||||
"dataWord == 0 || dataWord == mask".to_owned(),
|
||||
));
|
||||
//throw FormatException.getFormatInstance();
|
||||
} else if dataWord == 1 || dataWord == mask - 1 {
|
||||
stuffedBits += 1;
|
||||
} else if data_word == 1 || data_word == mask - 1 {
|
||||
stuffed_bits += 1;
|
||||
}
|
||||
}
|
||||
// Now, actually unpack the bits and remove the stuffing
|
||||
let mut correctedBits =
|
||||
vec![false; (numDataCodewords * codewordSize as u32 - stuffedBits) as usize];
|
||||
let mut corrected_bits =
|
||||
vec![false; (num_data_codewords * codeword_size as u32 - stuffed_bits) as usize];
|
||||
let mut index = 0;
|
||||
for i in 0..numDataCodewords as usize {
|
||||
for i in 0..num_data_codewords as usize {
|
||||
// for (int i = 0; i < numDataCodewords; i++) {
|
||||
let dataWord = dataWords[i];
|
||||
if dataWord == 1 || dataWord == mask - 1 {
|
||||
let data_word = data_words[i];
|
||||
if data_word == 1 || data_word == mask - 1 {
|
||||
// next codewordSize-1 bits are all zeros or all ones
|
||||
correctedBits.splice(
|
||||
index..index + codewordSize - 1,
|
||||
vec![dataWord > 1; codewordSize],
|
||||
corrected_bits.splice(
|
||||
index..index + codeword_size - 1,
|
||||
vec![data_word > 1; codeword_size],
|
||||
);
|
||||
// Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
|
||||
index += codewordSize - 1;
|
||||
index += codeword_size - 1;
|
||||
} else {
|
||||
for bit in (0..codewordSize).rev() {
|
||||
for bit in (0..codeword_size).rev() {
|
||||
// for (int bit = codewordSize - 1; bit >= 0; --bit) {
|
||||
correctedBits[index] = (dataWord & (1 << bit)) != 0;
|
||||
corrected_bits[index] = (data_word & (1 << bit)) != 0;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CorrectedBitsRXingResult::new(
|
||||
correctedBits,
|
||||
(100 * (numCodewords - numDataCodewords as usize) / numCodewords) as u32,
|
||||
corrected_bits,
|
||||
(100 * (num_codewords - num_data_codewords as usize) / num_codewords) as u32,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -467,66 +454,66 @@ fn correctBits(
|
||||
*
|
||||
* @return the array of bits
|
||||
*/
|
||||
fn extractBits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<bool> {
|
||||
fn extract_bits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<bool> {
|
||||
let compact = ddata.isCompact();
|
||||
let layers = ddata.getNbLayers();
|
||||
let baseMatrixSize = ((if compact { 11 } else { 14 }) + layers * 4) as usize; // not including alignment lines
|
||||
let mut alignmentMap = vec![0u32; baseMatrixSize];
|
||||
let mut rawbits = vec![false; totalBitsInLayer(layers as usize, compact)];
|
||||
let base_matrix_size = ((if compact { 11 } else { 14 }) + layers * 4) as usize; // not including alignment lines
|
||||
let mut alignment_map = vec![0u32; base_matrix_size];
|
||||
let mut rawbits = vec![false; total_bits_in_layer(layers as usize, compact)];
|
||||
|
||||
if compact {
|
||||
for i in 0..alignmentMap.len() {
|
||||
for i in 0..alignment_map.len() {
|
||||
// for (int i = 0; i < alignmentMap.length; i++) {
|
||||
alignmentMap[i] = i as u32;
|
||||
alignment_map[i] = i as u32;
|
||||
}
|
||||
} else {
|
||||
let matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15);
|
||||
let origCenter = baseMatrixSize / 2;
|
||||
let center = matrixSize / 2;
|
||||
for i in 0..origCenter {
|
||||
let matrix_size = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15);
|
||||
let orig_center = base_matrix_size / 2;
|
||||
let center = matrix_size / 2;
|
||||
for i in 0..orig_center {
|
||||
// for (int i = 0; i < origCenter; i++) {
|
||||
let newOffset = i + i / 15;
|
||||
alignmentMap[origCenter - i - 1] = (center - newOffset - 1) as u32;
|
||||
alignmentMap[origCenter + i] = (center + newOffset + 1) as u32;
|
||||
let new_offset = i + i / 15;
|
||||
alignment_map[orig_center - i - 1] = (center - new_offset - 1) as u32;
|
||||
alignment_map[orig_center + i] = (center + new_offset + 1) as u32;
|
||||
}
|
||||
}
|
||||
let mut rowOffset = 0;
|
||||
let mut row_offset = 0;
|
||||
for i in 0..layers {
|
||||
// for (int i = 0, rowOffset = 0; i < layers; i++) {
|
||||
let rowSize = (layers - i) * 4 + (if compact { 9 } else { 12 });
|
||||
let row_size = (layers - i) * 4 + (if compact { 9 } else { 12 });
|
||||
// The top-left most point of this layer is <low, low> (not including alignment lines)
|
||||
let low = i * 2;
|
||||
// The bottom-right most point of this layer is <high, high> (not including alignment lines)
|
||||
let high = baseMatrixSize as u32 - 1 - low;
|
||||
let high = base_matrix_size as u32 - 1 - low;
|
||||
// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
|
||||
for j in 0..rowSize {
|
||||
for j in 0..row_size {
|
||||
// for (int j = 0; j < rowSize; j++) {
|
||||
let columnOffset = j * 2;
|
||||
let column_offset = j * 2;
|
||||
for k in 0..2 {
|
||||
// for (int k = 0; k < 2; k++) {
|
||||
// left column
|
||||
rawbits[(rowOffset + columnOffset + k) as usize] = matrix.get(
|
||||
alignmentMap[(low + k) as usize],
|
||||
alignmentMap[(low + j) as usize],
|
||||
rawbits[(row_offset + column_offset + k) as usize] = matrix.get(
|
||||
alignment_map[(low + k) as usize],
|
||||
alignment_map[(low + j) as usize],
|
||||
);
|
||||
// bottom row
|
||||
rawbits[(rowOffset + 2 * rowSize + columnOffset + k) as usize] = matrix.get(
|
||||
alignmentMap[(low + j) as usize],
|
||||
alignmentMap[(high - k) as usize],
|
||||
rawbits[(row_offset + 2 * row_size + column_offset + k) as usize] = matrix.get(
|
||||
alignment_map[(low + j) as usize],
|
||||
alignment_map[(high - k) as usize],
|
||||
);
|
||||
// right column
|
||||
rawbits[(rowOffset + 4 * rowSize + columnOffset + k) as usize] = matrix.get(
|
||||
alignmentMap[(high - k) as usize],
|
||||
alignmentMap[(high - j) as usize],
|
||||
rawbits[(row_offset + 4 * row_size + column_offset + k) as usize] = matrix.get(
|
||||
alignment_map[(high - k) as usize],
|
||||
alignment_map[(high - j) as usize],
|
||||
);
|
||||
// top row
|
||||
rawbits[(rowOffset + 6 * rowSize + columnOffset + k) as usize] = matrix.get(
|
||||
alignmentMap[(high - j) as usize],
|
||||
alignmentMap[(low + k) as usize],
|
||||
rawbits[(row_offset + 6 * row_size + column_offset + k) as usize] = matrix.get(
|
||||
alignment_map[(high - j) as usize],
|
||||
alignment_map[(low + k) as usize],
|
||||
);
|
||||
}
|
||||
}
|
||||
rowOffset += rowSize * 8;
|
||||
row_offset += row_size * 8;
|
||||
}
|
||||
return rawbits;
|
||||
}
|
||||
@@ -534,9 +521,9 @@ fn extractBits(ddata: &AztecDetectorRXingResult, matrix: &BitMatrix) -> Vec<bool
|
||||
/**
|
||||
* Reads a code of given length and at given index in an array of bits
|
||||
*/
|
||||
fn readCode(rawbits: &[bool], start_index: usize, length: usize) -> u32 {
|
||||
fn read_code(rawbits: &[bool], start_index: usize, length: usize) -> u32 {
|
||||
let mut res = 0;
|
||||
for i in start_index..start_index+length {
|
||||
for i in start_index..start_index + length {
|
||||
// for (int i = startIndex; i < startIndex + length; i++) {
|
||||
res <<= 1;
|
||||
if rawbits[i] {
|
||||
@@ -549,12 +536,12 @@ fn readCode(rawbits: &[bool], start_index: usize, length: usize) -> u32 {
|
||||
/**
|
||||
* Reads a code of length 8 in an array of bits, padding with zeros
|
||||
*/
|
||||
fn readByte(rawbits: &[bool], start_index: usize) -> u8 {
|
||||
fn read_byte(rawbits: &[bool], start_index: usize) -> u8 {
|
||||
let n = rawbits.len() - start_index;
|
||||
if n >= 8 {
|
||||
return readCode(rawbits, start_index, 8) as u8;
|
||||
return read_code(rawbits, start_index, 8) as u8;
|
||||
}
|
||||
return (readCode(rawbits, start_index, n) << (8 - n)) as u8;
|
||||
return (read_code(rawbits, start_index, n) << (8 - n)) as u8;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -564,12 +551,12 @@ pub fn convertBoolArrayToByteArray(bool_arr: &[bool]) -> Vec<u8> {
|
||||
let mut byte_arr = vec![0u8; (bool_arr.len() + 7) / 8];
|
||||
for i in 0..byte_arr.len() {
|
||||
// for (int i = 0; i < byteArr.length; i++) {
|
||||
byte_arr[i] = readByte(bool_arr, 8 * i);
|
||||
byte_arr[i] = read_byte(bool_arr, 8 * i);
|
||||
}
|
||||
return byte_arr;
|
||||
}
|
||||
|
||||
fn totalBitsInLayer(layers: usize, compact: bool) -> usize {
|
||||
fn total_bits_in_layer(layers: usize, compact: bool) -> usize {
|
||||
(if compact { 88 } else { 112 } + 16 * layers) * layers
|
||||
// return ((compact ? 88 : 112) + 16 * layers) * layers;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ use super::{AztecCode, HighLevelEncoder};
|
||||
*/
|
||||
|
||||
pub const DEFAULT_EC_PERCENT: u32 = 33; // default minimal percentage of error check words
|
||||
pub const DEFAULT_AZTEC_LAYERS: u32 = 0;
|
||||
pub const DEFAULT_AZTEC_LAYERS: i32 = 0;
|
||||
pub const MAX_NB_BITS: u32 = 32;
|
||||
pub const MAX_NB_BITS_COMPACT: u32 = 4;
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn encode_simple(data: &str) -> Result<AztecCode, Exceptions> {
|
||||
pub fn encode(
|
||||
data: &str,
|
||||
minECCPercent: u32,
|
||||
userSpecifiedLayers: u32,
|
||||
userSpecifiedLayers: i32,
|
||||
) -> Result<AztecCode, Exceptions> {
|
||||
let bytes = encoding::all::ISO_8859_1
|
||||
.encode(data, encoding::EncoderTrap::Strict)
|
||||
@@ -92,12 +92,12 @@ pub fn encode(
|
||||
pub fn encode_with_charset(
|
||||
data: &str,
|
||||
minECCPercent: u32,
|
||||
userSpecifiedLayers: u32,
|
||||
userSpecifiedLayers: i32,
|
||||
charset: &'static dyn encoding::Encoding,
|
||||
) -> Result<AztecCode, Exceptions> {
|
||||
let bytes = charset
|
||||
.encode(data, encoding::EncoderTrap::Replace)
|
||||
.unwrap(); //data.getBytes(null != charset ? charset : StandardCharsets.ISO_8859_1);
|
||||
.encode(data, encoding::EncoderTrap::Strict)
|
||||
.expect("must be encodeable"); //data.getBytes(null != charset ? charset : StandardCharsets.ISO_8859_1);
|
||||
encode_bytes_with_charset(&bytes, minECCPercent, userSpecifiedLayers, charset)
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn encode_bytes_simple(data: &[u8]) -> Result<AztecCode, Exceptions> {
|
||||
pub fn encode_bytes(
|
||||
data: &[u8],
|
||||
minECCPercent: u32,
|
||||
userSpecifiedLayers: u32,
|
||||
userSpecifiedLayers: i32,
|
||||
) -> Result<AztecCode, Exceptions> {
|
||||
encode_bytes_with_charset(
|
||||
data,
|
||||
@@ -146,24 +146,24 @@ pub fn encode_bytes(
|
||||
*/
|
||||
pub fn encode_bytes_with_charset(
|
||||
data: &[u8],
|
||||
minECCPercent: u32,
|
||||
userSpecifiedLayers: u32,
|
||||
min_eccpercent: u32,
|
||||
user_specified_layers: i32,
|
||||
charset: &'static dyn encoding::Encoding,
|
||||
) -> Result<AztecCode, Exceptions> {
|
||||
// High-level encode
|
||||
let bits = HighLevelEncoder::with_charset(data.into(), charset).encode()?;
|
||||
|
||||
// stuff bits and choose symbol size
|
||||
let eccBits = bits.getSize() as u32 * minECCPercent / 100 + 11;
|
||||
let totalSizeBits = bits.getSize() as u32 + eccBits;
|
||||
let ecc_bits = bits.getSize() as u32 * min_eccpercent / 100 + 11;
|
||||
let total_size_bits = bits.getSize() as u32 + ecc_bits;
|
||||
let mut compact;
|
||||
let mut layers;
|
||||
let mut totalBitsInLayerVar;
|
||||
let mut wordSize;
|
||||
let mut stuffedBits;
|
||||
if userSpecifiedLayers != DEFAULT_AZTEC_LAYERS {
|
||||
compact = userSpecifiedLayers < 0;
|
||||
layers = userSpecifiedLayers;
|
||||
let mut layers:u32;
|
||||
let mut total_bits_in_layer_var;
|
||||
let mut word_size;
|
||||
let mut stuffed_bits;
|
||||
if user_specified_layers != DEFAULT_AZTEC_LAYERS {
|
||||
compact = user_specified_layers < 0;
|
||||
layers = i32::abs(user_specified_layers) as u32;
|
||||
if layers
|
||||
> (if compact {
|
||||
MAX_NB_BITS_COMPACT
|
||||
@@ -173,27 +173,27 @@ pub fn encode_bytes_with_charset(
|
||||
{
|
||||
return Err(Exceptions::IllegalArgumentException(format!(
|
||||
"Illegal value {} for layers",
|
||||
userSpecifiedLayers
|
||||
user_specified_layers
|
||||
)));
|
||||
}
|
||||
totalBitsInLayerVar = totalBitsInLayer(layers, compact);
|
||||
wordSize = WORD_SIZE[layers as usize];
|
||||
let usableBitsInLayers = totalBitsInLayerVar - (totalBitsInLayerVar % wordSize);
|
||||
stuffedBits = stuffBits(&bits, wordSize as usize);
|
||||
if stuffedBits.getSize() as u32 + eccBits > usableBitsInLayers {
|
||||
total_bits_in_layer_var = total_bits_in_layer(layers, compact);
|
||||
word_size = WORD_SIZE[layers as usize];
|
||||
let usable_bits_in_layers = total_bits_in_layer_var - (total_bits_in_layer_var % word_size);
|
||||
stuffed_bits = stuffBits(&bits, word_size as usize);
|
||||
if stuffed_bits.getSize() as u32 + ecc_bits > usable_bits_in_layers {
|
||||
return Err(Exceptions::IllegalArgumentException(
|
||||
"Data to large for user specified layer".to_owned(),
|
||||
));
|
||||
}
|
||||
if compact && stuffedBits.getSize() as u32 > wordSize * 64 {
|
||||
if compact && stuffed_bits.getSize() as u32 > word_size * 64 {
|
||||
// Compact format only allows 64 data words, though C4 can hold more words than that
|
||||
return Err(Exceptions::IllegalArgumentException(
|
||||
"Data to large for user specified layer".to_owned(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
wordSize = 0;
|
||||
stuffedBits = BitArray::new();
|
||||
word_size = 0;
|
||||
stuffed_bits = BitArray::new();
|
||||
// We look at the possible table sizes in the order Compact1, Compact2, Compact3,
|
||||
// Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1)
|
||||
// is the same size, but has more data.
|
||||
@@ -207,37 +207,38 @@ pub fn encode_bytes_with_charset(
|
||||
}
|
||||
compact = i <= 3;
|
||||
layers = if compact { i + 1 } else { i };
|
||||
totalBitsInLayerVar = totalBitsInLayer(layers, compact);
|
||||
if totalSizeBits > totalBitsInLayerVar as u32 {
|
||||
total_bits_in_layer_var = total_bits_in_layer(layers, compact);
|
||||
if total_size_bits > total_bits_in_layer_var as u32 {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// [Re]stuff the bits if this is the first opportunity, or if the
|
||||
// wordSize has changed
|
||||
if stuffedBits.getSize() == 0 || wordSize != WORD_SIZE[layers as usize] {
|
||||
wordSize = WORD_SIZE[layers as usize];
|
||||
stuffedBits = stuffBits(&bits, wordSize as usize);
|
||||
if stuffed_bits.getSize() == 0 || word_size != WORD_SIZE[layers as usize] {
|
||||
word_size = WORD_SIZE[layers as usize];
|
||||
stuffed_bits = stuffBits(&bits, word_size as usize);
|
||||
}
|
||||
let usableBitsInLayers = totalBitsInLayerVar - (totalBitsInLayerVar % wordSize);
|
||||
if compact && stuffedBits.getSize() as u32 > wordSize * 64 {
|
||||
let usable_bits_in_layers =
|
||||
total_bits_in_layer_var - (total_bits_in_layer_var % word_size);
|
||||
if compact && stuffed_bits.getSize() as u32 > word_size * 64 {
|
||||
// Compact format only allows 64 data words, though C4 can hold more words than that
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if stuffedBits.getSize() as u32 + eccBits <= usableBitsInLayers {
|
||||
if stuffed_bits.getSize() as u32 + ecc_bits <= usable_bits_in_layers {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let message_bits = generateCheckWords(
|
||||
&stuffedBits,
|
||||
totalBitsInLayerVar as usize,
|
||||
wordSize as usize,
|
||||
&stuffed_bits,
|
||||
total_bits_in_layer_var as usize,
|
||||
word_size as usize,
|
||||
);
|
||||
|
||||
// generate mode message
|
||||
let messageSizeInWords = stuffedBits.getSize() as u32 / wordSize;
|
||||
let messageSizeInWords = stuffed_bits.getSize() as u32 / word_size;
|
||||
let modeMessage = generateModeMessage(compact, layers as u32, messageSizeInWords);
|
||||
|
||||
// allocate symbol
|
||||
@@ -541,7 +542,7 @@ pub fn stuffBits(bits: &BitArray, word_size: usize) -> BitArray {
|
||||
return out;
|
||||
}
|
||||
|
||||
fn totalBitsInLayer(layers: u32, compact: bool) -> u32 {
|
||||
fn total_bits_in_layer(layers: u32, compact: bool) -> u32 {
|
||||
((if compact { 88 } else { 112 }) + 16 * layers) * layers
|
||||
// return ((compact ? 88 : 112) + 16 * layers) * layers;
|
||||
}
|
||||
|
||||
@@ -127,8 +127,8 @@ impl HighLevelEncoder {
|
||||
char_map[Self::MODE_DIGIT][b'.' as usize] = 13;
|
||||
let mixed_table = [
|
||||
'\0', ' ', '\u{1}', '\u{2}', '\u{3}', '\u{4}', '\u{5}', '\u{6}', '\u{7}', '\u{8}',
|
||||
'\t', '\n', '\u{13}', '\u{f}', '\r', '\u{33}', '\u{34}', '\u{35}', '\u{36}', '\u{37}',
|
||||
'@', '\\', '^', '_', '`', '|', '~', '\u{177}',
|
||||
'\t', '\n', '\u{000b}', '\u{000c}', '\r', '\u{001b}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{001f}',
|
||||
'@', '\\', '^', '_', '`', '|', '~', '\u{007f}',
|
||||
];
|
||||
let mut i = 0;
|
||||
while i < mixed_table.len() {
|
||||
@@ -138,15 +138,15 @@ impl HighLevelEncoder {
|
||||
// for (int i = 0; i < mixedTable.length; i++) {
|
||||
// CHAR_MAP[MODE_MIXED][mixedTable[i]] = i;
|
||||
// }
|
||||
let punctTable = [
|
||||
let punct_table = [
|
||||
b'\0', b'\r', b'\0', b'\0', b'\0', b'\0', b'!', b'\'', b'#', b'$', b'%', b'&', b'\'',
|
||||
b'(', b')', b'*', b'+', b',', b'-', b'.', b'/', b':', b';', b'<', b'=', b'>', b'?',
|
||||
b'[', b']', b'{', b'}',
|
||||
];
|
||||
let mut i = 0;
|
||||
while i < punctTable.len() {
|
||||
if punctTable[i] > 0u8 {
|
||||
char_map[Self::MODE_PUNCT][punctTable[i] as usize] = i as u8;
|
||||
while i < punct_table.len() {
|
||||
if punct_table[i] > 0u8 {
|
||||
char_map[Self::MODE_PUNCT][punct_table[i] as usize] = i as u8;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
@@ -245,7 +245,7 @@ impl HighLevelEncoder {
|
||||
pub fn encode(&self) -> Result<BitArray, Exceptions> {
|
||||
let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0);
|
||||
if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) {
|
||||
if eci != CharacterSetECI::ISO8859_1 {
|
||||
if eci != CharacterSetECI::ISO8859_1 {//} && eci != CharacterSetECI::Cp1252 {
|
||||
initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?;
|
||||
}
|
||||
} else {
|
||||
@@ -332,6 +332,8 @@ impl HighLevelEncoder {
|
||||
// }
|
||||
// });
|
||||
// Convert it to a bit array, and return.
|
||||
// dbg!(min_state.clone().toBitArray(&self.text).to_string());
|
||||
|
||||
Ok(min_state.toBitArray(&self.text))
|
||||
}
|
||||
|
||||
|
||||
@@ -85,8 +85,9 @@ impl State {
|
||||
// throw new IllegalArgumentException("ECI code must be between 0 and 999999");
|
||||
} else {
|
||||
let eci_digits = encoding::all::ISO_8859_1
|
||||
.encode(&format!("{}", eci), encoding::EncoderTrap::Replace)
|
||||
.encode(&format!("{}", eci), encoding::EncoderTrap::Strict)
|
||||
.unwrap();
|
||||
dbg!(format!("{}", eci));
|
||||
// let eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1);
|
||||
token.add(eci_digits.len() as i32, 3); // 1-6: number of ECI digits
|
||||
for eci_digit in &eci_digits {
|
||||
|
||||
@@ -2537,7 +2537,12 @@ impl CharacterSetECI {
|
||||
* but unsupported
|
||||
*/
|
||||
pub fn getCharacterSetECI(charset: &'static dyn Encoding) -> Option<CharacterSetECI> {
|
||||
match charset.name() {
|
||||
let name = if let Some(nm) = charset.whatwg_name() {
|
||||
nm
|
||||
}else {
|
||||
charset.name()
|
||||
};
|
||||
match name {
|
||||
"CP437" => Some(CharacterSetECI::Cp437),
|
||||
"iso-8859-1" => Some(CharacterSetECI::ISO8859_1),
|
||||
"iso-8859-2" => Some(CharacterSetECI::ISO8859_2),
|
||||
|
||||
@@ -373,7 +373,7 @@ pub enum EncodeHintValue {
|
||||
* A positive number (1, 2, .. 32) specifies a normal (non-compact) Aztec code.
|
||||
* (Type {@link Integer}, or {@link String} representation of the integer value).
|
||||
*/
|
||||
AztecLayers(u32),
|
||||
AztecLayers(i32),
|
||||
|
||||
/**
|
||||
* Specifies the exact version of QR code to be encoded.
|
||||
|
||||
Reference in New Issue
Block a user