steady working on qrcode encoder

This commit is contained in:
Henry Schimke
2022-10-02 17:34:53 -05:00
parent 02288dcfc3
commit bbf0b920bf
8 changed files with 1062 additions and 871 deletions

View File

@@ -1,667 +0,0 @@
/*
* Copyright 2021 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.qrcode.encoder;
import com.google.zxing.qrcode.decoder.Mode;
import com.google.zxing.qrcode.decoder.Version;
import com.google.zxing.common.BitArray;
import com.google.zxing.common.ECIEncoderSet;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Encoder that encodes minimally
*
* Algorithm:
*
* The eleventh commandment was "Thou Shalt Compute" or "Thou Shalt Not Compute" - I forget which (Alan Perilis).
*
* This implementation computes. As an alternative, the QR-Code specification suggests heuristics like this one:
*
* If initial input data is in the exclusive subset of the Alphanumeric character set AND if there are less than
* [6,7,8] characters followed by data from the remainder of the 8-bit byte character set, THEN select the 8-
* bit byte mode ELSE select Alphanumeric mode;
*
* This is probably right for 99.99% of cases but there is at least this one counter example: The string "AAAAAAa"
* encodes 2 bits smaller as ALPHANUMERIC(AAAAAA), BYTE(a) than by encoding it as BYTE(AAAAAAa).
* Perhaps that is the only counter example but without having proof, it remains unclear.
*
* ECI switching:
*
* In multi language content the algorithm selects the most compact representation using ECI modes.
* For example the most compact representation of the string "\u0150\u015C" (O-double-acute, S-circumflex) is
* ECI(UTF-8), BYTE(\u0150\u015C) while prepending one or more times the same leading character as in
* "\u0150\u0150\u015C", the most compact representation uses two ECIs so that the string is encoded as
* ECI(ISO-8859-2), BYTE(\u0150\u0150), ECI(ISO-8859-3), BYTE(\u015C).
*
* @author Alex Geller
*/
final class MinimalEncoder {
private enum VersionSize {
SMALL("version 1-9"),
MEDIUM("version 10-26"),
LARGE("version 27-40");
private final String description;
VersionSize(String description) {
this.description = description;
}
public String toString() {
return description;
}
}
private final String stringToEncode;
private final boolean isGS1;
private final ECIEncoderSet encoders;
private final ErrorCorrectionLevel ecLevel;
/**
* Creates a MinimalEncoder
*
* @param stringToEncode The string to encode
* @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
* chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
* charset to encode any character in the input that can be encoded by it if the charset is among the
* supported charsets.
* @param isGS1 {@code true} if a FNC1 is to be prepended; {@code false} otherwise
* @param ecLevel The error correction level.
* @see RXingResultList#getVersion
*/
MinimalEncoder(String stringToEncode, Charset priorityCharset, boolean isGS1, ErrorCorrectionLevel ecLevel) {
this.stringToEncode = stringToEncode;
this.isGS1 = isGS1;
this.encoders = new ECIEncoderSet(stringToEncode, priorityCharset, -1);
this.ecLevel = ecLevel;
}
/**
* Encodes the string minimally
*
* @param stringToEncode The string to encode
* @param version The preferred {@link Version}. A minimal version is computed (see
* {@link RXingResultList#getVersion method} when the value of the argument is null
* @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
* chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
* charset to encode any character in the input that can be encoded by it if the charset is among the
* supported charsets.
* @param isGS1 {@code true} if a FNC1 is to be prepended; {@code false} otherwise
* @param ecLevel The error correction level.
* @return An instance of {@code RXingResultList} representing the minimal solution.
* @see RXingResultList#getBits
* @see RXingResultList#getVersion
* @see RXingResultList#getSize
*/
static RXingResultList encode(String stringToEncode, Version version, Charset priorityCharset, boolean isGS1,
ErrorCorrectionLevel ecLevel) throws WriterException {
return new MinimalEncoder(stringToEncode, priorityCharset, isGS1, ecLevel).encode(version);
}
RXingResultList encode(Version version) throws WriterException {
if (version == null) { // compute minimal encoding trying the three version sizes.
Version[] versions = { getVersion(VersionSize.SMALL),
getVersion(VersionSize.MEDIUM),
getVersion(VersionSize.LARGE) };
RXingResultList[] results = { encodeSpecificVersion(versions[0]),
encodeSpecificVersion(versions[1]),
encodeSpecificVersion(versions[2]) };
int smallestSize = Integer.MAX_VALUE;
int smallestRXingResult = -1;
for (int i = 0; i < 3; i++) {
int size = results[i].getSize();
if (Encoder.willFit(size, versions[i], ecLevel) && size < smallestSize) {
smallestSize = size;
smallestRXingResult = i;
}
}
if (smallestRXingResult < 0) {
throw new WriterException("Data too big for any version");
}
return results[smallestRXingResult];
} else { // compute minimal encoding for a given version
RXingResultList result = encodeSpecificVersion(version);
if (!Encoder.willFit(result.getSize(), getVersion(getVersionSize(result.getVersion())), ecLevel)) {
throw new WriterException("Data too big for version" + version);
}
return result;
}
}
static VersionSize getVersionSize(Version version) {
return version.getVersionNumber() <= 9 ? VersionSize.SMALL : version.getVersionNumber() <= 26 ?
VersionSize.MEDIUM : VersionSize.LARGE;
}
static Version getVersion(VersionSize versionSize) {
switch (versionSize) {
case SMALL:
return Version.getVersionForNumber(9);
case MEDIUM:
return Version.getVersionForNumber(26);
case LARGE:
default:
return Version.getVersionForNumber(40);
}
}
static boolean isNumeric(char c) {
return c >= '0' && c <= '9';
}
static boolean isDoubleByteKanji(char c) {
return Encoder.isOnlyDoubleByteKanji(String.valueOf(c));
}
static boolean isAlphanumeric(char c) {
return Encoder.getAlphanumericCode(c) != -1;
}
boolean canEncode(Mode mode, char c) {
switch (mode) {
case KANJI: return isDoubleByteKanji(c);
case ALPHANUMERIC: return isAlphanumeric(c);
case NUMERIC: return isNumeric(c);
case BYTE: return true; // any character can be encoded as byte(s). Up to the caller to manage splitting into
// multiple bytes when String.getBytes(Charset) return more than one byte.
default:
return false;
}
}
static int getCompactedOrdinal(Mode mode) {
if (mode == null) {
return 0;
}
switch (mode) {
case KANJI:
return 0;
case ALPHANUMERIC:
return 1;
case NUMERIC:
return 2;
case BYTE:
return 3;
default:
throw new IllegalStateException("Illegal mode " + mode);
}
}
void addEdge(Edge[][][] edges, int position, Edge edge) {
int vertexIndex = position + edge.characterLength;
Edge[] modeEdges = edges[vertexIndex][edge.charsetEncoderIndex];
int modeOrdinal = getCompactedOrdinal(edge.mode);
if (modeEdges[modeOrdinal] == null || modeEdges[modeOrdinal].cachedTotalSize > edge.cachedTotalSize) {
modeEdges[modeOrdinal] = edge;
}
}
void addEdges(Version version, Edge[][][] edges, int from, Edge previous) {
int start = 0;
int end = encoders.length();
int priorityEncoderIndex = encoders.getPriorityEncoderIndex();
if (priorityEncoderIndex >= 0 && encoders.canEncode(stringToEncode.charAt(from),priorityEncoderIndex)) {
start = priorityEncoderIndex;
end = priorityEncoderIndex + 1;
}
for (int i = start; i < end; i++) {
if (encoders.canEncode(stringToEncode.charAt(from), i)) {
addEdge(edges, from, new Edge(Mode.BYTE, from, i, 1, previous, version));
}
}
if (canEncode(Mode.KANJI, stringToEncode.charAt(from))) {
addEdge(edges, from, new Edge(Mode.KANJI, from, 0, 1, previous, version));
}
int inputLength = stringToEncode.length();
if (canEncode(Mode.ALPHANUMERIC, stringToEncode.charAt(from))) {
addEdge(edges, from, new Edge(Mode.ALPHANUMERIC, from, 0, from + 1 >= inputLength ||
!canEncode(Mode.ALPHANUMERIC, stringToEncode.charAt(from + 1)) ? 1 : 2, previous, version));
}
if (canEncode(Mode.NUMERIC, stringToEncode.charAt(from))) {
addEdge(edges, from, new Edge(Mode.NUMERIC, from, 0, from + 1 >= inputLength ||
!canEncode(Mode.NUMERIC, stringToEncode.charAt(from + 1)) ? 1 : from + 2 >= inputLength ||
!canEncode(Mode.NUMERIC, stringToEncode.charAt(from + 2)) ? 2 : 3, previous, version));
}
}
RXingResultList encodeSpecificVersion(Version version) throws WriterException {
@SuppressWarnings("checkstyle:lineLength")
/* A vertex represents a tuple of a position in the input, a mode and a character encoding where position 0
* denotes the position left of the first character, 1 the position left of the second character and so on.
* Likewise the end vertices are located after the last character at position stringToEncode.length().
*
* An edge leading to such a vertex encodes one or more of the characters left of the position that the vertex
* represents and encodes it in the same encoding and mode as the vertex on which the edge ends. In other words,
* all edges leading to a particular vertex encode the same characters in the same mode with the same character
* encoding. They differ only by their source vertices who are all located at i+1 minus the number of encoded
* characters.
*
* The edges leading to a vertex are stored in such a way that there is a fast way to enumerate the edges ending
* on a particular vertex.
*
* The algorithm processes the vertices in order of their position thereby performing the following:
*
* For every vertex at position i the algorithm enumerates the edges ending on the vertex and removes all but the
* shortest from that list.
* Then it processes the vertices for the position i+1. If i+1 == stringToEncode.length() then the algorithm ends
* and chooses the the edge with the smallest size from any of the edges leading to vertices at this position.
* Otherwise the algorithm computes all possible outgoing edges for the vertices at the position i+1
*
* Examples:
* The process is illustrated by showing the graph (edges) after each iteration from left to right over the input:
* An edge is drawn as follows "(" + fromVertex + ") -- " + encodingMode + "(" + encodedInput + ") (" +
* accumulatedSize + ") --> (" + toVertex + ")"
*
* Example 1 encoding the string "ABCDE":
* Note: This example assumes that alphanumeric encoding is only possible in multiples of two characters so that
* the example is both short and showing the principle. In reality this restriction does not exist.
*
* Initial situation
* (initial) -- BYTE(A) (20) --> (1_BYTE)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 1
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 2
* (initial) -- BYTE(A) (20) --> (1_BYTE)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- BYTE(C) (44) --> (3_BYTE)
* (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 3
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- BYTE(D) (64) --> (4_BYTE)
* (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
* (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 4
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE) -- BYTE(D) (44) --> (4_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC) -- BYTE(E) (55) --> (5_BYTE)
*
* Situation after adding edges to vertices at position 5
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE) -- BYTE(D) (44) --> (4_BYTE) -- BYTE(E) (52) --> (5_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Encoding as BYTE(ABCDE) has the smallest size of 52 and is hence chosen. The encodation ALPHANUMERIC(ABCD),
* BYTE(E) is longer with a size of 55.
*
* Example 2 encoding the string "XXYY" where X denotes a character unique to character set ISO-8859-2 and Y a
* character unique to ISO-8859-3. Both characters encode as double byte in UTF-8:
*
* Initial situation
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 1
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2)
* (1_BYTE_ISO-8859-2) -- BYTE(X) (72) --> (2_BYTE_UTF-8)
* (1_BYTE_ISO-8859-2) -- BYTE(X) (72) --> (2_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 2
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (80) --> (3_BYTE_UTF-8)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (80) --> (3_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 3
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (80) --> (4_BYTE_ISO-8859-3)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (112) --> (4_BYTE_UTF-8)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (112) --> (4_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8) -- BYTE(Y) (72) --> (3_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE) -- BYTE(Y) (72) --> (3_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 4
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3) -- BYTE(Y) (80) --> (4_BYTE_ISO-8859-3)
* (3_BYTE_UTF-8) -- BYTE(Y) (88) --> (4_BYTE_UTF-8)
* (3_BYTE_UTF-16BE) -- BYTE(Y) (88) --> (4_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8) -- BYTE(Y) (72) --> (3_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE) -- BYTE(Y) (72) --> (3_BYTE_UTF-16BE)
*
* Encoding as ECI(ISO-8859-2),BYTE(XX),ECI(ISO-8859-3),BYTE(YY) has the smallest size of 80 and is hence chosen.
* The encodation ECI(UTF-8),BYTE(XXYY) is longer with a size of 88.
*/
int inputLength = stringToEncode.length();
// Array that represents vertices. There is a vertex for every character, encoding and mode. The vertex contains
// a list of all edges that lead to it that have the same encoding and mode.
// The lists are created lazily
// The last dimension in the array below encodes the 4 modes KANJI, ALPHANUMERIC, NUMERIC and BYTE via the
// function getCompactedOrdinal(Mode)
Edge[][][] edges = new Edge[inputLength + 1][encoders.length()][4];
addEdges(version, edges, 0, null);
for (int i = 1; i <= inputLength; i++) {
for (int j = 0; j < encoders.length(); j++) {
for (int k = 0; k < 4; k++) {
if (edges[i][j][k] != null && i < inputLength) {
addEdges(version, edges, i, edges[i][j][k]);
}
}
}
}
int minimalJ = -1;
int minimalK = -1;
int minimalSize = Integer.MAX_VALUE;
for (int j = 0; j < encoders.length(); j++) {
for (int k = 0; k < 4; k++) {
if (edges[inputLength][j][k] != null) {
Edge edge = edges[inputLength][j][k];
if (edge.cachedTotalSize < minimalSize) {
minimalSize = edge.cachedTotalSize;
minimalJ = j;
minimalK = k;
}
}
}
}
if (minimalJ < 0) {
throw new WriterException("Internal error: failed to encode \"" + stringToEncode + "\"");
}
return new RXingResultList(version, edges[inputLength][minimalJ][minimalK]);
}
private final class Edge {
private final Mode mode;
private final int fromPosition;
private final int charsetEncoderIndex;
private final int characterLength;
private final Edge previous;
private final int cachedTotalSize;
private Edge(Mode mode, int fromPosition, int charsetEncoderIndex, int characterLength, Edge previous,
Version version) {
this.mode = mode;
this.fromPosition = fromPosition;
this.charsetEncoderIndex = mode == Mode.BYTE || previous == null ? charsetEncoderIndex :
previous.charsetEncoderIndex; // inherit the encoding if not of type BYTE
this.characterLength = characterLength;
this.previous = previous;
int size = previous != null ? previous.cachedTotalSize : 0;
boolean needECI = mode == Mode.BYTE &&
(previous == null && this.charsetEncoderIndex != 0) || // at the beginning and charset is not ISO-8859-1
(previous != null && this.charsetEncoderIndex != previous.charsetEncoderIndex);
if (previous == null || mode != previous.mode || needECI) {
size += 4 + mode.getCharacterCountBits(version);
}
switch (mode) {
case KANJI:
size += 13;
break;
case ALPHANUMERIC:
size += characterLength == 1 ? 6 : 11;
break;
case NUMERIC:
size += characterLength == 1 ? 4 : characterLength == 2 ? 7 : 10;
break;
case BYTE:
size += 8 * encoders.encode(stringToEncode.substring(fromPosition, fromPosition + characterLength),
charsetEncoderIndex).length;
if (needECI) {
size += 4 + 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
}
break;
}
cachedTotalSize = size;
}
}
final class RXingResultList {
private final List<RXingResultList.RXingResultNode> list = new ArrayList<>();
private final Version version;
RXingResultList(Version version, Edge solution) {
int length = 0;
Edge current = solution;
boolean containsECI = false;
while (current != null) {
length += current.characterLength;
Edge previous = current.previous;
boolean needECI = current.mode == Mode.BYTE &&
(previous == null && current.charsetEncoderIndex != 0) || // at the beginning and charset is not ISO-8859-1
(previous != null && current.charsetEncoderIndex != previous.charsetEncoderIndex);
if (needECI) {
containsECI = true;
}
if (previous == null || previous.mode != current.mode || needECI) {
list.add(0, new RXingResultNode(current.mode, current.fromPosition, current.charsetEncoderIndex, length));
length = 0;
}
if (needECI) {
list.add(0, new RXingResultNode(Mode.ECI, current.fromPosition, current.charsetEncoderIndex, 0));
}
current = previous;
}
// prepend FNC1 if needed. If the bits contain an ECI then the FNC1 must be preceeded by an ECI.
// If there is no ECI at the beginning then we put an ECI to the default charset (ISO-8859-1)
if (isGS1) {
RXingResultNode first = list.get(0);
if (first != null && first.mode != Mode.ECI && containsECI) {
// prepend a default character set ECI
list.add(0, new RXingResultNode(Mode.ECI, 0, 0, 0));
}
first = list.get(0);
// prepend or insert a FNC1_FIRST_POSITION after the ECI (if any)
list.add(first.mode != Mode.ECI ? 0 : 1, new RXingResultNode(Mode.FNC1_FIRST_POSITION, 0, 0, 0));
}
// set version to smallest version into which the bits fit.
int versionNumber = version.getVersionNumber();
int lowerLimit;
int upperLimit;
switch (getVersionSize(version)) {
case SMALL:
lowerLimit = 1;
upperLimit = 9;
break;
case MEDIUM:
lowerLimit = 10;
upperLimit = 26;
break;
case LARGE:
default:
lowerLimit = 27;
upperLimit = 40;
break;
}
int size = getSize(version);
// increase version if needed
while (versionNumber < upperLimit && !Encoder.willFit(size, Version.getVersionForNumber(versionNumber),
ecLevel)) {
versionNumber++;
}
// shrink version if possible
while (versionNumber > lowerLimit && Encoder.willFit(size, Version.getVersionForNumber(versionNumber - 1),
ecLevel)) {
versionNumber--;
}
this.version = Version.getVersionForNumber(versionNumber);
}
/**
* returns the size in bits
*/
int getSize() {
return getSize(version);
}
private int getSize(Version version) {
int result = 0;
for (RXingResultNode resultNode : list) {
result += resultNode.getSize(version);
}
return result;
}
/**
* appends the bits
*/
void getBits(BitArray bits) throws WriterException {
for (RXingResultNode resultNode : list) {
resultNode.getBits(bits);
}
}
Version getVersion() {
return version;
}
public String toString() {
StringBuilder result = new StringBuilder();
RXingResultNode previous = null;
for (RXingResultNode current : list) {
if (previous != null) {
result.append(",");
}
result.append(current.toString());
previous = current;
}
return result.toString();
}
final class RXingResultNode {
private final Mode mode;
private final int fromPosition;
private final int charsetEncoderIndex;
private final int characterLength;
RXingResultNode(Mode mode, int fromPosition, int charsetEncoderIndex, int characterLength) {
this.mode = mode;
this.fromPosition = fromPosition;
this.charsetEncoderIndex = charsetEncoderIndex;
this.characterLength = characterLength;
}
/**
* returns the size in bits
*/
private int getSize(Version version) {
int size = 4 + mode.getCharacterCountBits(version);
switch (mode) {
case KANJI:
size += 13 * characterLength;
break;
case ALPHANUMERIC:
size += (characterLength / 2) * 11;
size += (characterLength % 2) == 1 ? 6 : 0;
break;
case NUMERIC:
size += (characterLength / 3) * 10;
int rest = characterLength % 3;
size += rest == 1 ? 4 : rest == 2 ? 7 : 0;
break;
case BYTE:
size += 8 * getCharacterCountIndicator();
break;
case ECI:
size += 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
}
return size;
}
/**
* returns the length in characters according to the specification (differs from getCharacterLength() in BYTE mode
* for multi byte encoded characters)
*/
private int getCharacterCountIndicator() {
return mode == Mode.BYTE ?
encoders.encode(stringToEncode.substring(fromPosition, fromPosition + characterLength),
charsetEncoderIndex).length : characterLength;
}
/**
* appends the bits
*/
private void getBits(BitArray bits) throws WriterException {
bits.appendBits(mode.getBits(), 4);
if (characterLength > 0) {
int length = getCharacterCountIndicator();
bits.appendBits(length, mode.getCharacterCountBits(version));
}
if (mode == Mode.ECI) {
bits.appendBits(encoders.getECIValue(charsetEncoderIndex), 8);
} else if (characterLength > 0) {
// append data
Encoder.appendBytes(stringToEncode.substring(fromPosition, fromPosition + characterLength), mode, bits,
encoders.getCharset(charsetEncoderIndex));
}
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append(mode).append('(');
if (mode == Mode.ECI) {
result.append(encoders.getCharset(charsetEncoderIndex).displayName());
} else {
result.append(makePrintable(stringToEncode.substring(fromPosition, fromPosition + characterLength)));
}
result.append(')');
return result.toString();
}
private String makePrintable(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < 32 || s.charAt(i) > 126) {
result.append('.');
} else {
result.append(s.charAt(i));
}
}
return result.toString();
}
}
}
}

View File

@@ -14,53 +14,58 @@
* limitations under the License.
*/
package com.google.zxing.qrcode.encoder;
// package com.google.zxing.qrcode.encoder;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitArray;
import com.google.zxing.common.StringUtils;
import com.google.zxing.common.CharacterSetECI;
import com.google.zxing.common.reedsolomon.GenericGF;
import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.decoder.Mode;
import com.google.zxing.qrcode.decoder.Version;
// import com.google.zxing.EncodeHintType;
// import com.google.zxing.WriterException;
// import com.google.zxing.common.BitArray;
// import com.google.zxing.common.StringUtils;
// import com.google.zxing.common.CharacterSetECI;
// import com.google.zxing.common.reedsolomon.GenericGF;
// import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
// import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
// import com.google.zxing.qrcode.decoder.Mode;
// import com.google.zxing.qrcode.decoder.Version;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
// import java.nio.charset.Charset;
// import java.nio.charset.StandardCharsets;
// import java.util.ArrayList;
// import java.util.Collection;
// import java.util.Map;
use std::collections::HashMap;
use encoding::EncodingRef;
use crate::{EncodingHintDictionary, common::{BitArray, CharacterSetECI, reedsolomon::{ReedSolomonEncoder, get_predefined_genericgf, PredefinedGenericGF}, StringUtils}, Exceptions, qrcode::decoder::{ErrorCorrectionLevel, Mode, VersionRef, Version}};
use super::{mask_util, ByteMatrix, QRCode, matrix_util};
/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
*/
public final class Encoder {
// The original table is defined in the table 5 of JISX0510:2004 (p.19).
private static final int[] ALPHANUMERIC_TABLE = {
const ALPHANUMERIC_TABLE : [i8;96]= [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
};
];
static final Charset DEFAULT_BYTE_MODE_ENCODING = StandardCharsets.ISO_8859_1;
const DEFAULT_BYTE_MODE_ENCODING : EncodingRef = encoding::all::ISO_8859_1;
private Encoder() {
}
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
private static int calculateMaskPenalty(ByteMatrix matrix) {
return MaskUtil.applyMaskPenaltyRule1(matrix)
+ MaskUtil.applyMaskPenaltyRule2(matrix)
+ MaskUtil.applyMaskPenaltyRule3(matrix)
+ MaskUtil.applyMaskPenaltyRule4(matrix);
pub fn calculateMaskPenalty( matrix:&ByteMatrix) -> u32{
return mask_util::applyMaskPenaltyRule1(matrix)
+ mask_util::applyMaskPenaltyRule2(matrix)
+ mask_util::applyMaskPenaltyRule3(matrix)
+ mask_util::applyMaskPenaltyRule4(matrix);
}
/**
@@ -70,26 +75,26 @@ public final class Encoder {
* @throws WriterException if encoding can't succeed, because of for example invalid content
* or configuration
*/
public static QRCode encode(String content, ErrorCorrectionLevel ecLevel) throws WriterException {
return encode(content, ecLevel, null);
pub fn encode( content:&str, ecLevel:&ErrorCorrectionLevel) -> Result<QRCode, Exceptions> {
return encode_with_hints(content, ecLevel, HashMap::new());
}
public static QRCode encode(String content,
ErrorCorrectionLevel ecLevel,
Map<EncodeHintType,?> hints) throws WriterException {
pub fn encode_with_hints( content:&str,
ecLevel:&ErrorCorrectionLevel,
hints:EncodingHintDictionary) -> Result<QRCode, Exceptions> {
Version version;
BitArray headerAndDataBits;
Mode mode;
let version;
let headerAndDataBits;
let mode;
boolean hasGS1FormatHint = hints != null && hints.containsKey(EncodeHintType.GS1_FORMAT) &&
Boolean.parseBoolean(hints.get(EncodeHintType.GS1_FORMAT).toString());
boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.QR_COMPACT) &&
Boolean.parseBoolean(hints.get(EncodeHintType.QR_COMPACT).toString());
let hasGS1FormatHint = hints != null && hints.containsKey(EncodeHintType::GS1_FORMAT) &&
Boolean.parseBoolean(hints.get(EncodeHintType::GS1_FORMAT).toString());
let hasCompactionHint = hints != null && hints.containsKey(EncodeHintType::QR_COMPACT) &&
Boolean.parseBoolean(hints.get(EncodeHintType::QR_COMPACT).toString());
// Determine what character encoding has been specified by the caller, if any
Charset encoding = DEFAULT_BYTE_MODE_ENCODING;
boolean hasEncodingHint = hints != null && hints.containsKey(EncodeHintType.CHARACTER_SET);
let encoding = DEFAULT_BYTE_MODE_ENCODING;
let hasEncodingHint = hints != null && hints.containsKey(EncodeHintType::CHARACTER_SET);
if (hasEncodingHint) {
encoding = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
}
@@ -191,7 +196,7 @@ public final class Encoder {
qrCode.setMaskPattern(maskPattern);
// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
matrix_util::buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
qrCode.setMatrix(matrix);
return qrCode;
@@ -202,25 +207,25 @@ public final class Encoder {
*
* @throws WriterException if the data cannot fit in any version
*/
private static Version recommendVersion(ErrorCorrectionLevel ecLevel,
Mode mode,
BitArray headerBits,
BitArray dataBits) throws WriterException {
fn recommendVersion( ecLevel:&ErrorCorrectionLevel,
mode:Mode,
headerBits:&BitArray,
dataBits:&BitArray) -> Result<VersionRef,Exceptions> {
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
int provisionalBitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1));
Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
let provisionalBitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, Version::getVersionForNumber(1));
let provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
int bitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);
let bitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);
return chooseVersion(bitsNeeded, ecLevel);
}
private static int calculateBitsNeeded(Mode mode,
BitArray headerBits,
BitArray dataBits,
Version version) {
fn calculateBitsNeeded( mode:Mode,
headerBits:&BitArray,
dataBits:&BitArray,
version:VersionRef) -> u32 {
return headerBits.getSize() + mode.getCharacterCountBits(version) + dataBits.getSize();
}
@@ -228,22 +233,22 @@ public final class Encoder {
* @return the code point of the table used in alphanumeric mode or
* -1 if there is no corresponding code in the table.
*/
static int getAlphanumericCode(int code) {
if (code < ALPHANUMERIC_TABLE.length) {
pub fn getAlphanumericCode( code:u32) -> u32{
if code < ALPHANUMERIC_TABLE.len() {
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
public static Mode chooseMode(String content) {
return chooseMode(content, null);
pub fn chooseMode( content:&str) -> Mode{
return chooseModeWithEncoding(content, None);
}
/**
* Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
* if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
*/
private static Mode chooseMode(String content, Charset encoding) {
fn chooseModeWithEncoding( content:&str, encoding:Option<EncodingRef>) -> Mode{
if (StringUtils.SHIFT_JIS_CHARSET.equals(encoding) && isOnlyDoubleByteKanji(content)) {
// Choose Kanji mode if all input are double-byte characters
return Mode.KANJI;
@@ -269,32 +274,36 @@ public final class Encoder {
return Mode.BYTE;
}
static boolean isOnlyDoubleByteKanji(String content) {
byte[] bytes = content.getBytes(StringUtils.SHIFT_JIS_CHARSET);
int length = bytes.length;
if (length % 2 != 0) {
pub fn isOnlyDoubleByteKanji( content:&str) -> bool{
let bytes = content.getBytes(StringUtils::SHIFT_JIS_CHARSET);
let length = bytes.len();
if length % 2 != 0 {
return false;
}
for (int i = 0; i < length; i += 2) {
int byte1 = bytes[i] & 0xFF;
if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
let mut i = 0;
while i < length {
// for (int i = 0; i < length; i += 2) {
let byte1 = bytes[i] & 0xFF;
if (byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB) {
return false;
}
i+=2;
}
return true;
}
private static int chooseMaskPattern(BitArray bits,
ErrorCorrectionLevel ecLevel,
Version version,
ByteMatrix matrix) throws WriterException {
fn chooseMaskPattern( bits:&BitArray,
ecLevel:&ErrorCorrectionLevel,
version:VersionRef,
matrix:&ByteMatrix) -> Result<u32, Exceptions> {
int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
int bestMaskPattern = -1;
let minPenalty = u32::MAX; // Lower penalty is better.
let bestMaskPattern = -1;
// We try all mask patterns to choose the best one.
for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
int penalty = calculateMaskPenalty(matrix);
for maskPattern in 0..QRCode::NUM_MASK_PATTERNS {
// for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
matrix_util::buildMatrix(bits, ecLevel, version, maskPattern, matrix);
let penalty = calculateMaskPenalty(matrix);
if (penalty < minPenalty) {
minPenalty = penalty;
bestMaskPattern = maskPattern;
@@ -303,38 +312,39 @@ public final class Encoder {
return bestMaskPattern;
}
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
for (int versionNum = 1; versionNum <= 40; versionNum++) {
Version version = Version.getVersionForNumber(versionNum);
if (willFit(numInputBits, version, ecLevel)) {
fn chooseVersion( numInputBits:u32, ecLevel:&ErrorCorrectionLevel) -> Result<VersionRef,Exceptions> {
for versionNum in 1..=40 {
// for (int versionNum = 1; versionNum <= 40; versionNum++) {
let version = Version::getVersionForNumber(versionNum);
if willFit(numInputBits, version, ecLevel) {
return version;
}
}
throw new WriterException("Data too big");
Err(Exceptions::WriterException("Data too big".to_owned()));
}
/**
* @return true if the number of input bits will fit in a code with the specified version and
* error correction level.
*/
static boolean willFit(int numInputBits, Version version, ErrorCorrectionLevel ecLevel) {
pub fn willFit( numInputBits:u32, version:VersionRef, ecLevel:&ErrorCorrectionLevel) -> bool {
// In the following comments, we use numbers of Version 7-H.
// numBytes = 196
int numBytes = version.getTotalCodewords();
let numBytes = version.getTotalCodewords();
// getNumECBytes = 130
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numEcBytes = ecBlocks.getTotalECCodewords();
let ecBlocks = version.getECBlocksForLevel(ecLevel);
let numEcBytes = ecBlocks.getTotalECCodewords();
// getNumDataBytes = 196 - 130 = 66
int numDataBytes = numBytes - numEcBytes;
int totalInputBytes = (numInputBits + 7) / 8;
let numDataBytes = numBytes - numEcBytes;
let totalInputBytes = (numInputBits + 7) / 8;
return numDataBytes >= totalInputBytes;
}
/**
* Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
*/
static void terminateBits(int numDataBytes, BitArray bits) throws WriterException {
int capacity = numDataBytes * 8;
pub fn terminateBits( numDataBytes:u32, bits:&BitArray) -> Result<(),Exceptions> {
let capacity = numDataBytes * 8;
if (bits.getSize() > capacity) {
throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " > " +
capacity);
@@ -366,13 +376,13 @@ public final class Encoder {
* the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
* JISX0510:2004 (p.30)
*/
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes,
int numDataBytes,
int numRSBlocks,
int blockID,
int[] numDataBytesInBlock,
int[] numECBytesInBlock) throws WriterException {
if (blockID >= numRSBlocks) {
pub fn getNumDataBytesAndNumECBytesForBlockID( numTotalBytes:u32,
numDataBytes:u32,
numRSBlocks:u32,
blockID:u32,
numDataBytesInBlock:&[u32],
numECBytesInBlock:&[u32]) -> Result<(),Exceptions> {
if blockID >= numRSBlocks {
throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
@@ -422,36 +432,37 @@ public final class Encoder {
* Interleave "bits" with corresponding error correction bytes. On success, store the result in
* "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
*/
static BitArray interleaveWithECBytes(BitArray bits,
int numTotalBytes,
int numDataBytes,
int numRSBlocks) throws WriterException {
pub fn interleaveWithECBytes( bits:&BitArray,
numTotalBytes:u32,
numDataBytes:u32,
numRSBlocks:u32) -> Result<BitArray,Exceptions> {
// "bits" must have "getNumDataBytes" bytes of data.
if (bits.getSizeInBytes() != numDataBytes) {
throw new WriterException("Number of bits and data bytes does not match");
if bits.getSizeInBytes() != numDataBytes {
return Err(Exceptions::WriterException("Number of bits and data bytes does not match".to_owned()))
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
int dataBytesOffset = 0;
int maxNumDataBytes = 0;
int maxNumEcBytes = 0;
let dataBytesOffset = 0;
let maxNumDataBytes = 0;
let maxNumEcBytes = 0;
// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
Collection<BlockPair> blocks = new ArrayList<>(numRSBlocks);
let blocks = Vec::new();
for (int i = 0; i < numRSBlocks; ++i) {
int[] numDataBytesInBlock = new int[1];
int[] numEcBytesInBlock = new int[1];
for i in 0..numRSBlocks {
// for (int i = 0; i < numRSBlocks; ++i) {
let numDataBytesInBlock = new int[1];
let numEcBytesInBlock = new int[1];
getNumDataBytesAndNumECBytesForBlockID(
numTotalBytes, numDataBytes, numRSBlocks, i,
numDataBytesInBlock, numEcBytesInBlock);
int size = numDataBytesInBlock[0];
byte[] dataBytes = new byte[size];
let size = numDataBytesInBlock[0];
let dataBytes = new byte[size];
bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
let ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
blocks.add(new BlockPair(dataBytes, ecBytes));
maxNumDataBytes = Math.max(maxNumDataBytes, size);
@@ -459,10 +470,10 @@ public final class Encoder {
dataBytesOffset += numDataBytesInBlock[0];
}
if (numDataBytes != dataBytesOffset) {
throw new WriterException("Data bytes does not match offset");
return Err(Exceptions::WriterException("Data bytes does not match offset".to_owned()))
}
BitArray result = new BitArray();
let result = BitArray::new();
// First, place data blocks.
for (int i = 0; i < maxNumDataBytes; ++i) {
@@ -490,17 +501,20 @@ public final class Encoder {
return result;
}
static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) {
int numDataBytes = dataBytes.length;
int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
for (int i = 0; i < numDataBytes; i++) {
pub fn generateECBytes( dataBytes:&[u8], numEcBytesInBlock:u32) -> Vec<u8> {
let numDataBytes = dataBytes.length;
let toEncode = vec![0;numDataBytes + numEcBytesInBlock];
for i in 0..numDataBytes {
// for (int i = 0; i < numDataBytes; i++) {
toEncode[i] = dataBytes[i] & 0xFF;
}
new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock);
ReedSolomonEncoder::new(get_predefined_genericgf(PredefinedGenericGF::QrCodeField256)).encode(&mut toEncode, numEcBytesInBlock);
byte[] ecBytes = new byte[numEcBytesInBlock];
for (int i = 0; i < numEcBytesInBlock; i++) {
ecBytes[i] = (byte) toEncode[numDataBytes + i];
let ecBytes = vec![0u8;numEcBytesInBlock];
for i in 0..numEcBytesInBlock {
// for (int i = 0; i < numEcBytesInBlock; i++) {
ecBytes[i] = toEncode[numDataBytes + i];
}
return ecBytes;
}
@@ -508,7 +522,7 @@ public final class Encoder {
/**
* Append mode info. On success, store the result in "bits".
*/
static void appendModeInfo(Mode mode, BitArray bits) {
pub fn appendModeInfo( mode:Mode, bits:&BitArray) {
bits.appendBits(mode.getBits(), 4);
}
@@ -516,75 +530,84 @@ public final class Encoder {
/**
* Append length info. On success, store the result in "bits".
*/
static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits) throws WriterException {
int numBits = mode.getCharacterCountBits(version);
if (numLetters >= (1 << numBits)) {
throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1));
pub fn appendLengthInfo( numLetters:u32, version:VersionRef, mode:Mode, bits:&BitArray) -> Result<(),Exceptions> {
let numBits = mode.getCharacterCountBits(version);
if numLetters >= (1 << numBits) {
return Err(Exceptions::WriterExceptin(format!("{} is bigger than {}" ,numLetters , ((1 << numBits) - 1))))
}
bits.appendBits(numLetters, numBits);
Ok(())
}
/**
* Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
*/
static void appendBytes(String content,
Mode mode,
BitArray bits,
Charset encoding) throws WriterException {
switch (mode) {
case NUMERIC:
appendNumericBytes(content, bits);
break;
case ALPHANUMERIC:
appendAlphanumericBytes(content, bits);
break;
case BYTE:
append8BitBytes(content, bits, encoding);
break;
case KANJI:
appendKanjiBytes(content, bits);
break;
default:
throw new WriterException("Invalid mode: " + mode);
}
pub fn appendBytes( content:&str,
mode:Mode,
bits:&BitArray,
encoding:EncodingRef) -> Result<(),Exceptions>{
match mode {
Mode::NUMERIC => Ok(appendNumericBytes(content, bits)),
Mode::ALPHANUMERIC => Ok(appendAlphanumericBytes(content, bits)),
Mode::BYTE => Ok(append8BitBytes(content, bits, encoding)),
Mode::KANJI => Ok(appendKanjiBytes(content, bits)),
_=> Err(Exceptions::WriterException(format!("Invalid mode: {}" , mode)))
}
// switch (mode) {
// case NUMERIC:
// appendNumericBytes(content, bits);
// break;
// case ALPHANUMERIC:
// appendAlphanumericBytes(content, bits);
// break;
// case BYTE:
// append8BitBytes(content, bits, encoding);
// break;
// case KANJI:
// appendKanjiBytes(content, bits);
// break;
// default:
// throw new WriterException("Invalid mode: " + mode);
// }
}
static void appendNumericBytes(CharSequence content, BitArray bits) {
int length = content.length();
int i = 0;
while (i < length) {
int num1 = content.charAt(i) - '0';
if (i + 2 < length) {
pub fn appendNumericBytes( content:&str, bits:&BitArray) {
let length = content.length();
let i = 0;
while i < length {
let num1 = content.charAt(i) - '0';
if i + 2 < length {
// Encode three numeric letters in ten bits.
int num2 = content.charAt(i + 1) - '0';
int num3 = content.charAt(i + 2) - '0';
let num2 = content.charAt(i + 1) - '0';
let num3 = content.charAt(i + 2) - '0';
bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
i += 3;
} else if (i + 1 < length) {
} else if i + 1 < length {
// Encode two numeric letters in seven bits.
int num2 = content.charAt(i + 1) - '0';
let num2 = content.charAt(i + 1) - '0';
bits.appendBits(num1 * 10 + num2, 7);
i += 2;
} else {
// Encode one numeric letter in four bits.
bits.appendBits(num1, 4);
i++;
i+=1;
}
}
}
static void appendAlphanumericBytes(CharSequence content, BitArray bits) throws WriterException {
int length = content.length();
int i = 0;
while (i < length) {
int code1 = getAlphanumericCode(content.charAt(i));
if (code1 == -1) {
throw new WriterException();
pub fn appendAlphanumericBytes( content:&str, bits:&BitArray) -> Result<(),Exceptions> {
let length = content.len();
let i = 0;
while i < length {
let code1 = getAlphanumericCode(content.charAt(i));
if code1 == -1 {
return Err(Exceptions::WriterException("".to_owned()));
}
if (i + 1 < length) {
int code2 = getAlphanumericCode(content.charAt(i + 1));
if i + 1 < length {
let code2 = getAlphanumericCode(content.charAt(i + 1));
if (code2 == -1) {
throw new WriterException();
return Err(Exceptions::WriterException("".to_owned()));
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1 * 45 + code2, 11);
@@ -592,46 +615,52 @@ public final class Encoder {
} else {
// Encode one alphanumeric letter in six bits.
bits.appendBits(code1, 6);
i++;
i+=1;
}
}
Ok(())
}
static void append8BitBytes(String content, BitArray bits, Charset encoding) {
byte[] bytes = content.getBytes(encoding);
for (byte b : bytes) {
fn append8BitBytes( content:&str, bits:&BitArray, encoding:EncodingRef) {
let bytes = content.getBytes(encoding);
for b in bytes {
// for (byte b : bytes) {
bits.appendBits(b, 8);
}
}
static void appendKanjiBytes(String content, BitArray bits) throws WriterException {
byte[] bytes = content.getBytes(StringUtils.SHIFT_JIS_CHARSET);
if (bytes.length % 2 != 0) {
throw new WriterException("Kanji byte size not even");
fn appendKanjiBytes( content:&str, bits:&BitArray) -> Result<(),Exceptions> {
let bytes = content.getBytes(StringUtils::SHIFT_JIS_CHARSET);
if bytes.length % 2 != 0 {
return Err(Exceptions::WriterException("Kanji byte size not even".to_owned()))
}
int maxI = bytes.length - 1; // bytes.length must be even
for (int i = 0; i < maxI; i += 2) {
int byte1 = bytes[i] & 0xFF;
int byte2 = bytes[i + 1] & 0xFF;
int code = (byte1 << 8) | byte2;
int subtracted = -1;
if (code >= 0x8140 && code <= 0x9ffc) {
let maxI = bytes.length - 1; // bytes.length must be even
let mut i = 0;
while i < maxI {
// for (int i = 0; i < maxI; i += 2) {
let byte1 = bytes[i] & 0xFF;
let byte2 = bytes[i + 1] & 0xFF;
let code = (byte1 << 8) | byte2;
let subtracted = -1;
if code >= 0x8140 && code <= 0x9ffc {
subtracted = code - 0x8140;
} else if (code >= 0xe040 && code <= 0xebbf) {
subtracted = code - 0xc140;
}
if (subtracted == -1) {
throw new WriterException("Invalid byte sequence");
if subtracted == -1 {
return Err(Exceptions::WriterException("Invalid byte sequence".to_owned()))
}
int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded, 13);
i+=2;
}
Ok(())
}
private static void appendECI(CharacterSetECI eci, BitArray bits) {
bits.appendBits(Mode.ECI.getBits(), 4);
fn appendECI( eci:&CharacterSetECI, bits:&BitArray) {
bits.appendBits(Mode::ECI.getBits(), 4);
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.getValue(), 8);
}
}

View File

@@ -0,0 +1,818 @@
/*
* Copyright 2021 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::{fmt, rc::Rc};
use encoding::EncodingRef;
use crate::{common::{ECIEncoderSet, BitArray}, qrcode::decoder::{ErrorCorrectionLevel, Version, Mode, VersionRef}, Exceptions};
use super::encoder;
enum VersionSize {
SMALL,//("version 1-9"),
MEDIUM,//("version 10-26"),
LARGE,//("version 27-40");
// private final String description;
// VersionSize(String description) {
// this.description = description;
// }
// public String toString() {
// return description;
// }
}
impl fmt::Display for VersionSize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!( f, "{}", match self {
VersionSize::SMALL => "version 1-9",
VersionSize::MEDIUM => "version 10-26",
VersionSize::LARGE => "version 27-40",
})
}
}
/**
* Encoder that encodes minimally
*
* Algorithm:
*
* The eleventh commandment was "Thou Shalt Compute" or "Thou Shalt Not Compute" - I forget which (Alan Perilis).
*
* This implementation computes. As an alternative, the QR-Code specification suggests heuristics like this one:
*
* If initial input data is in the exclusive subset of the Alphanumeric character set AND if there are less than
* [6,7,8] characters followed by data from the remainder of the 8-bit byte character set, THEN select the 8-
* bit byte mode ELSE select Alphanumeric mode;
*
* This is probably right for 99.99% of cases but there is at least this one counter example: The string "AAAAAAa"
* encodes 2 bits smaller as ALPHANUMERIC(AAAAAA), BYTE(a) than by encoding it as BYTE(AAAAAAa).
* Perhaps that is the only counter example but without having proof, it remains unclear.
*
* ECI switching:
*
* In multi language content the algorithm selects the most compact representation using ECI modes.
* For example the most compact representation of the string "\u0150\u015C" (O-double-acute, S-circumflex) is
* ECI(UTF-8), BYTE(\u0150\u015C) while prepending one or more times the same leading character as in
* "\u0150\u0150\u015C", the most compact representation uses two ECIs so that the string is encoded as
* ECI(ISO-8859-2), BYTE(\u0150\u0150), ECI(ISO-8859-3), BYTE(\u015C).
*
* @author Alex Geller
*/
pub struct MinimalEncoder {
stringToEncode: String,
isGS1: bool,
encoders: ECIEncoderSet,
ecLevel:ErrorCorrectionLevel,
}
impl MinimalEncoder {
/**
* Creates a MinimalEncoder
*
* @param stringToEncode The string to encode
* @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
* chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
* charset to encode any character in the input that can be encoded by it if the charset is among the
* supported charsets.
* @param isGS1 {@code true} if a FNC1 is to be prepended; {@code false} otherwise
* @param ecLevel The error correction level.
* @see RXingResultList#getVersion
*/
pub fn new( stringToEncode:String, priorityCharset: EncodingRef, isGS1:bool, ecLevel:ErrorCorrectionLevel) -> Self {
Self {
stringToEncode,
isGS1,
encoders: ECIEncoderSet::new(&stringToEncode, priorityCharset, -1),
ecLevel,
}
// let encoders = ECIEncoderSet::new(&stringToEncode, priorityCharset, -1);
}
/**
* Encodes the string minimally
*
* @param stringToEncode The string to encode
* @param version The preferred {@link Version}. A minimal version is computed (see
* {@link RXingResultList#getVersion method} when the value of the argument is null
* @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
* chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
* charset to encode any character in the input that can be encoded by it if the charset is among the
* supported charsets.
* @param isGS1 {@code true} if a FNC1 is to be prepended; {@code false} otherwise
* @param ecLevel The error correction level.
* @return An instance of {@code RXingResultList} representing the minimal solution.
* @see RXingResultList#getBits
* @see RXingResultList#getVersion
* @see RXingResultList#getSize
*/
pub fn encode_with_details<'a>( stringToEncode:String, version:VersionRef, priorityCharset:EncodingRef, isGS1:bool,
ecLevel:ErrorCorrectionLevel) -> Result<RXingResultList<'a>,Exceptions> {
MinimalEncoder::new(stringToEncode, priorityCharset, isGS1, ecLevel).encode(Some(version))
}
pub fn encode(&self, version:Option<VersionRef>) -> Result<RXingResultList,Exceptions> {
if version.is_none() { // compute minimal encoding trying the three version sizes.
let versions = [ Self::getVersion(VersionSize::SMALL),
Self::getVersion(VersionSize::MEDIUM),
Self::getVersion(VersionSize::LARGE) ];
let results = [ self.encodeSpecificVersion(&versions[0]),
self.encodeSpecificVersion(&versions[1]),
self.encodeSpecificVersion(&versions[2]) ];
let smallestSize = u32::MAX;
let smallestRXingResult = -1;
for i in 0..3 {
// for (int i = 0; i < 3; i++) {
let size = results[i].getSize();
if encoder::willFit(size, versions[i], self.ecLevel) && size < smallestSize {
smallestSize = size;
smallestRXingResult = i;
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::WriterException("Data too big for any version".to_owned()));
}
return results[smallestRXingResult];
} else { // compute minimal encoding for a given version
let result = self.encodeSpecificVersion(version);
if !encoder::willFit(result.getSize(), Self::getVersion(Self::getVersionSize(result.getVersion())), self.ecLevel) {
return Err(Exceptions::WriterException(format!("Data too big for version {}" , version)));
}
return result;
}
}
pub fn getVersionSize( version:&Version) -> VersionSize {
return if version.getVersionNumber() <= 9 { VersionSize::SMALL} else {if version.getVersionNumber() <= 26
{VersionSize::MEDIUM} else {VersionSize::LARGE}};
}
pub fn getVersion( versionSize:VersionSize)->VersionRef {
match versionSize {
VersionSize::SMALL => Version::getVersionForNumber(9).expect("should always exist"),
VersionSize::MEDIUM => Version::getVersionForNumber(26).expect("should always exist"),
VersionSize::LARGE => Version::getVersionForNumber(40).expect("should always exist"),
}
// switch (versionSize) {
// case SMALL:
// return Version.getVersionForNumber(9);
// case MEDIUM:
// return Version.getVersionForNumber(26);
// case LARGE:
// default:
// return Version.getVersionForNumber(40);
// }
}
pub fn isNumeric( c:char) -> bool{
return c >= '0' && c <= '9';
}
pub fn isDoubleByteKanji( c:char) -> bool{
return encoder::isOnlyDoubleByteKanji(String.valueOf(c));
}
pub fn isAlphanumeric( c: char) -> bool{
return encoder::getAlphanumericCode(c) != -1;
}
pub fn canEncode(&self, mode:&Mode, c:char) -> bool {
match mode {
Mode::NUMERIC => Self::isNumeric(c),
Mode::ALPHANUMERIC => Self::isAlphanumeric(c),
Mode::STRUCTURED_APPEND => todo!(),
Mode::BYTE => true,
Mode::KANJI => Self::isDoubleByteKanji(c),
_=> false,// any character can be encoded as byte(s). Up to the caller to manage splitting into
// multiple bytes when String.getBytes(Charset) return more than one byte.
}
}
pub fn getCompactedOrdinal( mode:Option<Mode>) -> Result<u32,Exceptions>{
if mode.is_none() {
return Ok(0);
}
match &mode.unwrap() {
Mode::NUMERIC => Ok(2),
Mode::ALPHANUMERIC => Ok(1),
Mode::BYTE => Ok(3),
Mode::KANJI => Ok(0),
_=> Err(Exceptions::IllegalArgumentException(format!("Illegal mode {:?}", mode))),
}
// switch (mode) {
// case KANJI:
// return 0;
// case ALPHANUMERIC:
// return 1;
// case NUMERIC:
// return 2;
// case BYTE:
// return 3;
// default:
// throw new IllegalStateException("Illegal mode " + mode);
// }
}
pub fn addEdge(&self, edges:&Vec<Vec<Vec<&'_ Edge>>>, position:u32, edge:Option<&Edge>) {
let vertexIndex = position + edge.as_ref().unwrap().characterLength;
let modeEdges = edges[vertexIndex as usize][edge.as_ref().unwrap().charsetEncoderIndex as usize];
let modeOrdinal = Self::getCompactedOrdinal(Some(edge.as_ref().unwrap().mode)).expect("value") as usize;
if /*modeEdges[modeOrdinal] == null ||*/ modeEdges[modeOrdinal].cachedTotalSize > (&edge).unwrap().cachedTotalSize {
modeEdges[modeOrdinal] = edge.unwrap();
}
}
pub fn addEdges( &self, version:&Edge, edges:&Vec<Vec<Vec<Edge>>>, from:u32, previous:&Edge) {
let start = 0;
let end = self.encoders.len();
let priorityEncoderIndex = self.encoders.getPriorityEncoderIndex();
if priorityEncoderIndex >= 0 && self.encoders.canEncode(self.stringToEncode.chars().nth(from).unwrap(),priorityEncoderIndex) {
start = priorityEncoderIndex;
end = priorityEncoderIndex + 1;
}
for i in start..end {
// for (int i = start; i < end; i++) {
if self.encoders.canEncode(self.stringToEncode.chars().nth(from).unwrap(), i) {
self.addEdge(edges, from, Edge::new(Mode::BYTE, from, i, 1, previous, version));
}
}
if self.canEncode(Mode::KANJI, self.stringToEncode.chars().nth(from).unwrap()) {
self.addEdge(edges, from, Edge::(Mode::KANJI, from, 0, 1, previous, version));
}
let inputLength = self.stringToEncode.len();
if self.canEncode(Mode::ALPHANUMERIC, self.stringToEncode.charAt(from)) {
self.addEdge(edges, from, Edge::new(Mode::ALPHANUMERIC, from, 0, from + 1 >= inputLength ||
!self.canEncode(Mode::ALPHANUMERIC, self.stringToEncode.charAt(from + 1)) ? 1 : 2, previous, version));
}
if self.canEncode(Mode::NUMERIC, self.stringToEncode.chars().nth(from).unwrap()) {
self.addEdge(edges, from, Edge::new(Mode::NUMERIC, from, 0, from + 1 >= inputLength ||
!self.canEncode(Mode::NUMERIC, self.stringToEncode.charAt(from + 1)) ? 1 : from + 2 >= inputLength ||
!self.canEncode(Mode::NUMERIC, self.stringToEncode.charAt(from + 2)) ? 2 : 3, previous, version));
}
}
pub fn encodeSpecificVersion(&self, version:VersionRef) ->Result< RXingResultList, Exceptions >{
// @SuppressWarnings("checkstyle:lineLength")
/* A vertex represents a tuple of a position in the input, a mode and a character encoding where position 0
* denotes the position left of the first character, 1 the position left of the second character and so on.
* Likewise the end vertices are located after the last character at position stringToEncode.length().
*
* An edge leading to such a vertex encodes one or more of the characters left of the position that the vertex
* represents and encodes it in the same encoding and mode as the vertex on which the edge ends. In other words,
* all edges leading to a particular vertex encode the same characters in the same mode with the same character
* encoding. They differ only by their source vertices who are all located at i+1 minus the number of encoded
* characters.
*
* The edges leading to a vertex are stored in such a way that there is a fast way to enumerate the edges ending
* on a particular vertex.
*
* The algorithm processes the vertices in order of their position thereby performing the following:
*
* For every vertex at position i the algorithm enumerates the edges ending on the vertex and removes all but the
* shortest from that list.
* Then it processes the vertices for the position i+1. If i+1 == stringToEncode.length() then the algorithm ends
* and chooses the the edge with the smallest size from any of the edges leading to vertices at this position.
* Otherwise the algorithm computes all possible outgoing edges for the vertices at the position i+1
*
* Examples:
* The process is illustrated by showing the graph (edges) after each iteration from left to right over the input:
* An edge is drawn as follows "(" + fromVertex + ") -- " + encodingMode + "(" + encodedInput + ") (" +
* accumulatedSize + ") --> (" + toVertex + ")"
*
* Example 1 encoding the string "ABCDE":
* Note: This example assumes that alphanumeric encoding is only possible in multiples of two characters so that
* the example is both short and showing the principle. In reality this restriction does not exist.
*
* Initial situation
* (initial) -- BYTE(A) (20) --> (1_BYTE)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 1
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 2
* (initial) -- BYTE(A) (20) --> (1_BYTE)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC)
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- BYTE(C) (44) --> (3_BYTE)
* (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 3
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- BYTE(D) (64) --> (4_BYTE)
* (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
* (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Situation after adding edges to vertices at position 4
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE) -- BYTE(D) (44) --> (4_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC) -- BYTE(E) (55) --> (5_BYTE)
*
* Situation after adding edges to vertices at position 5
* (initial) -- BYTE(A) (20) --> (1_BYTE) -- BYTE(B) (28) --> (2_BYTE) -- BYTE(C) (36) --> (3_BYTE) -- BYTE(D) (44) --> (4_BYTE) -- BYTE(E) (52) --> (5_BYTE)
* (1_BYTE) -- ALPHANUMERIC(BC) (44) --> (3_ALPHANUMERIC) -- ALPHANUMERIC(DE) (55) --> (5_ALPHANUMERIC)
* (initial) -- ALPHANUMERIC(AB) (24) --> (2_ALPHANUMERIC) -- ALPHANUMERIC(CD) (35) --> (4_ALPHANUMERIC)
*
* Encoding as BYTE(ABCDE) has the smallest size of 52 and is hence chosen. The encodation ALPHANUMERIC(ABCD),
* BYTE(E) is longer with a size of 55.
*
* Example 2 encoding the string "XXYY" where X denotes a character unique to character set ISO-8859-2 and Y a
* character unique to ISO-8859-3. Both characters encode as double byte in UTF-8:
*
* Initial situation
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 1
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2)
* (1_BYTE_ISO-8859-2) -- BYTE(X) (72) --> (2_BYTE_UTF-8)
* (1_BYTE_ISO-8859-2) -- BYTE(X) (72) --> (2_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 2
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (80) --> (3_BYTE_UTF-8)
* (2_BYTE_ISO-8859-2) -- BYTE(Y) (80) --> (3_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 3
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (80) --> (4_BYTE_ISO-8859-3)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (112) --> (4_BYTE_UTF-8)
* (3_BYTE_ISO-8859-3) -- BYTE(Y) (112) --> (4_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8) -- BYTE(Y) (72) --> (3_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE) -- BYTE(Y) (72) --> (3_BYTE_UTF-16BE)
*
* Situation after adding edges to vertices at position 4
* (initial) -- BYTE(X) (32) --> (1_BYTE_ISO-8859-2) -- BYTE(X) (40) --> (2_BYTE_ISO-8859-2) -- BYTE(Y) (72) --> (3_BYTE_ISO-8859-3) -- BYTE(Y) (80) --> (4_BYTE_ISO-8859-3)
* (3_BYTE_UTF-8) -- BYTE(Y) (88) --> (4_BYTE_UTF-8)
* (3_BYTE_UTF-16BE) -- BYTE(Y) (88) --> (4_BYTE_UTF-16BE)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-8) -- BYTE(X) (56) --> (2_BYTE_UTF-8) -- BYTE(Y) (72) --> (3_BYTE_UTF-8)
* (initial) -- BYTE(X) (40) --> (1_BYTE_UTF-16BE) -- BYTE(X) (56) --> (2_BYTE_UTF-16BE) -- BYTE(Y) (72) --> (3_BYTE_UTF-16BE)
*
* Encoding as ECI(ISO-8859-2),BYTE(XX),ECI(ISO-8859-3),BYTE(YY) has the smallest size of 80 and is hence chosen.
* The encodation ECI(UTF-8),BYTE(XXYY) is longer with a size of 88.
*/
let inputLength = self.stringToEncode.len();
// Array that represents vertices. There is a vertex for every character, encoding and mode. The vertex contains
// a list of all edges that lead to it that have the same encoding and mode.
// The lists are created lazily
// The last dimension in the array below encodes the 4 modes KANJI, ALPHANUMERIC, NUMERIC and BYTE via the
// function getCompactedOrdinal(Mode)
let edges = vec![vec![vec![]]];//new Edge[inputLength + 1][encoders.length()][4];
self. addEdges(version, &edges, 0, None);
for i in 1..=inputLength {
// for (int i = 1; i <= inputLength; i++) {
for j in 0..self.encoders.len() {
// for (int j = 0; j < encoders.length(); j++) {
for k in 0..4 {
// for (int k = 0; k < 4; k++) {
if edges[i][j][k] != null && i < inputLength {
self.addEdges(version, edges, i, edges[i][j][k]);
}
}
}
}
let minimalJ = -1;
let minimalK = -1;
let minimalSize = u32::MAX;
for j in 0..self.encoders.len() {
// for (int j = 0; j < encoders.length(); j++) {
for k in 0..4 {
// for (int k = 0; k < 4; k++) {
if edges[inputLength][j][k] != null {
let edge = edges[inputLength][j][k];
if edge.cachedTotalSize < minimalSize {
minimalSize = edge.cachedTotalSize;
minimalJ = j;
minimalK = k;
}
}
}
}
if minimalJ < 0 {
return Err(Exceptions::WriterException(format!(r#"Internal error: failed to encode "{}"#,self.stringToEncode)));
}
Ok(RXingResultList::new(version, edges[inputLength][minimalJ][minimalK]))
}
}
struct Edge<'a> {
mode:Mode,
fromPosition:u32,
charsetEncoderIndex:u32,
characterLength:u32,
previous:Option<&'a Edge<'a>>,
cachedTotalSize:u32,
encoders:&'a ECIEncoderSet,
stringToEncode: &'a str,
}
impl Edge<'_> {
pub fn new( mode:Mode, fromPosition:u32, charsetEncoderIndex:u32, characterLength:u32, previous:Option<&'_ Edge>,
version:&Version, encoders: &'_ ECIEncoderSet, stringToEncode: &'_ str) -> Self {
let nci = if mode == Mode::BYTE || previous.is_none() {charsetEncoderIndex} else
{previous.as_ref().unwrap().charsetEncoderIndex};
Self {
mode,
fromPosition,
charsetEncoderIndex: nci,
characterLength,
previous,
stringToEncode,
cachedTotalSize: {
let size = if previous.is_some() {previous.as_ref().unwrap().cachedTotalSize} else {0};
let needECI = mode == Mode::BYTE &&
(previous.is_none() && nci != 0) || // at the beginning and charset is not ISO-8859-1
(previous.is_some() && nci != previous.as_ref().unwrap().charsetEncoderIndex);
if previous.is_none()|| mode != previous.as_ref().unwrap().mode || needECI {
size += 4 + mode.getCharacterCountBits(&version) as u32;
}
match mode {
Mode::NUMERIC => size += if characterLength == 1 {4} else {if characterLength == 2 {7} else {10}},
Mode::ALPHANUMERIC => size += if characterLength == 1 {6} else {11},
Mode::BYTE =>{
size += 8 * encoders.encode_string(&stringToEncode[fromPosition as usize..(fromPosition + characterLength)as usize],
charsetEncoderIndex as usize).len() as u32;
if needECI {
size += 4 + 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
}
},
Mode::KANJI => size += 13,
_=> {},
}
// switch (mode) {
// case KANJI:
// size += 13;
// break;
// case ALPHANUMERIC:
// size += characterLength == 1 ? 6 : 11;
// break;
// case NUMERIC:
// size += characterLength == 1 ? 4 : characterLength == 2 ? 7 : 10;
// break;
// case BYTE:
// size += 8 * encoders.encode(stringToEncode.substring(fromPosition, fromPosition + characterLength),
// charsetEncoderIndex).length;
// if (needECI) {
// size += 4 + 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
// }
// break;
// }
size
},
encoders
}
// this.mode = mode;
// this.fromPosition = fromPosition;
// this.charsetEncoderIndex = mode == Mode.BYTE || previous == null ? charsetEncoderIndex :
// previous.charsetEncoderIndex; // inherit the encoding if not of type BYTE
// this.characterLength = characterLength;
// this.previous = previous;
// int size = previous != null ? previous.cachedTotalSize : 0;
// boolean needECI = mode == Mode.BYTE &&
// (previous == null && this.charsetEncoderIndex != 0) || // at the beginning and charset is not ISO-8859-1
// (previous != null && this.charsetEncoderIndex != previous.charsetEncoderIndex);
// if (previous == null || mode != previous.mode || needECI) {
// size += 4 + mode.getCharacterCountBits(version);
// }
// switch (mode) {
// case KANJI:
// size += 13;
// break;
// case ALPHANUMERIC:
// size += characterLength == 1 ? 6 : 11;
// break;
// case NUMERIC:
// size += characterLength == 1 ? 4 : characterLength == 2 ? 7 : 10;
// break;
// case BYTE:
// size += 8 * encoders.encode(stringToEncode.substring(fromPosition, fromPosition + characterLength),
// charsetEncoderIndex).length;
// if (needECI) {
// size += 4 + 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
// }
// break;
// }
// cachedTotalSize = size;
}
}
struct RXingResultList<'a> {
list: Vec<RXingResultNode<'a>>,
version: VersionRef,
}
impl RXingResultList<'_> {
pub fn new( version:VersionRef, solution:&'_ Edge, isGS1:bool, ecLevel: &ErrorCorrectionLevel) -> Self {
let length = 0;
let current = Some(solution);
let containsECI = false;
let list = Vec::new();
while current.is_some() {
length += current.as_ref().unwrap().characterLength;
let previous = current.as_ref().unwrap().previous;
let needECI = current.as_ref().unwrap().mode == Mode::BYTE &&
(previous.is_none() && current.as_ref().unwrap().charsetEncoderIndex != 0) || // at the beginning and charset is not ISO-8859-1
(previous.is_some() && current.as_ref().unwrap().charsetEncoderIndex != previous.as_ref().unwrap().charsetEncoderIndex);
if needECI {
containsECI = true;
}
if previous.is_none() || previous.as_ref().unwrap().mode != current.as_ref().unwrap().mode || needECI {
list.push( RXingResultNode::new(current.mode, current.fromPosition, current.charsetEncoderIndex, length));
length = 0;
}
if needECI {
list.push( RXingResultNode::new(Mode::ECI, current.fromPosition, current.charsetEncoderIndex, 0));
}
current = previous;
}
// prepend FNC1 if needed. If the bits contain an ECI then the FNC1 must be preceeded by an ECI.
// If there is no ECI at the beginning then we put an ECI to the default charset (ISO-8859-1)
if isGS1 {
if let Some(first) = list.get(0){
// if first != null && first.mode != Mode.ECI && containsECI {
if first.mode != Mode::ECI && containsECI {
// prepend a default character set ECI
list.push(0, RXingResultNode::new(Mode::ECI, 0, 0, 0));
}}
let first = list.get(0).unwrap();
// prepend or insert a FNC1_FIRST_POSITION after the ECI (if any)
// if first != null && first.mode != Mode.ECI && containsECI {
list.push( RXingResultNode::new(Mode::FNC1_FIRST_POSITION, 0, 0, 0));
}
// set version to smallest version into which the bits fit.
let versionNumber = version.getVersionNumber();
let (lowerLimit,upperLimit) =
match MinimalEncoder::getVersionSize(&version) {
VersionSize::SMALL =>
(1,9),
VersionSize::MEDIUM=>(10,26),
_=>(27,40),
};
// let lowerLimit;
// let upperLimit;
// switch (getVersionSize(version)) {
// case SMALL:
// lowerLimit = 1;
// upperLimit = 9;
// break;
// case MEDIUM:
// lowerLimit = 10;
// upperLimit = 26;
// break;
// case LARGE:
// default:
// lowerLimit = 27;
// upperLimit = 40;
// break;
// }
let size = Self::internal_static_get_size(version,&list);
// increase version if needed
while versionNumber < upperLimit && !encoder::willFit(size, Version::getVersionForNumber(versionNumber),
ecLevel) {
versionNumber+=1;
}
// shrink version if possible
while versionNumber > lowerLimit && encoder::willFit(size, Version::getVersionForNumber(versionNumber - 1),
ecLevel) {
versionNumber-=1;
}
let version = Version::getVersionForNumber(versionNumber).unwrap();
Self {
list,
version,
}
}
/**
* returns the size in bits
*/
pub fn getSize(&self) -> u32{
self. getSizeLocal(self.version)
}
fn getSizeLocal(&self, version:VersionRef) -> u32{
let result = 0;
for resultNode in &self.list {
result += resultNode.getSize(version);
}
return result;
}
fn internal_static_get_size(version:VersionRef, list: &Vec<RXingResultNode>) {
let result = 0;
for resultNode in list {
result += resultNode.getSize(version);
}
return result;
}
/**
* appends the bits
*/
pub fn getBits(&self, bits:&BitArray) -> Result<(),Exceptions> {
for resultNode in &self.list {
resultNode.getBits(bits);
}
Ok(())
}
pub fn getVersion(&self) -> &Version{
&self. version
}
}
impl fmt::Display for RXingResultList<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut result = String::new();
let previous = None;
for current in &self.list {
// for (RXingResultNode current : list) {
if previous.is_some() {
result.push_str(",");
}
result.push_str(&current.to_string());
previous = Some(current);
}
write!(f,"{}", result)
}
}
struct RXingResultNode<'a> {
mode:Mode,
fromPosition:u32,
charsetEncoderIndex:u32,
characterLength:u32,
encoders:&'a ECIEncoderSet,
version: VersionRef,
stringToEncode: &'a str,
}
impl RXingResultNode<'_> {
pub fn new( mode:Mode, fromPosition:u32, charsetEncoderIndex:u32, characterLength:u32, encoders:&'_ ECIEncoderSet, stringToEncode: &'_ str, version: &'_ Version) -> Self {
Self {
mode,
fromPosition,
charsetEncoderIndex,
characterLength,
encoders,
stringToEncode,
version,
}
}
/**
* returns the size in bits
*/
fn getSize(&self, version:&Version) -> u32{
let size = 4 + self.mode.getCharacterCountBits(version) as u32;
match self.mode {
Mode::NUMERIC => {
size += (self.characterLength / 3) * 10;
let rest = self.characterLength % 3;
size += if rest == 1 {4} else { if rest == 2 {7} else {0}};
},
Mode::ALPHANUMERIC => {
size += (self.characterLength / 2) * 11;
size += if (self.characterLength % 2) == 1 {6} else {0};
},
Mode::BYTE => size += 8 * self.getCharacterCountIndicator(),
Mode::ECI => size += 8,
Mode::KANJI => size += 13 * self.characterLength,
_ => {},
}
// switch (mode) {
// case KANJI:
// size += 13 * characterLength;
// break;
// case ALPHANUMERIC:
// size += (characterLength / 2) * 11;
// size += (characterLength % 2) == 1 ? 6 : 0;
// break;
// case NUMERIC:
// size += (characterLength / 3) * 10;
// int rest = characterLength % 3;
// size += rest == 1 ? 4 : rest == 2 ? 7 : 0;
// break;
// case BYTE:
// size += 8 * getCharacterCountIndicator();
// break;
// case ECI:
// size += 8; // the ECI assignment numbers for ISO-8859-x, UTF-8 and UTF-16 are all 8 bit long
// }
size
}
/**
* returns the length in characters according to the specification (differs from getCharacterLength() in BYTE mode
* for multi byte encoded characters)
*/
fn getCharacterCountIndicator(&self) -> u32{
if self.mode == Mode::BYTE
{self.encoders.encode_string(&self.stringToEncode[self.fromPosition as usize..(self.fromPosition + self.characterLength) as usize],
self.charsetEncoderIndex as usize).len() as u32} else {self.characterLength}
}
/**
* appends the bits
*/
fn getBits(&self, bits:&BitArray) -> Result<(),Exceptions> {
bits.appendBits(self.mode.getBits() as u32, 4);
if self.characterLength > 0 {
let length = self.getCharacterCountIndicator();
bits.appendBits(length, self.mode.getCharacterCountBits(self.version.as_ref()) as usize);
}
if self.mode == Mode::ECI {
bits.appendBits(self.encoders.getECIValue(self.charsetEncoderIndex as usize), 8);
} else if self.characterLength > 0 {
// append data
encoder::appendBytes(self.stringToEncode[self.fromPosition as usize..(self.fromPosition + self.characterLength) as usize], self.mode, bits,
self.encoders.getCharset(self.charsetEncoderIndex as usize));
}
Ok(())
}
fn makePrintable( s:&str) -> String {
let mut result = String::new();
for i in 0..s.chars().count() {
// for (int i = 0; i < s.length(); i++) {
if (s.chars().nth(i).unwrap() as u8) < 32 || (s.chars().nth(i).unwrap() as u8) > 126 {
result.push('.');
} else {
result.push(s.chars().nth(i).unwrap());
}
}
result
}
}
impl fmt::Display for RXingResultNode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let result = String::new();
result.push_str(&format!("{:?}",self.mode));
result.push('(');
if self.mode == Mode::ECI {
result.push_str(self.encoders.getCharset(self.charsetEncoderIndex as usize).name());
} else {
result.push_str(&Self::makePrintable(&self.stringToEncode[self.fromPosition as usize..(self.fromPosition + self.characterLength) as usize]));
}
result.push(')');
write!(f,"{}", result)
}
}

View File

@@ -3,10 +3,13 @@ mod byte_matrix;
mod block_pair;
pub mod mask_util;
pub mod matrix_util;
mod minimal_encoder;
pub mod encoder;
pub use qr_code::*;
pub use byte_matrix::*;
pub use block_pair::*;
pub use minimal_encoder::*;
#[cfg(test)]
mod QRCodeTestCase;