cargo clippy && fmt

This commit is contained in:
Henry Schimke
2023-03-02 15:54:40 -06:00
parent 5deb1ddbe2
commit 800efb7984
28 changed files with 111 additions and 135 deletions

View File

@@ -23,7 +23,8 @@ use crate::{
encoder::HighLevelEncoder, encoder::HighLevelEncoder,
shared_test_methods::{stripSpace, toBitArray, toBooleanArray}, shared_test_methods::{stripSpace, toBitArray, toBooleanArray},
}, },
BarcodeFormat, EncodeHintType, EncodeHintValue, Point, common::CharacterSetECI, common::CharacterSetECI,
BarcodeFormat, EncodeHintType, EncodeHintValue, Point,
}; };
use super::{encoder::aztec_encoder, AztecWriter}; use super::{encoder::aztec_encoder, AztecWriter};
@@ -137,8 +138,8 @@ X X X X X X X X X X X X X
#[test] #[test]
fn testAztecWriter() { fn testAztecWriter() {
let shift_jis: CharacterSetECI = let shift_jis: CharacterSetECI =
CharacterSetECI::getCharacterSetECIByName("Shift_JIS").expect("must exist"); CharacterSetECI::getCharacterSetECIByName("Shift_JIS").expect("must exist");
testWriter("Espa\u{00F1}ol", None, 25, true, 1); // Without ECI (implicit ISO-8859-1) testWriter("Espa\u{00F1}ol", None, 25, true, 1); // Without ECI (implicit ISO-8859-1)
testWriter("Espa\u{00F1}ol", Some(ISO_8859_1), 25, true, 1); // Explicit ISO-8859-1 testWriter("Espa\u{00F1}ol", Some(ISO_8859_1), 25, true, 1); // Explicit ISO-8859-1
testWriter("\u{20AC} 1 sample data.", Some(WINDOWS_1252), 25, true, 2); // ISO-8859-1 can't encode Euro; Windows-1252 can testWriter("\u{20AC} 1 sample data.", Some(WINDOWS_1252), 25, true, 2); // ISO-8859-1 can't encode Euro; Windows-1252 can
@@ -817,7 +818,9 @@ fn testStuffBits(wordSize: usize, bits: &str, expected: &str) {
fn testHighLevelEncodeStringUtf8(s: &str, expectedBits: &str) { fn testHighLevelEncodeStringUtf8(s: &str, expectedBits: &str) {
let bits = HighLevelEncoder::with_charset( let bits = HighLevelEncoder::with_charset(
CharacterSetECI::UTF8.encode(s).expect("should encode to bytes"), CharacterSetECI::UTF8
.encode(s)
.expect("should encode to bytes"),
CharacterSetECI::UTF8, CharacterSetECI::UTF8,
) )
.encode() .encode()
@@ -838,7 +841,9 @@ fn testHighLevelEncodeStringUtf8(s: &str, expectedBits: &str) {
fn testHighLevelEncodeString(s: &str, expectedBits: &str) { fn testHighLevelEncodeString(s: &str, expectedBits: &str) {
let bits = HighLevelEncoder::new( let bits = HighLevelEncoder::new(
CharacterSetECI::ISO8859_1.encode(s).expect("should encode to bytes"), CharacterSetECI::ISO8859_1
.encode(s)
.expect("should encode to bytes"),
) )
.encode() .encode()
.expect("high level ok"); .expect("high level ok");
@@ -857,7 +862,9 @@ fn testHighLevelEncodeString(s: &str, expectedBits: &str) {
fn testHighLevelEncodeStringCount(s: &str, expectedReceivedBits: u32) { fn testHighLevelEncodeStringCount(s: &str, expectedReceivedBits: u32) {
let bits = HighLevelEncoder::new( let bits = HighLevelEncoder::new(
CharacterSetECI::ISO8859_1.encode(s).expect("should encode to bytes"), CharacterSetECI::ISO8859_1
.encode(s)
.expect("should encode to bytes"),
) )
.encode() .encode()
.expect("high level ok"); .expect("high level ok");

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{BitMatrix, Result, CharacterSetECI}, common::{BitMatrix, CharacterSetECI, Result},
exceptions::Exceptions, exceptions::Exceptions,
BarcodeFormat, EncodeHintType, EncodeHintValue, Writer, BarcodeFormat, EncodeHintType, EncodeHintValue, Writer,
}; };

View File

@@ -113,7 +113,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
// Intermediary buffer of decoded bytes, which is decoded into a string and flushed // Intermediary buffer of decoded bytes, which is decoded into a string and flushed
// when character encoding changes (ECI) or input ends. // when character encoding changes (ECI) or input ends.
let mut decoded_bytes: Vec<u8> = Vec::new(); let mut decoded_bytes: Vec<u8> = Vec::new();
let mut encdr: CharacterSetECI = CharacterSetECI::ISO8859_1; let mut encdr: CharacterSetECI = CharacterSetECI::ISO8859_1;
let mut index = 0; let mut index = 0;
@@ -159,10 +159,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
let mut n = read_code(corrected_bits, index, 3); let mut n = read_code(corrected_bits, index, 3);
index += 3; index += 3;
// flush bytes, FLG changes state // flush bytes, FLG changes state
result.push_str( result.push_str(&encdr.decode(&decoded_bytes)?);
&encdr
.decode(&decoded_bytes)?,
);
decoded_bytes.clear(); decoded_bytes.clear();
match n { match n {
@@ -206,7 +203,7 @@ fn get_encoded_data(corrected_bits: &[bool]) -> Result<String> {
} }
} else { } else {
// Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*. // Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*.
let b = str.as_bytes(); let b = str.as_bytes();
//let b = str.getBytes(StandardCharsets.US_ASCII); //let b = str.getBytes(StandardCharsets.US_ASCII);
//decodedBytes.write(b, 0, b.length); //decodedBytes.write(b, 0, b.length);

View File

@@ -19,7 +19,7 @@ use crate::{
reedsolomon::{ reedsolomon::{
get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder, get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder,
}, },
BitArray, BitMatrix, Result, CharacterSetECI, BitArray, BitMatrix, CharacterSetECI, Result,
}, },
exceptions::Exceptions, exceptions::Exceptions,
}; };

View File

@@ -14,10 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{ use crate::common::{BitArray, CharacterSetECI, Result};
common::{BitArray, CharacterSetECI, Result},
exceptions::Exceptions,
};
use super::{State, Token}; use super::{State, Token};
@@ -243,10 +240,10 @@ impl HighLevelEncoder {
pub fn encode(&self) -> Result<BitArray> { pub fn encode(&self) -> Result<BitArray> {
let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0); let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0);
//if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) { //if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) {
if self.charset != CharacterSetECI::ISO8859_1 { if self.charset != CharacterSetECI::ISO8859_1 {
//} && eci != CharacterSetECI::Cp1252 { //} && eci != CharacterSetECI::Cp1252 {
initial_state = initial_state.appendFLGn(self.charset.getValue())?; initial_state = initial_state.appendFLGn(self.charset.getValue())?;
} }
// } else { // } else {
// return Err(Exceptions::illegal_argument_with( // return Err(Exceptions::illegal_argument_with(
// "No ECI code for character set", // "No ECI code for character set",

View File

@@ -17,7 +17,7 @@
use std::fmt; use std::fmt;
use crate::{ use crate::{
common::{BitArray, Result, CharacterSetECI}, common::{BitArray, CharacterSetECI, Result},
exceptions::Exceptions, exceptions::Exceptions,
}; };

View File

@@ -20,7 +20,7 @@ use regex::Regex;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{RXingResult, common::CharacterSetECI}; use crate::{common::CharacterSetECI, RXingResult};
use uriparse::URI; use uriparse::URI;
@@ -405,9 +405,7 @@ fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut
fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| String::default()); fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| String::default());
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8); // fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} else if let Some(enc) = CharacterSetECI::getCharacterSetECIByName(charset) { } else if let Some(enc) = CharacterSetECI::getCharacterSetECIByName(charset) {
fragment = if let Ok(encoded_result) = fragment = if let Ok(encoded_result) = enc.decode(&fragmentBytes) {
enc.decode(&fragmentBytes)
{
encoded_result encoded_result
} else { } else {
String::from_utf8(fragmentBytes).unwrap_or_else(|_| String::default()) String::from_utf8(fragmentBytes).unwrap_or_else(|_| String::default())

View File

@@ -40,19 +40,14 @@ fn test_random() {
// } // }
assert_eq!( assert_eq!(
CharacterSetECI::UTF8, CharacterSetECI::UTF8,
StringUtils::guessCharset(&bytes, &HashMap::new()) StringUtils::guessCharset(&bytes, &HashMap::new()).unwrap()
.unwrap()
); );
} }
#[test] #[test]
fn test_short_shift_jis1() { fn test_short_shift_jis1() {
// 金魚 // 金魚
do_test( do_test(&[0x8b, 0xe0, 0x8b, 0x9b], CharacterSetECI::SJIS, "SJIS");
&[0x8b, 0xe0, 0x8b, 0x9b],
CharacterSetECI::SJIS,
"SJIS",
);
} }
#[test] #[test]
@@ -87,7 +82,7 @@ fn test_utf16_be() {
do_test( do_test(
&[0xFE, 0xFF, 0x8c, 0x03, 0x53, 0x8b, 0x67, 0xdc], &[0xFE, 0xFF, 0x8c, 0x03, 0x53, 0x8b, 0x67, 0xdc],
CharacterSetECI::UnicodeBigUnmarked, CharacterSetECI::UnicodeBigUnmarked,
&CharacterSetECI::UnicodeBigUnmarked.getCharsetName(), CharacterSetECI::UnicodeBigUnmarked.getCharsetName(),
); );
} }
@@ -97,7 +92,7 @@ fn test_utf16_le() {
do_test( do_test(
&[0xFF, 0xFE, 0x03, 0x8c, 0x8b, 0x53, 0xdc, 0x67], &[0xFF, 0xFE, 0x03, 0x8c, 0x8b, 0x53, 0xdc, 0x67],
CharacterSetECI::UTF16LE, CharacterSetECI::UTF16LE,
&CharacterSetECI::UTF16LE.getCharsetName(), CharacterSetECI::UTF16LE.getCharsetName(),
); );
} }

View File

@@ -17,7 +17,7 @@
use encoding::EncodingRef; use encoding::EncodingRef;
use crate::common::Result; use crate::common::Result;
use crate::{Exceptions}; use crate::Exceptions;
/** /**
* Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1 * Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1
@@ -51,11 +51,11 @@ pub enum CharacterSetECI {
Cp1256, //(24, "windows-1256"), Cp1256, //(24, "windows-1256"),
UnicodeBigUnmarked, //(25, "UTF-16BE", "UnicodeBig"), UnicodeBigUnmarked, //(25, "UTF-16BE", "UnicodeBig"),
UTF16LE, UTF16LE,
UTF8, //(26, "UTF-8"), UTF8, //(26, "UTF-8"),
ASCII, //(new int[] {27, 170}, "US-ASCII"), ASCII, //(new int[] {27, 170}, "US-ASCII"),
Big5, //(28), Big5, //(28),
GB18030, //(29, "GB2312", "EUC_CN", "GBK"), GB18030, //(29, "GB2312", "EUC_CN", "GBK"),
EUC_KR, //(30, "EUC-KR"); EUC_KR, //(30, "EUC-KR");
} }
impl CharacterSetECI { impl CharacterSetECI {
// private static final Map<Integer,CharacterSetECI> VALUE_TO_ECI = new HashMap<>(); // private static final Map<Integer,CharacterSetECI> VALUE_TO_ECI = new HashMap<>();
@@ -126,7 +126,7 @@ impl CharacterSetECI {
} }
} }
pub fn getCharset(&self, ) -> EncodingRef { pub fn getCharset(&self) -> EncodingRef {
let name = match self { let name = match self {
// CharacterSetECI::Cp437 => "CP437", // CharacterSetECI::Cp437 => "CP437",
CharacterSetECI::Cp437 => "cp437", CharacterSetECI::Cp437 => "cp437",
@@ -161,8 +161,8 @@ impl CharacterSetECI {
encoding::label::encoding_from_whatwg_label(name).unwrap() encoding::label::encoding_from_whatwg_label(name).unwrap()
} }
pub fn getCharsetName(&self, ) -> &'static str { pub fn getCharsetName(&self) -> &'static str {
match self { match self {
// CharacterSetECI::Cp437 => "CP437", // CharacterSetECI::Cp437 => "CP437",
CharacterSetECI::Cp437 => "cp437", CharacterSetECI::Cp437 => "cp437",
CharacterSetECI::ISO8859_1 => "iso-8859-1", CharacterSetECI::ISO8859_1 => "iso-8859-1",
@@ -193,7 +193,6 @@ impl CharacterSetECI {
CharacterSetECI::GB18030 => "gb2312", CharacterSetECI::GB18030 => "gb2312",
CharacterSetECI::EUC_KR => "euc-kr", CharacterSetECI::EUC_KR => "euc-kr",
} }
} }
/** /**
@@ -317,25 +316,33 @@ impl CharacterSetECI {
} }
pub fn encode(&self, input: &str) -> Result<Vec<u8>> { pub fn encode(&self, input: &str) -> Result<Vec<u8>> {
self.getCharset().encode(input, encoding::EncoderTrap::Strict).map_err(|e| Exceptions::format_with(e.to_string())) self.getCharset()
.encode(input, encoding::EncoderTrap::Strict)
.map_err(|e| Exceptions::format_with(e.to_string()))
} }
pub fn encode_replace(&self, input: &str) -> Result<Vec<u8>> { pub fn encode_replace(&self, input: &str) -> Result<Vec<u8>> {
self.getCharset().encode(input, encoding::EncoderTrap::Replace).map_err(|e| Exceptions::format_with(e.to_string())) self.getCharset()
.encode(input, encoding::EncoderTrap::Replace)
.map_err(|e| Exceptions::format_with(e.to_string()))
} }
pub fn decode(&self, input:&[u8]) -> Result<String> { pub fn decode(&self, input: &[u8]) -> Result<String> {
if self == &CharacterSetECI::Cp437 { if self == &CharacterSetECI::Cp437 {
use codepage_437::BorrowFromCp437; use codepage_437::BorrowFromCp437;
use codepage_437::CP437_CONTROL; use codepage_437::CP437_CONTROL;
Ok(String::borrow_from_cp437(&input, &CP437_CONTROL)) Ok(String::borrow_from_cp437(&input, &CP437_CONTROL))
}else { } else {
self.getCharset().decode(input, encoding::DecoderTrap::Strict).map_err(|e| Exceptions::format_with(e.to_string())) self.getCharset()
.decode(input, encoding::DecoderTrap::Strict)
.map_err(|e| Exceptions::format_with(e.to_string()))
} }
} }
pub fn decode_replace(&self, input:&[u8]) -> Result<String> { pub fn decode_replace(&self, input: &[u8]) -> Result<String> {
self.getCharset().decode(input, encoding::DecoderTrap::Replace).map_err(|e| Exceptions::format_with(e.to_string())) self.getCharset()
.decode(input, encoding::DecoderTrap::Replace)
.map_err(|e| Exceptions::format_with(e.to_string()))
} }
} }

View File

@@ -112,9 +112,7 @@ impl ECIEncoderSet {
for encoder in &neededEncoders { for encoder in &neededEncoders {
// for (CharsetEncoder encoder : neededEncoders) { // for (CharsetEncoder encoder : neededEncoders) {
let c = stringToEncode.get(i).unwrap(); let c = stringToEncode.get(i).unwrap();
if (fnc1.is_some() && c == fnc1.as_ref().unwrap()) if (fnc1.is_some() && c == fnc1.as_ref().unwrap()) || encoder.encode(c).is_ok() {
|| encoder.encode(c).is_ok()
{
canEncode = true; canEncode = true;
break; break;
} }
@@ -125,12 +123,7 @@ impl ECIEncoderSet {
// for encoder in ENCODERS { // for encoder in ENCODERS {
let encoder = ENCODERS.get(i_encoder).unwrap(); let encoder = ENCODERS.get(i_encoder).unwrap();
// for (CharsetEncoder encoder : ENCODERS) { // for (CharsetEncoder encoder : ENCODERS) {
if encoder if encoder.encode(stringToEncode.get(i).unwrap()).is_ok() {
.encode(
stringToEncode.get(i).unwrap()
)
.is_ok()
{
//Good, we found an encoder that can encode the character. We add him to the list and continue scanning //Good, we found an encoder that can encode the character. We add him to the list and continue scanning
//the input //the input
neededEncoders.push(*encoder); neededEncoders.push(*encoder);

View File

@@ -136,9 +136,7 @@ impl ECIStringBuilder {
} else if !self.current_bytes.is_empty() { } else if !self.current_bytes.is_empty() {
let bytes = std::mem::take(&mut self.current_bytes); let bytes = std::mem::take(&mut self.current_bytes);
self.current_bytes.clear(); self.current_bytes.clear();
let encoded_value = encoder let encoded_value = encoder.decode(&bytes).unwrap();
.decode(&bytes)
.unwrap();
self.result.push_str(&encoded_value); self.result.push_str(&encoded_value);
} }
} else { } else {

View File

@@ -21,7 +21,7 @@ use unicode_segmentation::UnicodeSegmentation;
use crate::common::Result; use crate::common::Result;
use crate::Exceptions; use crate::Exceptions;
use super::{ECIEncoderSet, ECIInput, CharacterSetECI}; use super::{CharacterSetECI, ECIEncoderSet, ECIInput};
//* approximated (latch + 2 codewords) //* approximated (latch + 2 codewords)
pub const COST_PER_ECI: usize = 3; pub const COST_PER_ECI: usize = 3;

View File

@@ -16,8 +16,6 @@
use crate::{DecodeHintType, DecodeHintValue, DecodingHintDictionary}; use crate::{DecodeHintType, DecodeHintValue, DecodingHintDictionary};
use once_cell::sync::Lazy;
use super::CharacterSetECI; use super::CharacterSetECI;
/** /**
@@ -50,8 +48,7 @@ const ASSUME_SHIFT_JIS: bool = false;
// static SHIFT_JIS: &'static str = "SJIS"; // static SHIFT_JIS: &'static str = "SJIS";
// static GB2312: &'static str = "GB2312"; // static GB2312: &'static str = "GB2312";
pub static SHIFT_JIS_CHARSET: CharacterSetECI = pub static SHIFT_JIS_CHARSET: CharacterSetECI = CharacterSetECI::SJIS;
CharacterSetECI::SJIS;
// private static final boolean ASSUME_SHIFT_JIS = // private static final boolean ASSUME_SHIFT_JIS =
// SHIFT_JIS_CHARSET.equals(PLATFORM_DEFAULT_ENCODING) || // SHIFT_JIS_CHARSET.equals(PLATFORM_DEFAULT_ENCODING) ||
@@ -74,7 +71,7 @@ impl StringUtils {
} else if c == CharacterSetECI::ISO8859_1 { } else if c == CharacterSetECI::ISO8859_1 {
Some("ISO8859_1") Some("ISO8859_1")
} else { } else {
Some(&c.getCharsetName()) Some(c.getCharsetName())
} }
} }
@@ -92,7 +89,7 @@ impl StringUtils {
hints.get(&DecodeHintType::CHARACTER_SET) hints.get(&DecodeHintType::CHARACTER_SET)
{ {
// if let DecodeHintValue::CharacterSet(cs_name) = hint { // if let DecodeHintValue::CharacterSet(cs_name) = hint {
return CharacterSetECI::getCharacterSetECIByName(cs_name) return CharacterSetECI::getCharacterSetECIByName(cs_name);
// } // }
} }
// if hints.contains_key(&DecodeHintType::CHARACTER_SET) { // if hints.contains_key(&DecodeHintType::CHARACTER_SET) {
@@ -260,6 +257,6 @@ impl StringUtils {
return Some(CharacterSetECI::UTF8); return Some(CharacterSetECI::UTF8);
} }
// Otherwise, we take a wild guess with platform encoding // Otherwise, we take a wild guess with platform encoding
Some(CharacterSetECI::UTF8) Some(CharacterSetECI::UTF8)
} }
} }

View File

@@ -18,7 +18,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{BitMatrix, Result, CharacterSetECI}, common::{BitMatrix, CharacterSetECI, Result},
qrcode::encoder::ByteMatrix, qrcode::encoder::ByteMatrix,
BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
}; };
@@ -122,7 +122,8 @@ impl Writer for DataMatrixWriter {
hints.get(&EncodeHintType::CHARACTER_SET) else { hints.get(&EncodeHintType::CHARACTER_SET) else {
return Err(Exceptions::illegal_argument_with("charset does not exist")) return Err(Exceptions::illegal_argument_with("charset does not exist"))
}; };
charset = CharacterSetECI::getCharacterSetECIByName(char_set_name);//encoding::label::encoding_from_whatwg_label(char_set_name); charset = CharacterSetECI::getCharacterSetECIByName(char_set_name);
//encoding::label::encoding_from_whatwg_label(char_set_name);
// charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); // charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
} }
encoded = minimal_encoder::encodeHighLevelWithDetails( encoded = minimal_encoder::encodeHighLevelWithDetails(

View File

@@ -15,7 +15,7 @@
*/ */
use crate::{ use crate::{
common::{BitSource, DecoderRXingResult, ECIStringBuilder, Result, CharacterSetECI}, common::{BitSource, CharacterSetECI, DecoderRXingResult, ECIStringBuilder, Result},
Exceptions, Exceptions,
}; };
@@ -727,12 +727,7 @@ fn decodeBase256Segment(
*byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8; *byte = unrandomize255State(bits.readBits(8)?, codewordPosition) as u8;
codewordPosition += 1; codewordPosition += 1;
} }
result.append_string( result.append_string(&CharacterSetECI::ISO8859_1.decode(&bytes)?);
&CharacterSetECI::ISO8859_1
.decode(&bytes)
?,
);
byteSegments.push(bytes); byteSegments.push(bytes);
Ok(()) Ok(())

View File

@@ -16,7 +16,7 @@
use std::rc::Rc; use std::rc::Rc;
use crate::common::{Result, CharacterSetECI}; use crate::common::{CharacterSetECI, Result};
use crate::{Dimension, Exceptions}; use crate::{Dimension, Exceptions};
use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint}; use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint};
@@ -57,14 +57,10 @@ impl<'a> EncoderContext<'_> {
// } // }
// sb.append(ch); // sb.append(ch);
// } // }
let sb = if let Ok(encoded_bytes) = let sb = if let Ok(encoded_bytes) = ISO_8859_1_ENCODER.encode(msg) {
ISO_8859_1_ENCODER.encode(msg) ISO_8859_1_ENCODER.decode(&encoded_bytes).map_err(|e| {
{ Exceptions::parse_with(format!("round trip decode should always work: {e}"))
ISO_8859_1_ENCODER })?
.decode(&encoded_bytes)
.map_err(|e| {
Exceptions::parse_with(format!("round trip decode should always work: {e}"))
})?
} else { } else {
return Err(Exceptions::illegal_argument_with( return Err(Exceptions::illegal_argument_with(
"Message contains characters outside ISO-8859-1 encoding.", "Message contains characters outside ISO-8859-1 encoding.",

View File

@@ -18,7 +18,10 @@ use std::rc::Rc;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{datamatrix::encoder::{SymbolInfo, SymbolShapeHint}, common::CharacterSetECI}; use crate::{
common::CharacterSetECI,
datamatrix::encoder::{SymbolInfo, SymbolShapeHint},
};
use super::{high_level_encoder, minimal_encoder, symbol_info, SymbolInfoLookup}; use super::{high_level_encoder, minimal_encoder, symbol_info, SymbolInfoLookup};

View File

@@ -16,7 +16,7 @@
use std::rc::Rc; use std::rc::Rc;
use crate::common::{Result, CharacterSetECI}; use crate::common::{CharacterSetECI, Result};
use crate::{Dimension, Exceptions}; use crate::{Dimension, Exceptions};
use super::{ use super::{

View File

@@ -17,7 +17,7 @@
use std::{fmt, rc::Rc}; use std::{fmt, rc::Rc};
use crate::{ use crate::{
common::{ECIInput, MinimalECIInput, Result, CharacterSetECI}, common::{CharacterSetECI, ECIInput, MinimalECIInput, Result},
Exceptions, Exceptions,
}; };
@@ -171,10 +171,7 @@ pub fn encodeHighLevelWithDetails(
msg = &msg[high_level_encoder::MACRO_06_HEADER.chars().count()..(msg.chars().count() - 2)]; msg = &msg[high_level_encoder::MACRO_06_HEADER.chars().count()..(msg.chars().count() - 2)];
} }
Ok(ISO_8859_1_ENCODER Ok(ISO_8859_1_ENCODER
.decode( .decode(&encode(msg, priorityCharset, fnc1, shape, macroId)?)
&encode(msg, priorityCharset, fnc1, shape, macroId)?
)
.expect("should decode")) .expect("should decode"))
// return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1); // return new String(encode(msg, priorityCharset, fnc1, shape, macroId), StandardCharsets.ISO_8859_1);
} }

View File

@@ -18,7 +18,7 @@
* This file has been modified from its original form in Barcode4J. * This file has been modified from its original form in Barcode4J.
*/ */
use crate::common::{Result, CharacterSetECI}; use crate::common::{CharacterSetECI, Result};
use crate::Exceptions; use crate::Exceptions;
use super::{ use super::{

View File

@@ -197,16 +197,17 @@ pub fn encodeHighLevel(
input = Box::new(NoECIInput::new(msg.to_owned())); input = Box::new(NoECIInput::new(msg.to_owned()));
if encoding.is_none() { if encoding.is_none() {
encoding = Some(DEFAULT_ENCODING); encoding = Some(DEFAULT_ENCODING);
} else if &DEFAULT_ENCODING } else if &DEFAULT_ENCODING != encoding.as_ref().ok_or(Exceptions::ILLEGAL_STATE)? {
!= encoding.as_ref().ok_or(Exceptions::ILLEGAL_STATE)?
{
// if let Some(eci) = // if let Some(eci) =
// CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::ILLEGAL_STATE)?) // CharacterSetECI::getCharacterSetECI(encoding.ok_or(Exceptions::ILLEGAL_STATE)?)
// { // {
// encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?; // encodingECI(CharacterSetECI::getValue(&eci) as i32, &mut sb)?;
// } // }
encodingECI(CharacterSetECI::getValue(&encoding.ok_or(Exceptions::ILLEGAL_STATE)?) as i32, &mut sb)?; encodingECI(
CharacterSetECI::getValue(&encoding.ok_or(Exceptions::ILLEGAL_STATE)?) as i32,
&mut sb,
)?;
} }
} }
@@ -768,12 +769,7 @@ fn determineConsecutiveBinaryCount<T: ECIInput + ?Sized + 'static>(
} }
if let Some(encoder) = encoding { if let Some(encoder) = encoding {
let can_encode = encoder let can_encode = encoder.encode(&input.charAt(idx)?.to_string()).is_ok();
.encode(
&input.charAt(idx)?.to_string()
)
.is_ok();
if !can_encode { if !can_encode {
if TypeId::of::<T>() != TypeId::of::<NoECIInput>() { if TypeId::of::<T>() != TypeId::of::<NoECIInput>() {
@@ -856,7 +852,10 @@ impl Display for NoECIInput {
*/ */
#[cfg(test)] #[cfg(test)]
mod PDF417EncoderTestCase { mod PDF417EncoderTestCase {
use crate::{pdf417::encoder::{pdf_417_high_level_encoder::encodeHighLevel, Compaction}, common::CharacterSetECI}; use crate::{
common::CharacterSetECI,
pdf417::encoder::{pdf_417_high_level_encoder::encodeHighLevel, Compaction},
};
#[test] #[test]
fn testEncodeAuto() { fn testEncodeAuto() {

View File

@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::common::{Result, CharacterSetECI}; use crate::common::{CharacterSetECI, Result};
use super::{pdf_417_high_level_encoder, Compaction}; use super::{pdf_417_high_level_encoder, Compaction};

View File

@@ -17,7 +17,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
common::{BitMatrix, Result, CharacterSetECI}, common::{BitMatrix, CharacterSetECI, Result},
BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer, BarcodeFormat, EncodeHintType, EncodeHintValue, Exceptions, Writer,
}; };

View File

@@ -203,8 +203,7 @@ fn decodeHanziSegment(bits: &mut BitSource, result: &mut String, count: usize) -
count -= 1; count -= 1;
} }
let gb_encoder = let gb_encoder = CharacterSetECI::GB18030;
CharacterSetECI::GB18030;
let encode_string = gb_encoder let encode_string = gb_encoder
.decode(&buffer) .decode(&buffer)
.map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?; .map_err(|e| Exceptions::parse_with(format!("unable to decode buffer {buffer:?}: {e}")))?;
@@ -321,13 +320,9 @@ fn decodeByteSegment(
// ) // )
}; };
let encode_string = let encode_string = encoding.decode(&readBytes).map_err(|e| {
encoding Exceptions::parse_with(format!("unable to decode buffer {readBytes:?}: {e}"))
.decode(&readBytes) })?;
.map_err(|e| {
Exceptions::parse_with(format!("unable to decode buffer {readBytes:?}: {e}"))
})?
;
result.push_str(&encode_string); result.push_str(&encode_string);
byteSegments.push(readBytes); byteSegments.push(readBytes);

View File

@@ -28,8 +28,7 @@ use once_cell::sync::Lazy;
use super::QRCode; use super::QRCode;
static SHIFT_JIS_CHARSET: Lazy<CharacterSetECI> = static SHIFT_JIS_CHARSET: Lazy<CharacterSetECI> = Lazy::new(|| CharacterSetECI::SJIS);
Lazy::new(|| CharacterSetECI::SJIS);
/** /**
* @author satorux@google.com (Satoru Takabayashi) - creator * @author satorux@google.com (Satoru Takabayashi) - creator

View File

@@ -17,7 +17,7 @@
use std::{fmt, rc::Rc}; use std::{fmt, rc::Rc};
use crate::{ use crate::{
common::{BitArray, ECIEncoderSet, Result, CharacterSetECI}, common::{BitArray, CharacterSetECI, ECIEncoderSet, Result},
qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef}, qrcode::decoder::{ErrorCorrectionLevel, Mode, Version, VersionRef},
Exceptions, Exceptions,
}; };
@@ -1042,7 +1042,7 @@ impl fmt::Display for RXingResultNode {
result.push('('); result.push('(');
if self.mode == Mode::ECI { if self.mode == Mode::ECI {
result.push_str( result.push_str(
&self.encoders self.encoders
.getCharset(self.charsetEncoderIndex) .getCharset(self.charsetEncoderIndex)
.ok_or(fmt::Error)? .ok_or(fmt::Error)?
.getCharsetName(), .getCharsetName(),

View File

@@ -32,8 +32,7 @@ use crate::{
use super::{mask_util, matrix_util, BlockPair, ByteMatrix, MinimalEncoder, QRCode}; use super::{mask_util, matrix_util, BlockPair, ByteMatrix, MinimalEncoder, QRCode};
static SHIFT_JIS_CHARSET: CharacterSetECI = static SHIFT_JIS_CHARSET: CharacterSetECI = CharacterSetECI::SJIS;
CharacterSetECI::SJIS;
// The original table is defined in the table 5 of JISX0510:2004 (p.19). // The original table is defined in the table 5 of JISX0510:2004 (p.19).
const ALPHANUMERIC_TABLE: [i8; 96] = [ const ALPHANUMERIC_TABLE: [i8; 96] = [
@@ -97,8 +96,7 @@ pub fn encode_with_hints(
let mut has_encoding_hint = hints.contains_key(&EncodeHintType::CHARACTER_SET); let mut has_encoding_hint = hints.contains_key(&EncodeHintType::CHARACTER_SET);
if has_encoding_hint { if has_encoding_hint {
if let Some(EncodeHintValue::CharacterSet(v)) = hints.get(&EncodeHintType::CHARACTER_SET) { if let Some(EncodeHintValue::CharacterSet(v)) = hints.get(&EncodeHintType::CHARACTER_SET) {
encoding = encoding = Some(CharacterSetECI::getCharacterSetECIByName(v).ok_or(Exceptions::WRITER)?)
Some(CharacterSetECI::getCharacterSetECIByName(v).ok_or(Exceptions::WRITER)?)
} }
} }
@@ -122,9 +120,7 @@ pub fn encode_with_hints(
//Switch to default encoding //Switch to default encoding
let encoding = if let Some(encoding) = encoding { let encoding = if let Some(encoding) = encoding {
encoding encoding
} else if let Ok(_encs) = } else if let Ok(_encs) = DEFAULT_BYTE_MODE_ENCODING.encode(content) {
DEFAULT_BYTE_MODE_ENCODING.encode(content)
{
DEFAULT_BYTE_MODE_ENCODING DEFAULT_BYTE_MODE_ENCODING
} else { } else {
has_encoding_hint = true; has_encoding_hint = true;
@@ -720,7 +716,11 @@ pub fn appendAlphanumericBytes(content: &str, bits: &mut BitArray) -> Result<()>
Ok(()) Ok(())
} }
pub fn append8BitBytes(content: &str, bits: &mut BitArray, encoding: CharacterSetECI) -> Result<()> { pub fn append8BitBytes(
content: &str,
bits: &mut BitArray,
encoding: CharacterSetECI,
) -> Result<()> {
let bytes = encoding let bytes = encoding
.encode(content) .encode(content)
.map_err(|e| Exceptions::writer_with(format!("error {e}")))?; .map_err(|e| Exceptions::writer_with(format!("error {e}")))?;

View File

@@ -24,7 +24,7 @@ use std::{
}; };
use rxing::{ use rxing::{
common::{HybridBinarizer, Result, CharacterSetECI}, common::{CharacterSetECI, HybridBinarizer, Result},
multi::MultipleBarcodeReader, multi::MultipleBarcodeReader,
pdf417::PDF417RXingResultMetadata, pdf417::PDF417RXingResultMetadata,
BarcodeFormat, BinaryBitmap, BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue, BarcodeFormat, BinaryBitmap, BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue,
@@ -645,7 +645,9 @@ impl<T: MultipleBarcodeReader + Reader> PDF417MultiImageSpanAbstractBlackBoxTest
if ext == "bin" { if ext == "bin" {
let mut buffer: Vec<u8> = Vec::new(); let mut buffer: Vec<u8> = Vec::new();
File::open(&file)?.read_to_end(&mut buffer)?; File::open(&file)?.read_to_end(&mut buffer)?;
CharacterSetECI::ISO8859_1.decode_replace(&buffer).expect("decode") CharacterSetECI::ISO8859_1
.decode_replace(&buffer)
.expect("decode")
} else { } else {
read_to_string(&file).expect("ok") read_to_string(&file).expect("ok")
} }