Implement clippy suggestions

This commit is contained in:
Henry Schimke
2023-01-04 14:48:16 -06:00
parent c65eadf102
commit 48287631dd
196 changed files with 2465 additions and 2574 deletions

View File

@@ -734,7 +734,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
let dataBytes = &[
67, 70, 22, 38, 54, 70, 86, 102, 118, 134, 150, 166, 182, 198, 214,
@@ -746,7 +746,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
// High-order zero coefficient case.
let dataBytes = &[32, 49, 205, 69, 42, 20, 0, 236, 17];
@@ -757,7 +757,7 @@ fn testGenerateECBytes() {
assert_eq!(expected.len(), ecBytes.len());
for x in 0..expected.len() {
// for (int x = 0; x < expected.length; x++) {
assert_eq!(expected[x], ecBytes[x] & 0xFF);
assert_eq!(expected[x], ecBytes[x]);
}
}

View File

@@ -198,7 +198,7 @@ fn testGetDataMaskBitInternal(maskPattern: u32, expected: &Vec<Vec<u32>>) -> boo
}
}
}
return true;
true
}
// See mask patterns on the page 43 of JISX0510:2004.

View File

@@ -69,7 +69,7 @@ impl ByteMatrix {
// }
pub fn set_bool(&mut self, x: u32, y: u32, value: bool) {
self.bytes[y as usize][x as usize] = if value { 1 } else { 0 };
self.bytes[y as usize][x as usize] = u8::from(value); //if value { 1 } else { 0 };
}
pub fn clear(&mut self, value: u8) {
@@ -88,9 +88,10 @@ impl fmt::Display for ByteMatrix {
for y in 0..self.height as usize {
// for (int y = 0; y < height; ++y) {
let bytesY = &self.bytes[y];
for x in 0..self.width as usize {
for byte in bytesY.iter().take(self.width as usize) {
// for x in 0..self.width as usize {
// for (int x = 0; x < width; ++x) {
match bytesY[x] {
match *byte {
0 => result.push_str(" 0"),
1 => result.push_str(" 1"),
_ => result.push_str(" "),
@@ -119,7 +120,7 @@ impl From<ByteMatrix> for BitMatrix {
for y in 0..bm.getHeight() {
for x in 0..bm.getWidth() {
if bm.get(x, y) > 0 {
bit_matrix.set(x as u32, y as u32);
bit_matrix.set(x, y);
}
}
}

View File

@@ -55,10 +55,10 @@ pub const DEFAULT_BYTE_MODE_ENCODING: EncodingRef = encoding::all::ISO_8859_1;
// 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.
pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 {
return mask_util::applyMaskPenaltyRule1(matrix)
mask_util::applyMaskPenaltyRule1(matrix)
+ mask_util::applyMaskPenaltyRule2(matrix)
+ mask_util::applyMaskPenaltyRule3(matrix)
+ mask_util::applyMaskPenaltyRule4(matrix);
+ mask_util::applyMaskPenaltyRule4(matrix)
}
/**
@@ -69,7 +69,7 @@ pub fn calculateMaskPenalty(matrix: &ByteMatrix) -> u32 {
* or configuration
*/
pub fn encode(content: &str, ecLevel: ErrorCorrectionLevel) -> Result<QRCode, Exceptions> {
return encode_with_hints(content, ecLevel, &HashMap::new());
encode_with_hints(content, ecLevel, &HashMap::new())
}
pub fn encode_with_hints(
@@ -127,17 +127,15 @@ pub fn encode_with_hints(
version = rn.getVersion();
} else {
//Switch to default encoding
let encoding = if encoding.is_some() {
encoding.unwrap()
let encoding = if let Some(encoding) = encoding {
encoding
} else if let Ok(_encs) =
DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict)
{
DEFAULT_BYTE_MODE_ENCODING
} else {
if let Ok(_encs) =
DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict)
{
DEFAULT_BYTE_MODE_ENCODING
} else {
has_encoding_hint = true;
encoding::all::UTF_8
}
has_encoding_hint = true;
encoding::all::UTF_8
};
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
@@ -186,9 +184,9 @@ pub fn encode_with_hints(
version = Version::getVersionForNumber(versionNumber)?;
let bitsNeeded = calculateBitsNeeded(mode, &header_bits, &data_bits, version);
if !willFit(bitsNeeded, version, &ec_level) {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data too big for requested version".to_owned(),
));
)));
}
} else {
version = recommendVersion(&ec_level, mode, &header_bits, &data_bits)?;
@@ -317,7 +315,7 @@ pub fn getAlphanumericCode(code: u32) -> i8 {
}
pub fn chooseMode(content: &str) -> Mode {
return chooseModeWithEncoding(content, encoding::all::ISO_8859_1);
chooseModeWithEncoding(content, encoding::all::ISO_8859_1)
}
/**
@@ -335,7 +333,7 @@ fn chooseModeWithEncoding(content: &str, encoding: EncodingRef) -> Mode {
for i in 0..content.len() {
// for (int i = 0; i < content.length(); ++i) {
let c = content.chars().nth(i).unwrap();
if c >= '0' && c <= '9' {
if ('0'..='9').contains(&c) {
has_numeric = true;
} else if getAlphanumericCode(c as u32) != -1 {
has_alphanumeric = true;
@@ -349,7 +347,7 @@ fn chooseModeWithEncoding(content: &str, encoding: EncodingRef) -> Mode {
if has_numeric {
return Mode::NUMERIC;
}
return Mode::BYTE;
Mode::BYTE
}
pub fn isOnlyDoubleByteKanji(content: &str) -> bool {
@@ -366,12 +364,12 @@ pub fn isOnlyDoubleByteKanji(content: &str) -> bool {
while i < length {
// for (int i = 0; i < length; i += 2) {
let byte1 = bytes[i];
if (byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB) {
if !(0x81..=0x9F).contains(&byte1) && !(0xE0..=0xEB).contains(&byte1) {
return false;
}
i += 2;
}
return true;
true
}
fn chooseMaskPattern(
@@ -407,7 +405,7 @@ fn chooseVersion(
return Ok(version);
}
}
Err(Exceptions::WriterException("Data too big".to_owned()))
Err(Exceptions::WriterException(Some("Data too big".to_owned())))
}
/**
@@ -424,7 +422,7 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
// getNumDataBytes = 196 - 130 = 66
let num_data_bytes = num_bytes - num_ec_bytes;
let total_input_bytes = (numInputBits + 7) / 8;
return num_data_bytes >= total_input_bytes;
num_data_bytes >= total_input_bytes
}
/**
@@ -433,10 +431,10 @@ pub fn willFit(numInputBits: u32, version: VersionRef, ecLevel: &ErrorCorrection
pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exceptions> {
let capacity = num_data_bytes * 8;
if bits.getSize() > capacity as usize {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"data bits cannot fit in the QR Code{} > ",
capacity
)));
))));
// throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " > " +
// capacity);
}
@@ -468,9 +466,9 @@ pub fn terminateBits(num_data_bytes: u32, bits: &mut BitArray) -> Result<(), Exc
bits.appendBits(if (i & 0x01) == 0 { 0xEC } else { 0x11 }, 8)?;
}
if bits.getSize() != capacity as usize {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Bits size does not equal capacity".to_owned(),
));
)));
// throw new WriterException("Bits size does not equal capacity");
}
Ok(())
@@ -490,7 +488,9 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// numECBytesInBlock: &mut [u32],
) -> Result<(u32, u32), Exceptions> {
if block_id >= num_rsblocks {
return Err(Exceptions::WriterException("Block ID too large".to_owned()));
return Err(Exceptions::WriterException(Some(
"Block ID too large".to_owned(),
)));
// throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
@@ -512,12 +512,16 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
// Sanity checks.
// 26 = 26
if num_ec_bytes_in_group1 != numEcBytesInGroup2 {
return Err(Exceptions::WriterException("EC bytes mismatch".to_owned()));
return Err(Exceptions::WriterException(Some(
"EC bytes mismatch".to_owned(),
)));
// throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if num_rsblocks != num_rs_blocks_in_group1 + num_rs_blocks_in_group2 {
return Err(Exceptions::WriterException("RS blocks mismatch".to_owned()));
return Err(Exceptions::WriterException(Some(
"RS blocks mismatch".to_owned(),
)));
// throw new WriterException("RS blocks mismatch");
}
@@ -526,9 +530,9 @@ pub fn getNumDataBytesAndNumECBytesForBlockID(
!= ((num_data_bytes_in_group1 + num_ec_bytes_in_group1) * num_rs_blocks_in_group1)
+ ((num_data_bytes_in_group2 + numEcBytesInGroup2) * num_rs_blocks_in_group2)
{
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Total bytes mismatch".to_owned(),
));
)));
// throw new WriterException("Total bytes mismatch");
}
@@ -552,9 +556,9 @@ pub fn interleaveWithECBytes(
) -> Result<BitArray, Exceptions> {
// "bits" must have "getNumDataBytes" bytes of data.
if bits.getSizeInBytes() as u32 != num_data_bytes {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"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
@@ -590,9 +594,9 @@ pub fn interleaveWithECBytes(
data_bytes_offset += numDataBytesInBlock as usize;
}
if num_data_bytes != data_bytes_offset as u32 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data bytes does not match offset".to_owned(),
));
)));
}
let mut result = BitArray::new();
@@ -621,11 +625,11 @@ pub fn interleaveWithECBytes(
}
if num_total_bytes != result.getSizeInBytes() as u32 {
// Should be same.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"Interleaving error: {} and {} differ.",
num_total_bytes,
result.getSizeInBytes()
)));
))));
// throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
// result.getSizeInBytes() + " differ.");
}
@@ -652,7 +656,7 @@ pub fn generateECBytes(dataBytes: &[u8], num_ec_bytes_in_block: usize) -> Vec<u8
// for (int i = 0; i < numEcBytesInBlock; i++) {
ecBytes[i] = to_encode[num_data_bytes + i] as u8;
}
return ecBytes;
ecBytes
}
/**
@@ -674,11 +678,11 @@ pub fn appendLengthInfo(
) -> Result<(), Exceptions> {
let numBits = mode.getCharacterCountBits(version);
if num_letters >= (1 << numBits) {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"{} is bigger than {}",
num_letters,
((1 << numBits) - 1)
)));
))));
}
bits.appendBits(num_letters, numBits as usize)?;
Ok(())
@@ -698,10 +702,10 @@ pub fn appendBytes(
Mode::ALPHANUMERIC => appendAlphanumericBytes(content, bits),
Mode::BYTE => append8BitBytes(content, bits, encoding),
Mode::KANJI => appendKanjiBytes(content, bits),
_ => Err(Exceptions::WriterException(format!(
_ => Err(Exceptions::WriterException(Some(format!(
"Invalid mode: {:?}",
mode
))),
)))),
}
// switch (mode) {
// case NUMERIC:
@@ -752,12 +756,12 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<(),
while i < length {
let code1 = getAlphanumericCode(content.chars().nth(i).unwrap() as u32);
if code1 == -1 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
if i + 1 < length {
let code2 = getAlphanumericCode(content.chars().nth(i + 1).unwrap() as u32);
if code2 == -1 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits((code1 as i16 * 45 + code2 as i16) as u32, 11)?;
@@ -795,9 +799,9 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
.expect("should encode fine");
// let bytes = content.getBytes(StringUtils::SHIFT_JIS_CHARSET);
if bytes.len() % 2 != 0 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Kanji byte size not even".to_owned(),
));
)));
}
let max_i = bytes.len() - 1; // bytes.length must be even
let mut i = 0;
@@ -807,15 +811,15 @@ pub fn appendKanjiBytes(content: &str, bits: &mut BitArray) -> Result<(), Except
let byte2 = bytes[i + 1]; // & 0xFF;
let code: u16 = ((byte1 as u16) << 8u16) | byte2 as u16;
let mut subtracted: i32 = -1;
if code >= 0x8140 && code <= 0x9ffc {
if (0x8140..=0x9ffc).contains(&code) {
subtracted = code as i32 - 0x8140;
} else if code >= 0xe040 && code <= 0xebbf {
} else if (0xe040..=0xebbf).contains(&code) {
subtracted = code as i32 - 0xc140;
}
if subtracted == -1 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Invalid byte sequence".to_owned(),
));
)));
}
let encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded as u32, 13)?;

View File

@@ -85,8 +85,8 @@ pub fn applyMaskPenaltyRule3(matrix: &ByteMatrix) -> u32 {
&& arrayY[x + 4] == 1
&& arrayY[x + 5] == 0
&& arrayY[x + 6] == 1
&& (isWhiteHorizontal(&arrayY, x as i32 - 4, x as u32)
|| isWhiteHorizontal(&arrayY, x as i32 + 7, x as u32 + 11))
&& (isWhiteHorizontal(arrayY, x as i32 - 4, x as u32)
|| isWhiteHorizontal(arrayY, x as i32 + 7, x as u32 + 11))
{
numPenalties += 1;
}
@@ -118,7 +118,7 @@ pub fn isWhiteHorizontal(rowArray: &[u8], from: i32, to: u32) -> bool {
return false;
}
}
return true;
true
}
pub fn isWhiteVertical(array: &Vec<Vec<u8>>, col: u32, from: i32, to: u32) -> bool {
@@ -131,7 +131,7 @@ pub fn isWhiteVertical(array: &Vec<Vec<u8>>, col: u32, from: i32, to: u32) -> bo
return false;
}
}
return true;
true
}
/**
@@ -143,20 +143,22 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 {
let array = matrix.getArray();
let width = matrix.getWidth();
let height = matrix.getHeight();
for y in 0..height as usize {
for val_y in array.iter().take(height as usize) {
// for y in 0..height as usize {
// for (int y = 0; y < height; y++) {
let arrayY = &array[y];
for x in 0..width as usize {
// let arrayY = val_y;
for val_x in val_y.iter().take(width as usize) {
// for x in 0..width as usize {
// for (int x = 0; x < width; x++) {
if arrayY[x] == 1 {
if val_x == &1 {
numDarkCells += 1;
}
}
}
let numTotalCells = matrix.getHeight() * matrix.getWidth();
let fivePercentVariances =
(numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells;
return fivePercentVariances * N4;
(numDarkCells as i64 * 2 - numTotalCells as i64).unsigned_abs() as u32 * 10 / numTotalCells;
fivePercentVariances * N4
}
/**
@@ -183,10 +185,10 @@ pub fn getDataMaskBit(maskPattern: u32, x: u32, y: u32) -> Result<bool, Exceptio
((temp % 3) + ((y + x) & 0x1)) & 0x1
}
_ => {
return Err(Exceptions::IllegalArgumentException(format!(
return Err(Exceptions::IllegalArgumentException(Some(format!(
"Invalid mask pattern: {}",
maskPattern
)))
))))
}
};
// switch (maskPattern) {
@@ -266,5 +268,5 @@ fn applyMaskPenaltyRule1Internal(matrix: &ByteMatrix, isHorizontal: bool) -> u32
penalty += N1 + (numSameBitCells - 5);
}
}
return penalty;
penalty
}

View File

@@ -171,14 +171,18 @@ pub fn embedTypeInfo(
let mut typeInfoBits = BitArray::new();
makeTypeInfoBits(ecLevel, maskPattern as u32, &mut typeInfoBits)?;
for i in 0..typeInfoBits.getSize() {
for (i, coordinates) in TYPE_INFO_COORDINATES
.iter()
.enumerate()
.take(typeInfoBits.getSize())
{
// for (int i = 0; i < typeInfoBits.getSize(); ++i) {
// Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
// "typeInfoBits".
let bit = typeInfoBits.get(typeInfoBits.getSize() - 1 - i);
// Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
let coordinates = TYPE_INFO_COORDINATES[i];
// let coordinates = TYPE_INFO_COORDINATES[i];
let x1 = coordinates[0];
let y1 = coordinates[1];
matrix.set_bool(x1, y1, bit);
@@ -216,9 +220,7 @@ pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Resu
// for (int j = 0; j < 3; ++j) {
// Place bits in LSB (least significant bit) to MSB order.
let bit = versionInfoBits.get(bitIndex);
if bitIndex != 0 {
bitIndex -= 1;
}
bitIndex = bitIndex.saturating_sub(1);
// Left bottom corner.
matrix.set_bool(i, matrix.getHeight() - 11 + j, bit);
// Right bottom corner.
@@ -280,11 +282,11 @@ pub fn embedDataBits(
}
// All bits should be consumed.
if bitIndex != dataBits.getSize() {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"Not all bits consumed: {}/{}",
bitIndex,
dataBits.getSize()
)));
))));
}
Ok(())
}
@@ -325,9 +327,9 @@ pub fn findMSBSet(value: u32) -> u32 {
// operations. We don't care if coefficients are positive or negative.
pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32, Exceptions> {
if poly == 0 {
return Err(Exceptions::IllegalArgumentException(
return Err(Exceptions::IllegalArgumentException(Some(
"0 polynomial".to_owned(),
));
)));
}
let mut value = value;
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
@@ -351,9 +353,9 @@ pub fn makeTypeInfoBits(
bits: &mut BitArray,
) -> Result<(), Exceptions> {
if !QRCode::isValidMaskPattern(maskPattern as i32) {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Invalid mask pattern".to_owned(),
));
)));
}
let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
bits.appendBits(typeInfo, 5)?;
@@ -367,10 +369,10 @@ pub fn makeTypeInfoBits(
if bits.getSize() != 15 {
// Just in case.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"should not happen but we got: {}",
bits.getSize()
)));
))));
}
Ok(())
}
@@ -384,17 +386,17 @@ pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<(),
if bits.getSize() != 18 {
// Just in case.
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
"should not happen but we got: {}",
bits.getSize()
)));
))));
}
Ok(())
}
// Check if "value" is empty.
pub fn isEmpty(value: u8) -> bool {
return value == -1i8 as u8;
value == -1i8 as u8
}
pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
@@ -417,7 +419,7 @@ pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<(), Exceptions> {
if matrix.get(8, matrix.getHeight() - 8) == 0 {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
matrix.set(8, matrix.getHeight() - 8, 1);
Ok(())
@@ -431,7 +433,7 @@ pub fn embedHorizontalSeparationPattern(
for x in 0..8 {
// for (int x = 0; x < 8; ++x) {
if !isEmpty(matrix.get(xStart + x, yStart)) {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
}
matrix.set(xStart + x, yStart, 0);
}
@@ -446,7 +448,7 @@ pub fn embedVerticalSeparationPattern(
for y in 0..7 {
// for (int y = 0; y < 7; ++y) {
if !isEmpty(matrix.get(xStart, yStart + y)) {
return Err(Exceptions::WriterException("".to_owned()));
return Err(Exceptions::WriterException(None));
// throw new WriterException();
}
matrix.set(xStart, yStart + y, 0);
@@ -455,9 +457,10 @@ pub fn embedVerticalSeparationPattern(
}
pub fn embedPositionAdjustmentPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
for y in 0..5 {
for (y, patternY) in POSITION_ADJUSTMENT_PATTERN.iter().enumerate() {
// for y in 0..5 {
// for (int y = 0; y < 5; ++y) {
let patternY = POSITION_ADJUSTMENT_PATTERN[y];
// let patternY = POSITION_ADJUSTMENT_PATTERN[y];
for x in 0..5 {
// for (int x = 0; x < 5; ++x) {
matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);
@@ -466,9 +469,10 @@ pub fn embedPositionAdjustmentPattern(xStart: u32, yStart: u32, matrix: &mut Byt
}
pub fn embedPositionDetectionPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
for y in 0..7 {
for (y, patternY) in POSITION_DETECTION_PATTERN.iter().enumerate() {
// for y in 0..7 {
// for (int y = 0; y < 7; ++y) {
let patternY = POSITION_DETECTION_PATTERN[y];
// let patternY = POSITION_DETECTION_PATTERN[y];
for x in 0..7 {
// for (int x = 0; x < 7; ++x) {
matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);

View File

@@ -117,7 +117,7 @@ impl MinimalEncoder {
.map(|p| p.to_owned())
.collect::<Vec<String>>(),
isGS1,
encoders: ECIEncoderSet::new(&stringToEncode, priorityCharset, None),
encoders: ECIEncoderSet::new(stringToEncode, priorityCharset, None),
ecLevel,
}
@@ -152,7 +152,21 @@ impl MinimalEncoder {
}
pub fn encode(&self, version: Option<VersionRef>) -> Result<RXingResultList, Exceptions> {
if version.is_none() {
if let Some(version) = version {
// 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(Some(format!(
"Data too big for version {}",
version
))));
}
Ok(result)
} else {
// compute minimal encoding trying the three version sizes.
let versions = [
Self::getVersion(VersionSize::SMALL),
@@ -160,9 +174,9 @@ impl MinimalEncoder {
Self::getVersion(VersionSize::LARGE),
];
let results = [
self.encodeSpecificVersion(&versions[0])?,
self.encodeSpecificVersion(&versions[1])?,
self.encodeSpecificVersion(&versions[2])?,
self.encodeSpecificVersion(versions[0])?,
self.encodeSpecificVersion(versions[1])?,
self.encodeSpecificVersion(versions[2])?,
];
let mut smallestSize = u32::MAX;
let mut smallestRXingResult: i32 = -1;
@@ -175,39 +189,22 @@ impl MinimalEncoder {
}
}
if smallestRXingResult < 0 {
return Err(Exceptions::WriterException(
return Err(Exceptions::WriterException(Some(
"Data too big for any version".to_owned(),
));
}
Ok(results[smallestRXingResult as usize].clone())
} else {
// compute minimal encoding for a given version
let version = version.unwrap();
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
)));
}
Ok(result)
Ok(results[smallestRXingResult as usize].clone())
}
}
pub fn getVersionSize(version: VersionRef) -> VersionSize {
return if version.getVersionNumber() <= 9 {
if version.getVersionNumber() <= 9 {
VersionSize::SMALL
} else if version.getVersionNumber() <= 26 {
VersionSize::MEDIUM
} else {
if version.getVersionNumber() <= 26 {
VersionSize::MEDIUM
} else {
VersionSize::LARGE
}
};
VersionSize::LARGE
}
}
pub fn getVersion(versionSize: VersionSize) -> VersionRef {
@@ -229,8 +226,8 @@ impl MinimalEncoder {
pub fn isNumeric(c: &str) -> bool {
if c.len() == 1 {
let ch = c.chars().nth(0).unwrap();
ch >= '0' && ch <= '9'
let ch = c.chars().next().unwrap();
('0'..='9').contains(&ch)
} else {
false
}
@@ -238,12 +235,12 @@ impl MinimalEncoder {
}
pub fn isDoubleByteKanji(c: &str) -> bool {
return encoder::isOnlyDoubleByteKanji(&c);
encoder::isOnlyDoubleByteKanji(c)
}
pub fn isAlphanumeric(c: &str) -> bool {
if c.len() == 1 {
let ch = c.chars().nth(0).unwrap();
let ch = c.chars().next().unwrap();
encoder::getAlphanumericCode(ch as u32) != -1
} else {
false
@@ -271,10 +268,10 @@ impl MinimalEncoder {
Mode::ALPHANUMERIC => Ok(1),
Mode::BYTE => Ok(3),
Mode::KANJI => Ok(0),
_ => Err(Exceptions::IllegalArgumentException(format!(
_ => Err(Exceptions::IllegalArgumentException(Some(format!(
"Illegal mode {:?}",
mode
))),
)))),
}
// switch (mode) {
// case KANJI:
@@ -292,13 +289,12 @@ impl MinimalEncoder {
pub fn addEdge(
&self,
edges: &mut Vec<Vec<Vec<Option<Rc<Edge>>>>>,
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
position: usize,
edge: Option<Rc<Edge>>,
) {
let vertexIndex = position + edge.as_ref().unwrap().characterLength as usize;
let modeEdges =
&mut edges[vertexIndex as usize][edge.as_ref().unwrap().charsetEncoderIndex as usize];
let modeEdges = &mut edges[vertexIndex][edge.as_ref().unwrap().charsetEncoderIndex];
let modeOrdinal =
Self::getCompactedOrdinal(Some(edge.as_ref().unwrap().mode)).expect("value") as usize;
if modeEdges[modeOrdinal].is_none()
@@ -312,7 +308,7 @@ impl MinimalEncoder {
pub fn addEdges(
&self,
version: VersionRef,
edges: &mut Vec<Vec<Vec<Option<Rc<Edge>>>>>,
edges: &mut [Vec<Vec<Option<Rc<Edge>>>>],
from: usize,
previous: Option<Rc<Edge>>,
) {
@@ -322,7 +318,7 @@ impl MinimalEncoder {
if priorityEncoderIndex.is_some()
&& self.encoders.canEncode(
// self.stringToEncode.chars().nth(from as usize).unwrap() as i16,
&self.stringToEncode[from as usize],
&self.stringToEncode[from],
priorityEncoderIndex.unwrap(),
)
{
@@ -334,7 +330,7 @@ impl MinimalEncoder {
// for (int i = start; i < end; i++) {
if self
.encoders
.canEncode(&self.stringToEncode.get(from).unwrap(), i)
.canEncode(self.stringToEncode.get(from).unwrap(), i)
{
self.addEdge(
edges,
@@ -353,7 +349,7 @@ impl MinimalEncoder {
}
}
if self.canEncode(&Mode::KANJI, &self.stringToEncode.get(from).unwrap()) {
if self.canEncode(&Mode::KANJI, self.stringToEncode.get(from).unwrap()) {
self.addEdge(
edges,
from,
@@ -410,19 +406,15 @@ impl MinimalEncoder {
.canEncode(&Mode::NUMERIC, self.stringToEncode.get(from + 1).unwrap())
{
1
} else if from + 2 >= inputLength
|| !self
.canEncode(&Mode::NUMERIC, self.stringToEncode.get(from + 2).unwrap())
{
2
} else {
if from + 2 >= inputLength
|| !self.canEncode(
&Mode::NUMERIC,
self.stringToEncode.get(from + 2).unwrap(),
)
{
2
} else {
3
}
3
},
previous.clone(),
previous,
version,
self.encoders.clone(),
self.stringToEncode.clone(),
@@ -587,13 +579,13 @@ impl MinimalEncoder {
}
}
if minimalJ.is_none() {
return Err(Exceptions::WriterException(format!(
return Err(Exceptions::WriterException(Some(format!(
r#"Internal error: failed to encode "{}"#,
self.stringToEncode
.iter()
.map(|x| String::from(x))
.map(String::from)
.collect::<String>() //fold("", |acc,x| [acc,&x].concat())
)));
))));
}
Ok(RXingResultList::new(
version,
@@ -654,31 +646,27 @@ impl Edge {
(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;
size += 4 + mode.getCharacterCountBits(version) as u32;
}
match mode {
Mode::NUMERIC => {
size += if characterLength == 1 {
4
} else if characterLength == 2 {
7
} else {
if characterLength == 2 {
7
} else {
10
}
10
}
}
Mode::ALPHANUMERIC => size += if characterLength == 1 { 6 } else { 11 },
Mode::BYTE => {
let n: String = stringToEncode
.iter()
.skip(fromPosition as usize)
.skip(fromPosition)
.take(characterLength as usize)
.map(|x| String::from(x))
.map(String::from)
.collect();
size += 8 * encoders
.encode_string(&n, charsetEncoderIndex as usize)
.len() as u32;
size += 8 * encoders.encode_string(&n, charsetEncoderIndex).len() as u32;
// size += 8 * encoders
// .encode_string(
// &stringToEncode[fromPosition as usize
@@ -849,8 +837,8 @@ impl RXingResultList {
0,
0,
0,
encoders.clone(),
stringToEncode.clone(),
encoders,
stringToEncode,
version,
),
);
@@ -868,7 +856,7 @@ impl RXingResultList {
// set version to smallest version into which the bits fit.
let mut versionNumber = version.getVersionNumber();
let (lowerLimit, upperLimit) = match MinimalEncoder::getVersionSize(&version) {
let (lowerLimit, upperLimit) = match MinimalEncoder::getVersionSize(version) {
VersionSize::SMALL => (1, 9),
VersionSize::MEDIUM => (10, 26),
_ => (27, 40),
@@ -928,7 +916,7 @@ impl RXingResultList {
for resultNode in &self.list {
result += resultNode.getSize(version);
}
return result;
result
}
fn internal_static_get_size(version: VersionRef, list: &Vec<RXingResultNode>) -> u32 {
@@ -936,7 +924,7 @@ impl RXingResultList {
for resultNode in list {
result += resultNode.getSize(version);
}
return result;
result
}
/**
@@ -961,7 +949,7 @@ impl fmt::Display for RXingResultList {
for current in &self.list {
// for (RXingResultNode current : list) {
if previous.is_some() {
result.push_str(",");
result.push(',');
}
result.push_str(&current.to_string());
previous = Some(current);
@@ -1013,12 +1001,10 @@ impl RXingResultNode {
let rest = self.characterLength % 3;
size += if rest == 1 {
4
} else if rest == 2 {
7
} else {
if rest == 2 {
7
} else {
0
}
0
};
}
Mode::ALPHANUMERIC => {
@@ -1066,8 +1052,8 @@ impl RXingResultNode {
.encode_string(
// &self.stringToEncode[self.fromPosition as usize
// ..(self.fromPosition + self.characterLength as usize)],
&self.stringToEncode.get(self.fromPosition as usize).unwrap(),
self.charsetEncoderIndex as usize,
self.stringToEncode.get(self.fromPosition).unwrap(),
self.charsetEncoderIndex,
)
.len() as u32
} else {
@@ -1088,19 +1074,16 @@ impl RXingResultNode {
)?;
}
if self.mode == Mode::ECI {
bits.appendBits(
self.encoders.getECIValue(self.charsetEncoderIndex as usize),
8,
)?;
bits.appendBits(self.encoders.getECIValue(self.charsetEncoderIndex), 8)?;
} else if self.characterLength > 0 {
// append data
encoder::appendBytes(
// &self.stringToEncode[self.fromPosition as usize
// ..(self.fromPosition + self.characterLength as usize)],
&self.stringToEncode.get(self.fromPosition).unwrap(),
self.stringToEncode.get(self.fromPosition).unwrap(),
self.mode,
bits,
self.encoders.getCharset(self.charsetEncoderIndex as usize),
self.encoders.getCharset(self.charsetEncoderIndex),
)?;
}
Ok(())
@@ -1126,18 +1109,14 @@ impl fmt::Display for RXingResultNode {
result.push_str(&format!("{:?}", self.mode));
result.push('(');
if self.mode == Mode::ECI {
result.push_str(
self.encoders
.getCharset(self.charsetEncoderIndex as usize)
.name(),
);
result.push_str(self.encoders.getCharset(self.charsetEncoderIndex).name());
} else {
let sub_string: String = self
.stringToEncode
.iter()
.skip(self.fromPosition as usize)
.skip(self.fromPosition)
.take(self.characterLength as usize)
.map(|x| String::from(x))
.map(String::from)
.collect();
// result.push_str(&Self::makePrintable(
// &self.stringToEncode[self.fromPosition as usize

View File

@@ -92,7 +92,7 @@ impl QRCode {
// Check if "mask_pattern" is valid.
pub fn isValidMaskPattern(maskPattern: i32) -> bool {
maskPattern >= 0 && maskPattern < Self::NUM_MASK_PATTERNS
(0..Self::NUM_MASK_PATTERNS).contains(&maskPattern)
}
}
@@ -137,3 +137,9 @@ impl fmt::Display for QRCode {
write!(f, "{}", result)
}
}
impl Default for QRCode {
fn default() -> Self {
Self::new()
}
}