cargo fmt

This commit is contained in:
Henry Schimke
2022-10-17 10:51:08 -05:00
parent 111fe47566
commit ae11af8c5b
136 changed files with 2117 additions and 1776 deletions

View File

@@ -24,11 +24,11 @@
// */
// public final class RGBLuminanceSourceTestCase extends Assert {
use crate::{RGBLuminanceSource, LuminanceSource};
use crate::{LuminanceSource, RGBLuminanceSource};
const SRC_DATA : [u32;9] = [0x000000, 0x7F7F7F, 0xFFFFFF,
0xFF0000, 0x00FF00, 0x0000FF,
0x0000FF, 0x00FF00, 0xFF0000];
const SRC_DATA: [u32; 9] = [
0x000000, 0x7F7F7F, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0x0000FF, 0x00FF00, 0xFF0000,
];
#[test]
fn testCrop() {
@@ -45,14 +45,17 @@ use crate::{RGBLuminanceSource, LuminanceSource};
fn testMatrix() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec());
assert_eq!(vec![ 0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F ],
SOURCE.getMatrix());
assert_eq!(
vec![0x00, 0x7F, 0xFF, 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F],
SOURCE.getMatrix()
);
let croppedFullWidth = SOURCE.crop(0, 1, 3, 2).unwrap();
assert_eq!(vec![ 0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F ],
croppedFullWidth.getMatrix());
assert_eq!(
vec![0x3F, 0x7F, 0x3F, 0x3F, 0x7F, 0x3F],
croppedFullWidth.getMatrix()
);
let croppedCorner = SOURCE.crop(1, 1, 2, 2).unwrap();
assert_eq!(vec![ 0x7F, 0x3F, 0x7F, 0x3F ],
croppedCorner.getMatrix());
assert_eq!(vec![0x7F, 0x3F, 0x7F, 0x3F], croppedCorner.getMatrix());
}
#[test]

View File

@@ -177,7 +177,9 @@ fn testAztecWriter() {
// Test AztecWriter defaults
let data = "In ut magna vel mauris malesuada";
let writer = AztecWriter {};
let matrix = writer.encode(data, &BarcodeFormat::AZTEC, 0, 0).expect("matrix must exist");
let matrix = writer
.encode(data, &BarcodeFormat::AZTEC, 0, 0)
.expect("matrix must exist");
let aztec = encoder::encode(
data,
encoder::DEFAULT_EC_PERCENT,
@@ -731,7 +733,8 @@ fn testWriter(
EncodeHintType::ERROR_CORRECTION,
EncodeHintValue::ErrorCorrection(ecc_percent.to_string()),
);
let mut matrix = AztecWriter{}.encode_with_hints(data, &BarcodeFormat::AZTEC, 0, 0, &hints)
let mut matrix = AztecWriter {}
.encode_with_hints(data, &BarcodeFormat::AZTEC, 0, 0, &hints)
.expect("encoder created");
let cset = match charset {

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
use std::{ collections::HashMap};
use std::collections::HashMap;
use encoding::EncodingRef;

View File

@@ -14,11 +14,10 @@
* limitations under the License.
*/
use crate::{
common::{
reedsolomon::{
get_predefined_genericgf, PredefinedGenericGF, ReedSolomonDecoder, GenericGFRef,
get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonDecoder,
},
BitMatrix, CharacterSetECI, DecoderRXingResult, DetectorRXingResult,
},

View File

@@ -635,7 +635,11 @@ impl Detector {
for _i in 0..i_max {
// for (int i = 0; i < iMax; i++) {
if self.image.get(MathUtils::round(px) as u32, MathUtils::round(py) as u32) != color_model {
if self
.image
.get(MathUtils::round(px) as u32, MathUtils::round(py) as u32)
!= color_model
{
error += 1;
}
px += dx;

View File

@@ -50,7 +50,9 @@ impl BinaryShiftToken {
bit_array.appendBits(bsbc as u32 - 31, 5).unwrap();
}
}
bit_array.appendBits(text[self.binary_shift_start as usize + i].into(), 8).expect("should never fail to append");
bit_array
.appendBits(text[self.binary_shift_start as usize + i].into(), 8)
.expect("should never fail to append");
}
}

View File

@@ -19,7 +19,7 @@ use encoding::Encoding;
use crate::{
common::{
reedsolomon::{
get_predefined_genericgf, PredefinedGenericGF, ReedSolomonEncoder, GenericGFRef,
get_predefined_genericgf, GenericGFRef, PredefinedGenericGF, ReedSolomonEncoder,
},
BitArray, BitMatrix,
},

View File

@@ -127,8 +127,8 @@ impl HighLevelEncoder {
char_map[Self::MODE_DIGIT][b'.' as usize] = 13;
let mixed_table = [
'\0', ' ', '\u{1}', '\u{2}', '\u{3}', '\u{4}', '\u{5}', '\u{6}', '\u{7}', '\u{8}',
'\t', '\n', '\u{000b}', '\u{000c}', '\r', '\u{001b}', '\u{001c}', '\u{001d}', '\u{001e}', '\u{001f}',
'@', '\\', '^', '_', '`', '|', '~', '\u{007f}',
'\t', '\n', '\u{000b}', '\u{000c}', '\r', '\u{001b}', '\u{001c}', '\u{001d}',
'\u{001e}', '\u{001f}', '@', '\\', '^', '_', '`', '|', '~', '\u{007f}',
];
let mut i = 0;
while i < mixed_table.len() {
@@ -245,7 +245,8 @@ impl HighLevelEncoder {
pub fn encode(&self) -> Result<BitArray, Exceptions> {
let mut initial_state = State::new(Token::new(), Self::MODE_UPPER as u32, 0, 0);
if let Some(eci) = CharacterSetECI::getCharacterSetECI(self.charset) {
if eci != CharacterSetECI::ISO8859_1 {//} && eci != CharacterSetECI::Cp1252 {
if eci != CharacterSetECI::ISO8859_1 {
//} && eci != CharacterSetECI::Cp1252 {
initial_state = initial_state.appendFLGn(CharacterSetECI::getValue(&eci))?;
}
} else {

View File

@@ -1,15 +1,15 @@
mod aztec_code;
mod token;
mod simple_token;
mod binary_shift_token;
mod state;
mod high_level_encoder;
mod simple_token;
mod state;
mod token;
pub mod encoder;
pub use aztec_code::*;
pub use token::*;
pub use simple_token::*;
pub use binary_shift_token::*;
pub use state::*;
pub use high_level_encoder::*;
pub use simple_token::*;
pub use state::*;
pub use token::*;

View File

@@ -78,7 +78,8 @@ impl State {
let mut bits_added = 3;
/*if eci < 0 {
token.add(0, 3); // 0: FNC1
} else */if eci > 999999 {
} else */
if eci > 999999 {
return Err(Exceptions::IllegalArgumentException(
"ECI code must be between 0 and 999999".to_owned(),
));
@@ -151,7 +152,8 @@ impl State {
bitCount += latch >> 16;
mode = HighLevelEncoder::MODE_UPPER as u32;
}
let deltaBitCount = if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 {
let deltaBitCount =
if self.binary_shift_byte_count == 0 || self.binary_shift_byte_count == 31 {
18
} else {
if self.binary_shift_byte_count == 62 {
@@ -180,7 +182,10 @@ impl State {
return self;
}
let mut token = self.token;
token.addBinaryShift(index - self.binary_shift_byte_count, self.binary_shift_byte_count);
token.addBinaryShift(
index - self.binary_shift_byte_count,
self.binary_shift_byte_count,
);
State::new(token, self.mode, 0, self.bit_count)
}

View File

@@ -11,8 +11,8 @@ pub use aztec_writer::*;
#[cfg(test)]
mod DecoderTest;
#[cfg(test)]
mod EncoderTest;
#[cfg(test)]
mod DetectorTest;
#[cfg(test)]
mod EncoderTest;
mod shared_test_methods;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2009 ZXing authors
*
@@ -17,7 +16,10 @@
//package com.google.zxing;
use crate::{common::{BitArray, BitMatrix}, Exceptions, LuminanceSource};
use crate::{
common::{BitArray, BitMatrix},
Exceptions, LuminanceSource,
};
/**
* This class hierarchy provides a set of methods to convert luminance data to 1 bit data.

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2009 ZXing authors
*
@@ -19,7 +18,10 @@
use std::fmt;
use crate::{common::{BitMatrix, BitArray}, Exceptions, Binarizer};
use crate::{
common::{BitArray, BitMatrix},
Binarizer, Exceptions,
};
/**
* This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects

View File

@@ -13,7 +13,6 @@
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
// package com.google.zxing.client.result;
// /**

View File

@@ -46,8 +46,10 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let lastName = ResultParser::match_single_do_co_mo_prefixed_field("X:", &rawText, true)
.unwrap_or_default();
let fullName = buildName(&firstName, &lastName);
let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true).unwrap_or_default();
let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true).unwrap_or_default();
let title = ResultParser::match_single_do_co_mo_prefixed_field("T:", &rawText, true)
.unwrap_or_default();
let org = ResultParser::match_single_do_co_mo_prefixed_field("C:", &rawText, true)
.unwrap_or_default();
let addresses = ResultParser::match_do_co_mo_prefixed_field("A:", &rawText);
let phoneNumber1 = ResultParser::match_single_do_co_mo_prefixed_field("B:", &rawText, true)
.unwrap_or_default();

View File

@@ -20,9 +20,7 @@
use crate::RXingResult;
use super::{
ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser,
};
use super::{ParsedClientResult, ResultParser, URIParsedRXingResult, URIResultParser};
/**
* @author Sean Owen
@@ -40,7 +38,8 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let uri = rawUri?[0].clone();
if URIResultParser::is_basically_valid_uri(&uri) {
Some(ParsedClientResult::URIResult(URIParsedRXingResult::new(
uri, title.unwrap_or("".to_owned()),
uri,
title.unwrap_or("".to_owned()),
)))
} else {
None

View File

@@ -29,14 +29,12 @@
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use chrono_tz::Tz;
use regex::Regex;
use lazy_static::lazy_static;
use regex::Regex;
use crate::exceptions::Exceptions;
use super::{
maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType
};
use super::{maybe_append_multiple, maybe_append_string, ParsedRXingResult, ParsedRXingResultType};
// const RFC2445_DURATION: &'static str =
// "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?";
@@ -50,7 +48,8 @@ const RFC2445_DURATION_FIELD_UNITS: [i64; 5] = [
lazy_static! {
static ref DATE_TIME: Regex = Regex::new("[0-9]{8}(T[0-9]{6}Z?)?").unwrap();
static ref RFC2445_DURATION: Regex = Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap();
static ref RFC2445_DURATION: Regex =
Regex::new("P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?").unwrap();
}
// const DATE_TIME: &'static str = "[0-9]{8}(T[0-9]{6}Z?)?";

View File

@@ -34,7 +34,7 @@
// */
// public final class CalendarParsedRXingResultTestCase extends Assert {
use chrono::{NaiveDateTime};
use chrono::NaiveDateTime;
use crate::{
client::result::{ParsedClientResult, ParsedRXingResultType},

View File

@@ -22,7 +22,7 @@
// import org.junit.Test;
use crate::{
client::result::{ParsedClientResult, ParsedRXingResultType, ResultParser, ParsedRXingResult},
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType, ResultParser},
BarcodeFormat, RXingResult,
};

View File

@@ -28,10 +28,13 @@ use lazy_static::lazy_static;
lazy_static! {
static ref COMMA: Regex = Regex::new(",").unwrap();
static ref ATEXT_ALPHANUMERIC:Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
static ref ATEXT_ALPHANUMERIC: Regex =
Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
}
use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddressParsedRXingResult};
use super::{
EmailAddressParsedRXingResult, EmailDoCoMoResultParser, ParsedClientResult, ResultParser,
};
/**
* Represents a result that encodes an e-mail address, either as a plain address
@@ -66,7 +69,11 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
let mut tos = if hostEmail.is_empty() {
Vec::new()
} else {
COMMA.split(hostEmail).into_iter().map(|s| s.to_owned()).collect()
COMMA
.split(hostEmail)
.into_iter()
.map(|s| s.to_owned())
.collect()
};
// if (!hostEmail.isEmpty()) {
// tos = COMMA.split(hostEmail);
@@ -80,20 +87,32 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
// if (nameValues != null) {
if tos.is_empty() {
if let Some(tosString) = nv.get("to") {
tos = COMMA.split(tosString).into_iter().map(|s| s.to_owned()).collect();
tos = COMMA
.split(tosString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if tosString != null {
// tos = COMMA.split(tosString);
// }
}
if let Some(ccString) = nv.get("cc") {
ccs = COMMA.split(ccString).into_iter().map(|s| s.to_owned()).collect();
ccs = COMMA
.split(ccString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if ccString != null {
// ccs = COMMA.split(ccString);
// }
if let Some(bccString) = nv.get("bcc") {
bccs = COMMA.split(bccString).into_iter().map(|s| s.to_owned()).collect();
bccs = COMMA
.split(bccString)
.into_iter()
.map(|s| s.to_owned())
.collect();
}
// if bccString != null {
// bccs = COMMA.split(bccString);
@@ -101,12 +120,22 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
subject = nv.get("subject").unwrap_or(&"".to_owned()).clone();
body = nv.get("body").unwrap_or(&"".to_owned()).clone();
}
return Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(tos, ccs, bccs, subject.to_owned(), body.to_owned())));
return Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(
tos,
ccs,
bccs,
subject.to_owned(),
body.to_owned(),
),
));
} else {
// let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) {
return None;
}
return Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::new(rawText)));
return Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::new(rawText),
));
}
}

View File

@@ -24,13 +24,13 @@ use regex::Regex;
use crate::RXingResult;
use super::{ParsedClientResult, ResultParser, EmailAddressParsedRXingResult};
use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser};
use lazy_static::lazy_static;
lazy_static! {
static ref ATEXT_ALPHANUMERIC :Regex = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
static ref ATEXT_ALPHANUMERIC: Regex =
Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
}
/**
@@ -41,7 +41,6 @@ lazy_static! {
* @author Sean Owen
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !rawText.starts_with("MATMSG:") {
return None;
@@ -53,9 +52,13 @@ lazy_static! {
return None;
}
}
let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false).unwrap_or_default();
let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false).unwrap_or_default();
Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body)))
let subject = ResultParser::match_single_do_co_mo_prefixed_field("SUB:", &rawText, false)
.unwrap_or_default();
let body = ResultParser::match_single_do_co_mo_prefixed_field("BODY:", &rawText, false)
.unwrap_or_default();
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(tos, Vec::new(), Vec::new(), subject, body),
))
}
/**

View File

@@ -29,7 +29,7 @@
// import java.util.Map;
// import java.util.Objects;
use std::{collections::HashMap};
use std::collections::HashMap;
use super::{ParsedRXingResult, ParsedRXingResultType};

View File

@@ -42,10 +42,7 @@
use std::collections::HashMap;
use crate::{
client::result::{ParsedClientResult},
RXingResult, BarcodeFormat,
};
use crate::{client::result::ParsedClientResult, BarcodeFormat, RXingResult};
use super::ExpandedProductResultParser;

View File

@@ -41,7 +41,6 @@ pub fn testGeo1() {
//doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1.0,2.0");
// I think 1.0 and 1 and 2.0 and 2 are similar enough here, correct me if i'm wrong.
doTest("geo:1,2", 1.0, 2.0, 0.0, "", "geo:1,2");
}
#[test]
pub fn testGeo2() {

View File

@@ -24,7 +24,6 @@ use super::ParsedRXingResult;
* @author jbreiden@google.com (Jeff Breidenbach)
*/
pub struct ISBNParsedRXingResult {
isbn: String,
}
impl ParsedRXingResult for ISBNParsedRXingResult {
@@ -38,7 +37,6 @@ pub struct ISBNParsedRXingResult {
}
impl ISBNParsedRXingResult {
pub fn new(isbn: String) -> Self {
Self { isbn }
}
@@ -46,5 +44,4 @@ pub struct ISBNParsedRXingResult {
pub fn getISBN(&self) -> &str {
&self.isbn
}
}

View File

@@ -21,7 +21,7 @@
use crate::BarcodeFormat;
use super::{ ResultParser, ISBNParsedRXingResult, ParsedClientResult};
use super::{ISBNParsedRXingResult, ParsedClientResult, ResultParser};
/**
* Parses strings of digits that represent a ISBN.
@@ -48,6 +48,8 @@ use super::{ ResultParser, ISBNParsedRXingResult, ParsedClientResult};
return None;
}
Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new(rawText)))
Some(ParsedClientResult::ISBNResult(ISBNParsedRXingResult::new(
rawText,
)))
}
// }

View File

@@ -24,7 +24,6 @@
*/
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum ParsedRXingResultType {
ADDRESSBOOK,
EMAIL_ADDRESS,
PRODUCT,
@@ -37,5 +36,4 @@ pub enum ParsedRXingResultType {
WIFI,
ISBN,
VIN,
}

View File

@@ -24,10 +24,8 @@ use super::{ParsedRXingResult, ParsedRXingResultType};
* @author dswitkin@google.com (Daniel Switkin)
*/
pub struct ProductParsedRXingResult {
product_id: String,
normalized_product_id: String,
}
impl ParsedRXingResult for ProductParsedRXingResult {
fn getType(&self) -> super::ParsedRXingResultType {
@@ -57,5 +55,4 @@ impl ProductParsedRXingResult {
pub fn getNormalizedProductID(&self) -> &str {
&self.normalized_product_id
}
}

View File

@@ -27,8 +27,10 @@
* @author Sean Owen
*/
// public final class ProductParsedRXingResultTestCase extends Assert {
use crate::{BarcodeFormat, RXingResult, client::result::{ParsedRXingResult, ParsedRXingResultType, ParsedClientResult}};
use crate::{
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};
use super::ResultParser;
@@ -51,7 +53,6 @@ use super::ResultParser;
} else {
panic!("Expected ParsedClientResult::ProductResult")
}
}
// }

View File

@@ -20,7 +20,7 @@
// import com.google.zxing.RXingResult;
// import com.google.zxing.oned.UPCEReader;
use crate::{RXingResult, BarcodeFormat};
use crate::{BarcodeFormat, RXingResult};
use super::{ParsedClientResult, ProductParsedRXingResult, ResultParser};
@@ -33,8 +33,11 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
let format = result.getBarcodeFormat();
if !(format == &BarcodeFormat::UPC_A || format == &BarcodeFormat::UPC_E ||
format == &BarcodeFormat::EAN_8 || format == &BarcodeFormat::EAN_13) {
if !(format == &BarcodeFormat::UPC_A
|| format == &BarcodeFormat::UPC_E
|| format == &BarcodeFormat::EAN_8
|| format == &BarcodeFormat::EAN_13)
{
return None;
}
let rawText = ResultParser::getMassagedText(result);
@@ -52,6 +55,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
normalizedProductID = rawText.clone();
}
Some(ParsedClientResult::ProductResult(ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID)))
Some(ParsedClientResult::ProductResult(
ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID),
))
}

View File

@@ -38,9 +38,10 @@ use crate::{exceptions::Exceptions, RXingResult};
use super::{
AddressBookAUResultParser, AddressBookDoCoMoResultParser, BizcardResultParser,
BookmarkDoCoMoResultParser, EmailAddressResultParser, EmailDoCoMoResultParser,
ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult, ProductResultParser, SMSMMSResultParser, SMTPResultParser, TelResultParser,
TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser,
VEventResultParser, VINResultParser, WifiResultParser, SMSTOMMSTOResultParser,
ExpandedProductResultParser, GeoResultParser, ISBNResultParser, ParsedClientResult,
ProductResultParser, SMSMMSResultParser, SMSTOMMSTOResultParser, SMTPResultParser,
TelResultParser, TextParsedRXingResult, URIResultParser, URLTOResultParser, VCardResultParser,
VEventResultParser, VINResultParser, WifiResultParser,
};
/**

View File

@@ -84,11 +84,7 @@ fn do_test(contents: &str, number: &str, subject: &str, body: &str, via: &str, p
assert_eq!(&vec![number], smsRXingResult.getNumbers());
assert_eq!(subject, smsRXingResult.getSubject());
assert_eq!(body, smsRXingResult.getBody());
let vec_via = if via.is_empty() {
vec![]
}else {
vec![via]
};
let vec_via = if via.is_empty() { vec![] } else { vec![via] };
assert_eq!(&vec_via, smsRXingResult.getVias());
assert_eq!(parsedURI, smsRXingResult.getSMSURI());
} else {

View File

@@ -95,7 +95,11 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
add_number_via(
&mut numbers,
&mut vias,
&sms_uriwithout_query[(if last_comma > 0 { last_comma + 1} else {last_comma}) as usize..],
&sms_uriwithout_query[(if last_comma > 0 {
last_comma + 1
} else {
last_comma
}) as usize..],
);
Some(ParsedClientResult::SMSResult(
@@ -110,7 +114,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
fn add_number_via(numbers: &mut Vec<String>, vias: &mut Vec<String>, number_part: &str) {
if number_part.is_empty() {
return
return;
}
if let Some(number_end) = number_part.find(';') {
// if numberEnd < 0 {

View File

@@ -34,8 +34,11 @@ use super::{ParsedClientResult, ResultParser, SMSParsedRXingResult};
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !(rawText.starts_with("smsto:") || rawText.starts_with("SMSTO:") ||
rawText.starts_with("mmsto:") || rawText.starts_with("MMSTO:")) {
if !(rawText.starts_with("smsto:")
|| rawText.starts_with("SMSTO:")
|| rawText.starts_with("mmsto:")
|| rawText.starts_with("MMSTO:"))
{
return None;
}
// Thanks to dominik.wild for suggesting this enhancement to support
@@ -51,6 +54,13 @@ use super::{ParsedClientResult, ResultParser, SMSParsedRXingResult};
// body = number.substring(bodyStart + 1);
// number = number.substring(0, bodyStart);
// }
Some(ParsedClientResult::SMSResult(SMSParsedRXingResult::with_singles(number.to_owned(), String::from(""), String::from(""), body.to_owned())))
Some(ParsedClientResult::SMSResult(
SMSParsedRXingResult::with_singles(
number.to_owned(),
String::from(""),
String::from(""),
body.to_owned(),
),
))
// return new SMSParsedRXingResult(number, null, null, body);
}

View File

@@ -20,7 +20,7 @@
use crate::RXingResult;
use super::{ResultParser, ParsedClientResult, EmailAddressParsedRXingResult};
use super::{EmailAddressParsedRXingResult, ParsedClientResult, ResultParser};
/**
* <p>Parses an "smtp:" URI result, whose format is not standardized but appears to be like:
@@ -54,7 +54,15 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// subject = subject.substring(0, colon);
// }
// }
Some(ParsedClientResult::EmailResult(EmailAddressParsedRXingResult::with_details(vec![emailAddress.to_owned()],Vec::new(), Vec::new(), subject.to_owned(), body.to_owned())))
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(
vec![emailAddress.to_owned()],
Vec::new(),
Vec::new(),
subject.to_owned(),
body.to_owned(),
),
))
// return new EmailAddressParsedRXingResult(new String[] {emailAddress},
// null,
// null,

View File

@@ -27,12 +27,8 @@
* @author Sean Owen
*/
// public final class TelParsedRXingResultTestCase extends Assert {
use crate::{
client::result::{
ParsedClientResult, ParsedRXingResult, ParsedRXingResultType,
},
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};

View File

@@ -18,7 +18,7 @@
// import com.google.zxing.RXingResult;
use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
use super::{ParsedClientResult, ResultParser, TelParsedRXingResult};
/**
* Parses a "tel:" URI result, which specifies a phone number.
@@ -35,7 +35,11 @@ use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
return None;
}
// Normalize "TEL:" to "tel:"
let telURI = if rawText.starts_with("TEL:") {format!("tel:{}", &rawText[4..])} else {rawText.clone()};
let telURI = if rawText.starts_with("TEL:") {
format!("tel:{}", &rawText[4..])
} else {
rawText.clone()
};
// Drop tel, query portion
let queryStart = rawText[4..].find('?');
let number = if let Some(v) = queryStart {
@@ -44,6 +48,10 @@ use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
&rawText[4..]
};
// let number = queryStart < 0 ? : ;
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(number.to_owned(), telURI.to_owned(), "".to_owned())))
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(
number.to_owned(),
telURI.to_owned(),
"".to_owned(),
)))
}
// }

View File

@@ -43,7 +43,7 @@ impl URIParsedRXingResult {
pub fn new(uri: String, title: String) -> Self {
Self {
uri: Self::massage_uri(&uri),
title
title,
}
}

View File

@@ -21,6 +21,7 @@
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
use lazy_static::lazy_static;
/**
* Tries to parse results that are a URI of some kind.
*
@@ -28,17 +29,19 @@
*/
// public final class URIRXingResultParser extends RXingResultParser {
use regex::Regex;
use lazy_static::lazy_static;
use crate::RXingResult;
use super::{ParsedClientResult, ResultParser, URIParsedRXingResult};
lazy_static! {
static ref ALLOWED_URI_CHARS :Regex = Regex::new( ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile");
static ref USER_IN_HOST :Regex = Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile");
static ref ALLOWED_URI_CHARS: Regex =
Regex::new(ALLOWED_URI_CHARS_PATTERN).expect("Regex patterns should always copile");
static ref USER_IN_HOST: Regex =
Regex::new(":/*([^/@]+)@[^/]+").expect("Regex patterns should always copile");
static ref URL_WITH_PROTOCOL_PATTERN: Regex = Regex::new("[a-zA-Z][a-zA-Z0-9+-.]+:").unwrap();
static ref URL_WITHOUT_PROTOCOL_PATTERN :Regex = Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap();
static ref URL_WITHOUT_PROTOCOL_PATTERN: Regex =
Regex::new("([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}(:\\d{1,5})?(/|\\?|$)").unwrap();
}
const ALLOWED_URI_CHARS_PATTERN: &'static str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+";
@@ -79,7 +82,6 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
* to connect to yourbank.com at first glance.
*/
pub fn is_possibly_malicious_uri(uri: &str) -> bool {
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) {
if fnd.start() == 0 && fnd.end() == uri.len() {
true

View File

@@ -47,7 +47,8 @@ lazy_static! {
static ref NEWLINE_ESCAPE: Regex = Regex::new("\\\\[nN]").unwrap();
static ref VCARD_ESCAPE: Regex = Regex::new("\\\\([,;\\\\])").unwrap();
static ref EQUALS: Regex = Regex::new("=").unwrap();
static ref UNESCAPED_SEMICOLONS : fancy_regex::Regex = fancy_regex::Regex::new("(?<!\\\\);+").unwrap();
static ref UNESCAPED_SEMICOLONS: fancy_regex::Regex =
fancy_regex::Regex::new("(?<!\\\\);+").unwrap();
static ref SEMICOLON_OR_COMMA: Regex = Regex::new("[;,]").unwrap();
}
@@ -293,7 +294,10 @@ pub fn matchVCardPrefixedField(
.replace_all(&element, "")
.to_mut()
.to_owned();
element = NEWLINE_ESCAPE.replace_all(&element, "\n").to_mut().to_owned();
element = NEWLINE_ESCAPE
.replace_all(&element, "\n")
.to_mut()
.to_owned();
element = VCARD_ESCAPE.replace_all(&element, "$1").to_mut().to_owned();
// element = CR_LF_SPACE_TAB.matcher(element).replaceAll("");
// element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n");

View File

@@ -27,8 +27,10 @@
* @author Vikram Aggarwal
*/
// public final class WifiParsedRXingResultTestCase extends Assert {
use crate::{RXingResult, BarcodeFormat, client::result::{ParsedRXingResultType, ParsedRXingResult, ParsedClientResult}};
use crate::{
client::result::{ParsedClientResult, ParsedRXingResult, ParsedRXingResultType},
BarcodeFormat, RXingResult,
};
use super::ResultParser;
@@ -40,15 +42,40 @@ use super::ResultParser;
#[test]
fn testWep() {
doTest("WIFI:S:TenChars;P:0123456789;T:WEP;;", "TenChars", "0123456789", "WEP");
doTest("WIFI:S:TenChars;P:abcde56789;T:WEP;;", "TenChars", "abcde56789", "WEP");
doTest(
"WIFI:S:TenChars;P:0123456789;T:WEP;;",
"TenChars",
"0123456789",
"WEP",
);
doTest(
"WIFI:S:TenChars;P:abcde56789;T:WEP;;",
"TenChars",
"abcde56789",
"WEP",
);
// Non hex should not fail at this level
doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP");
doTest(
"WIFI:S:TenChars;P:hellothere;T:WEP;;",
"TenChars",
"hellothere",
"WEP",
);
// Escaped semicolons
doTest("WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;", "Ten;;Chars", "0123456789", "WEP");
doTest(
"WIFI:S:Ten\\;\\;Chars;P:0123456789;T:WEP;;",
"Ten;;Chars",
"0123456789",
"WEP",
);
// Escaped colons
doTest("WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;", "Ten::Chars", "0123456789", "WEP");
doTest(
"WIFI:S:Ten\\:\\:Chars;P:0123456789;T:WEP;;",
"Ten::Chars",
"0123456789",
"WEP",
);
// TODO(vikrama) Need a test for SB as well.
}
@@ -59,31 +86,69 @@ use super::ResultParser;
#[test]
fn testWpa() {
doTest("WIFI:S:TenChars;P:wow;T:WPA;;", "TenChars", "wow", "WPA");
doTest("WIFI:S:TenChars;P:space is silent;T:WPA;;", "TenChars", "space is silent", "WPA");
doTest("WIFI:S:TenChars;P:hellothere;T:WEP;;", "TenChars", "hellothere", "WEP");
doTest(
"WIFI:S:TenChars;P:space is silent;T:WPA;;",
"TenChars",
"space is silent",
"WPA",
);
doTest(
"WIFI:S:TenChars;P:hellothere;T:WEP;;",
"TenChars",
"hellothere",
"WEP",
);
// Escaped semicolons
doTest("WIFI:S:TenChars;P:hello\\;there;T:WEP;;", "TenChars", "hello;there", "WEP");
doTest(
"WIFI:S:TenChars;P:hello\\;there;T:WEP;;",
"TenChars",
"hello;there",
"WEP",
);
// Escaped colons
doTest("WIFI:S:TenChars;P:hello\\:there;T:WEP;;", "TenChars", "hello:there", "WEP");
doTest(
"WIFI:S:TenChars;P:hello\\:there;T:WEP;;",
"TenChars",
"hello:there",
"WEP",
);
}
#[test]
fn testEscape() {
doTest("WIFI:T:WPA;S:test;P:my_password\\\\;;", "test", "my_password\\", "WPA");
doTest("WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;", "My_WiFi_SSID", "abc123/", "WPA");
doTest("WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;", "\"foo;bar\\baz\"", "", "WPA");
doTest("WIFI:T:WPA;S:test;P:\\\"abcd\\\";;", "test", "\"abcd\"", "WPA");
doTest(
"WIFI:T:WPA;S:test;P:my_password\\\\;;",
"test",
"my_password\\",
"WPA",
);
doTest(
"WIFI:T:WPA;S:My_WiFi_SSID;P:abc123/;;",
"My_WiFi_SSID",
"abc123/",
"WPA",
);
doTest(
"WIFI:T:WPA;S:\"foo\\;bar\\\\baz\";;",
"\"foo;bar\\baz\"",
"",
"WPA",
);
doTest(
"WIFI:T:WPA;S:test;P:\\\"abcd\\\";;",
"test",
"\"abcd\"",
"WPA",
);
}
/**
* Given the string contents for the barcode, check that it matches our expectations
*/
fn doTest( contents:&str,
ssid:&str,
password:&str,
n_type:&str) {
let fakeRXingResult = RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE);
fn doTest(contents: &str, ssid: &str, password: &str, n_type: &str) {
let fakeRXingResult =
RXingResult::new(contents, Vec::new(), Vec::new(), BarcodeFormat::QR_CODE);
let result = ResultParser::parseRXingResult(&fakeRXingResult);
// Ensure it is a wifi code

View File

@@ -18,9 +18,9 @@
// import com.google.zxing.RXingResult;
use crate::client::result::{WifiParsedRXingResult, ParsedClientResult};
use crate::client::result::{ParsedClientResult, WifiParsedRXingResult};
use super::{ResultParser};
use super::ResultParser;
// @SuppressWarnings("checkstyle:lineLength")
/**
@@ -51,12 +51,15 @@ use super::{ResultParser};
return None;
}
let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned();
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false).unwrap_or(String::from(""));
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false)
.unwrap_or(String::from(""));
if ssid.is_empty() {
return None;
}
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false).unwrap_or(String::from(""));
let n_type = if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false){
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false)
.unwrap_or(String::from(""));
let n_type =
if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) {
nt
} else {
String::from("nopass")
@@ -67,7 +70,9 @@ use super::{ResultParser};
// is 'true' or 'false':
let mut hidden = false;
let mut phase2Method = ResultParser::matchSinglePrefixedField("PH2:", &rawText, ';', false);
let hValue = if let Some(hv) = ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false){
let hValue = if let Some(hv) =
ResultParser::matchSinglePrefixedField("H:", &rawText, ';', false)
{
// If PH2 was specified separately, or if the value is clearly boolean, interpret it as 'hidden'
if phase2Method.is_some() || "true" == hv.to_lowercase() || "false" == hv.to_lowercase() {
hidden = hv.parse().unwrap(); //Boolean.parseBoolean(hValue);
@@ -79,10 +84,24 @@ use super::{ResultParser};
String::from("")
};
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false).unwrap_or(String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false).unwrap_or(String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false).unwrap_or(String::from(""));
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false)
.unwrap_or(String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false)
.unwrap_or(String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false)
.unwrap_or(String::from(""));
Some(ParsedClientResult::WiFiResult(WifiParsedRXingResult::with_details(n_type, ssid, pass, hidden, identity, anonymousIdentity, eapMethod, phase2Method.unwrap_or(String::from("")))))
Some(ParsedClientResult::WiFiResult(
WifiParsedRXingResult::with_details(
n_type,
ssid,
pass,
hidden,
identity,
anonymousIdentity,
eapMethod,
phase2Method.unwrap_or(String::from("")),
),
))
}
// }

View File

@@ -1,48 +1,48 @@
mod ParsedResult;
mod ResultParser;
mod TelParsedResult;
mod TextParsedResult;
mod ParsedResultType;
mod TelResultParser;
mod ISBNParsedResult;
mod ISBNResultParser;
mod WifiParsedResult;
mod WifiResultParser;
mod GeoResultParser;
mod GeoParsedResult;
mod SMSParsedResult;
mod SMSMMSResultParser;
mod ProductParsedResult;
mod ProductResultParser;
mod URIParsedResult;
mod URIResultParser;
mod URLTOResultParser;
mod AbstractDoCoMoResultParser;
mod AddressBookAUResultParser;
mod AddressBookDoCoMoResultParser;
mod AddressBookParsedResult;
mod BizcardResultParser;
mod BookmarkDoCoMoResultParser;
mod SMSTOMMSTOResultParser;
mod CalendarParsedResult;
mod EmailAddressParsedResult;
mod EmailAddressResultParser;
mod EmailDoCoMoResultParser;
mod SMTPResultParser;
mod VINParsedResult;
mod VINResultParser;
mod AddressBookParsedResult;
mod AddressBookDoCoMoResultParser;
mod AddressBookAUResultParser;
mod VCardResultParser;
mod BizcardResultParser;
mod CalendarParsedResult;
mod VEventResultParser;
mod ExpandedProductParsedResult;
mod ExpandedProductResultParser;
mod GeoParsedResult;
mod GeoResultParser;
mod ISBNParsedResult;
mod ISBNResultParser;
mod ParsedResult;
mod ParsedResultType;
mod ProductParsedResult;
mod ProductResultParser;
mod ResultParser;
mod SMSMMSResultParser;
mod SMSParsedResult;
mod SMSTOMMSTOResultParser;
mod SMTPResultParser;
mod TelParsedResult;
mod TelResultParser;
mod TextParsedResult;
mod URIParsedResult;
mod URIResultParser;
mod URLTOResultParser;
mod VCardResultParser;
mod VEventResultParser;
mod VINParsedResult;
mod VINResultParser;
mod WifiParsedResult;
mod WifiResultParser;
use std::fmt;
pub use ParsedResult::*;
pub use ParsedResultType::*;
pub use ResultParser::*;
pub use TelParsedResult::*;
pub use TextParsedResult::*;
pub use ParsedResult::*;
// pub use TelResultParser::*;
pub use ISBNParsedResult::*;
// pub use ISBNResultParser::*;
@@ -50,42 +50,42 @@ pub use WifiParsedResult::*;
// pub use WifiResultParser::*;
pub use GeoParsedResult::*;
// pub use GeoResultParser::*;
pub use SMSParsedResult::*;
pub use ProductParsedResult::*;
pub use URIParsedResult::*;
pub use EmailAddressParsedResult::*;
pub use VINParsedResult::*;
pub use AddressBookParsedResult::*;
pub use CalendarParsedResult::*;
pub use CalendarParsedResult::*;
pub use EmailAddressParsedResult::*;
pub use ExpandedProductParsedResult::*;
pub use ProductParsedResult::*;
pub use SMSParsedResult::*;
pub use URIParsedResult::*;
pub use VINParsedResult::*;
#[cfg(test)]
mod TelParsedResultTestCase;
#[cfg(test)]
mod ISBNParsedResultTestCase;
#[cfg(test)]
mod WifiParsedResultTestCase;
#[cfg(test)]
mod GeoParsedResultTestCase;
#[cfg(test)]
mod SMSMMSParsedResultTestCase;
#[cfg(test)]
mod ProductParsedResultTestCase;
#[cfg(test)]
mod URIParsedResultTestCase;
#[cfg(test)]
mod EmailAddressParsedResultTestCase;
#[cfg(test)]
mod VINParsedResultTestCase;
#[cfg(test)]
mod AddressBookParsedResultTestCase;
#[cfg(test)]
mod CalendarParsedResultTestCase;
#[cfg(test)]
mod EmailAddressParsedResultTestCase;
#[cfg(test)]
mod ExpandedProductParsedResultTestCase;
#[cfg(test)]
mod GeoParsedResultTestCase;
#[cfg(test)]
mod ISBNParsedResultTestCase;
#[cfg(test)]
mod ParsedReaderResultTestCase;
#[cfg(test)]
mod ProductParsedResultTestCase;
#[cfg(test)]
mod SMSMMSParsedResultTestCase;
#[cfg(test)]
mod TelParsedResultTestCase;
#[cfg(test)]
mod URIParsedResultTestCase;
#[cfg(test)]
mod VINParsedResultTestCase;
#[cfg(test)]
mod WifiParsedResultTestCase;
pub enum ParsedClientResult {
TextResult(TextParsedRXingResult),

View File

@@ -133,7 +133,6 @@ use rand::Rng;
}
}
#[test]
fn test_set_bulk() {
let mut array = BitArray::with_size(64);
@@ -242,7 +241,11 @@ use rand::Rng;
let mut newBitArray = BitArray::with_initial_values(oldBits.clone(), size);
newBitArray.reverse();
let newBitsNew = newBitArray.getBitArray();
assert!(arrays_are_equal(&newBitsOriginal, &newBitsNew, size / 32 + 1));
assert!(arrays_are_equal(
&newBitsOriginal,
&newBitsNew,
size / 32 + 1
));
}
}

View File

@@ -222,21 +222,44 @@ use super::BitMatrix;
centerMatrix.setRegion(1, 1, 1, 1).expect("must set");
let emptyMatrix24 = BitMatrix::new(2, 4).unwrap();
assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \n \n", "x", " ").unwrap());
assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \r\r\n \n\r", "x", " ").unwrap());
assert_eq!(emptyMatrix, BitMatrix::parse_strings(" \n \n ", "x", " ").unwrap());
assert_eq!(
emptyMatrix,
BitMatrix::parse_strings(" \n \n \n", "x", " ").unwrap()
);
assert_eq!(
emptyMatrix,
BitMatrix::parse_strings(" \n \r\r\n \n\r", "x", " ").unwrap()
);
assert_eq!(
emptyMatrix,
BitMatrix::parse_strings(" \n \n ", "x", " ").unwrap()
);
assert_eq!(fullMatrix, BitMatrix::parse_strings("xxx\nxxx\nxxx\n", "x", " ").unwrap());
assert_eq!(
fullMatrix,
BitMatrix::parse_strings("xxx\nxxx\nxxx\n", "x", " ").unwrap()
);
assert_eq!(centerMatrix, BitMatrix::parse_strings(" \n x \n \n", "x", " ").unwrap());
assert_eq!(centerMatrix, BitMatrix::parse_strings(" \n x \n \n", "x ", " ").unwrap());
assert_eq!(
centerMatrix,
BitMatrix::parse_strings(" \n x \n \n", "x", " ").unwrap()
);
assert_eq!(
centerMatrix,
BitMatrix::parse_strings(" \n x \n \n", "x ", " ").unwrap()
);
assert!(BitMatrix::parse_strings(" \n xy\n \n", "x", " ").is_err());
assert_eq!(
emptyMatrix24,
BitMatrix::parse_strings(" \n \n \n \n", "x", " ").unwrap()
);
assert_eq!(emptyMatrix24, BitMatrix::parse_strings(" \n \n \n \n", "x", " ").unwrap());
assert_eq!(centerMatrix, BitMatrix::parse_strings(&centerMatrix.toString("x", "."), "x", ".").unwrap());
assert_eq!(
centerMatrix,
BitMatrix::parse_strings(&centerMatrix.toString("x", "."), "x", ".").unwrap()
);
}
#[test]
@@ -351,7 +374,10 @@ use super::BitMatrix;
let mut i = 0;
while i < BIT_MATRIX_POINTS.len() {
// for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) {
result.set(width - 1 - BIT_MATRIX_POINTS[i], height - 1 - BIT_MATRIX_POINTS[i + 1]);
result.set(
width - 1 - BIT_MATRIX_POINTS[i],
height - 1 - BIT_MATRIX_POINTS[i + 1],
);
i += 2;
}
return result;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*
@@ -19,7 +18,7 @@
// import java.util.Arrays;
use std::{fmt, cmp};
use std::{cmp, fmt};
use crate::Exceptions;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2008 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2008 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*
@@ -21,7 +20,7 @@
use crate::Exceptions;
use super::{BitMatrix, PerspectiveTransform, GridSampler};
use super::{BitMatrix, GridSampler, PerspectiveTransform};
/**
* @author Sean Owen

View File

@@ -16,7 +16,7 @@
//package com.google.zxing.common.detector;
use crate::{Exceptions, RXingResultPoint, common::BitMatrix, ResultPoint};
use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint};
/**
* <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image.
@@ -34,7 +34,9 @@ pub struct MonochromeRectangleDetector {
impl MonochromeRectangleDetector {
pub fn new(image: &BitMatrix) -> Self {
Self { image: image.clone() }
Self {
image: image.clone(),
}
}
/**
@@ -179,15 +181,9 @@ impl MonochromeRectangleDetector {
lastY as f32,
));
}
return Ok(RXingResultPoint::new(
lastRange[0] as f32,
lastY as f32,
));
return Ok(RXingResultPoint::new(lastRange[0] as f32, lastY as f32));
} else {
return Ok(RXingResultPoint::new(
lastRange[1] as f32,
lastY as f32,
));
return Ok(RXingResultPoint::new(lastRange[1] as f32, lastY as f32));
}
} else {
let lastX = x - deltaX;
@@ -198,18 +194,13 @@ impl MonochromeRectangleDetector {
lastRange[if deltaX < 0 { 0 } else { 1 }] as f32,
));
}
return Ok(RXingResultPoint::new(
lastX as f32,
lastRange[0] as f32,
));
return Ok(RXingResultPoint::new(lastX as f32, lastRange[0] as f32));
} else {
return Ok(RXingResultPoint::new(
lastX as f32,
lastRange[1] as f32,
));
return Ok(RXingResultPoint::new(lastX as f32, lastRange[1] as f32));
}
}
}}else {
}
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
}
lastRange_z = range;

View File

@@ -16,7 +16,7 @@
//package com.google.zxing.common.detector;
use crate::{RXingResultPoint, Exceptions, common::BitMatrix, ResultPoint};
use crate::{common::BitMatrix, Exceptions, RXingResultPoint, ResultPoint};
use super::MathUtils;
@@ -59,13 +59,7 @@ impl WhiteRectangleDetector {
* @param y y position of search center
* @throws NotFoundException if image is too small to accommodate {@code initSize}
*/
pub fn new(
image: &BitMatrix,
initSize: i32,
x: i32,
y: i32,
) -> Result<Self, Exceptions> {
pub fn new(image: &BitMatrix, initSize: i32, x: i32, y: i32) -> Result<Self, Exceptions> {
let halfsize = initSize / 2;
let leftInit = x - halfsize;
@@ -126,7 +120,9 @@ impl WhiteRectangleDetector {
// . |
// .....
let mut right_border_not_white = true;
while (right_border_not_white || !at_least_one_black_point_found_on_right) && right < self.width {
while (right_border_not_white || !at_least_one_black_point_found_on_right)
&& right < self.width
{
right_border_not_white = self.contains_black_point(up, down, right, false);
if right_border_not_white {
right += 1;
@@ -146,7 +142,8 @@ impl WhiteRectangleDetector {
// . .
// .___.
let mut bottom_border_not_white = true;
while (bottom_border_not_white || !at_least_one_black_point_found_on_bottom) && down < self.height
while (bottom_border_not_white || !at_least_one_black_point_found_on_bottom)
&& down < self.height
{
bottom_border_not_white = self.contains_black_point(left, right, down, true);
if bottom_border_not_white {

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2021 ZXing authors
*
@@ -24,7 +23,7 @@
// import java.util.ArrayList;
// import java.util.List;
use encoding::{EncodingRef, Encoding};
use encoding::{Encoding, EncodingRef};
use unicode_segmentation::UnicodeSegmentation;
use super::CharacterSetECI;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2021 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2022 ZXing authors
*
@@ -24,7 +23,7 @@
use std::fmt;
use encoding::{EncodingRef, Encoding};
use encoding::{Encoding, EncodingRef};
use crate::Exceptions;
@@ -81,7 +80,11 @@ impl ECIStringBuilder {
* @param value string to append
*/
pub fn append_string(&mut self, value: &str) {
value.as_bytes().iter().map(|b| self.current_bytes.push(*b)).count();
value
.as_bytes()
.iter()
.map(|b| self.current_bytes.push(*b))
.count();
// self.current_bytes.push(value.as_bytes());
}

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2009 ZXing authors
*
@@ -21,9 +20,9 @@
// import com.google.zxing.LuminanceSource;
// import com.google.zxing.NotFoundException;
use crate::{Exceptions, LuminanceSource, Binarizer};
use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{BitMatrix, BitArray};
use super::{BitArray, BitMatrix};
/**
* This Binarizer implementation uses the old ZXing global histogram approach. It is suitable

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -20,9 +20,9 @@
// import com.google.zxing.LuminanceSource;
// import com.google.zxing.NotFoundException;
use crate::{LuminanceSource, Binarizer, Exceptions};
use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{GlobalHistogramBinarizer, BitMatrix, BitArray};
use super::{BitArray, BitMatrix, GlobalHistogramBinarizer};
/**
* This class implements a local thresholding algorithm, which while slower than the

View File

@@ -20,7 +20,7 @@
// import java.util.ArrayList;
// import java.util.List;
use std::{rc::Rc, fmt};
use std::{fmt, rc::Rc};
use encoding::EncodingRef;
use unicode_segmentation::UnicodeSegmentation;

View File

@@ -18,7 +18,6 @@ mod BitSourceTestCase;
#[cfg(test)]
mod PerspectiveTransformTestCase;
mod string_utils;
pub use string_utils::*;
@@ -99,7 +98,6 @@ pub use eci_encoder_set::*;
mod minimal_eci_input;
pub use minimal_eci_input::*;
mod global_histogram_binarizer;
pub use global_histogram_binarizer::*;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -2,7 +2,7 @@ use std::fmt;
use crate::Exceptions;
use super::{GenericGFRef, GenericGFPoly};
use super::{GenericGFPoly, GenericGFRef};
/**
* <p>This class contains utility methods for performing mathematical operations over

View File

@@ -20,7 +20,7 @@ use std::fmt;
use crate::Exceptions;
use super::{GenericGFRef, GenericGF};
use super::{GenericGF, GenericGFRef};
/**
* <p>Represents a polynomial whose coefficients are elements of a GF.

View File

@@ -18,7 +18,7 @@
use crate::Exceptions;
use super::{GenericGFRef, GenericGFPoly, GenericGF};
use super::{GenericGF, GenericGFPoly, GenericGFRef};
/**
* <p>Implements Reed-Solomon decoding, as the name implies.</p>

View File

@@ -20,9 +20,9 @@
// import java.nio.charset.StandardCharsets;
// import java.util.Map;
use encoding::{EncodingRef, Encoding};
use encoding::{Encoding, EncodingRef};
use crate::{DecodingHintDictionary, DecodeHintType, DecodeHintValue};
use crate::{DecodeHintType, DecodeHintValue, DecodingHintDictionary};
use lazy_static::lazy_static;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2007 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2012 ZXing authors
*

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2008 ZXing authors
*

View File

@@ -18,7 +18,6 @@ mod buffered_image_luminance_source;
#[cfg(feature = "image")]
pub use buffered_image_luminance_source::*;
#[cfg(test)]
mod PlanarYUVLuminanceSourceTestCase;

View File

@@ -1,4 +1,3 @@
/*
* Copyright 2009 ZXing authors
*

View File

@@ -17,39 +17,138 @@
use crate::common::BitMatrix;
const BITNR: [[i16; 30]; 33] = [
[121,120,127,126,133,132,139,138,145,144,151,150,157,156,163,162,169,168,175,174,181,180,187,186,193,192,199,198, -2, -2],
[123,122,129,128,135,134,141,140,147,146,153,152,159,158,165,164,171,170,177,176,183,182,189,188,195,194,201,200,816, -3],
[125,124,131,130,137,136,143,142,149,148,155,154,161,160,167,166,173,172,179,178,185,184,191,190,197,196,203,202,818,817],
[283,282,277,276,271,270,265,264,259,258,253,252,247,246,241,240,235,234,229,228,223,222,217,216,211,210,205,204,819, -3],
[285,284,279,278,273,272,267,266,261,260,255,254,249,248,243,242,237,236,231,230,225,224,219,218,213,212,207,206,821,820],
[287,286,281,280,275,274,269,268,263,262,257,256,251,250,245,244,239,238,233,232,227,226,221,220,215,214,209,208,822, -3],
[289,288,295,294,301,300,307,306,313,312,319,318,325,324,331,330,337,336,343,342,349,348,355,354,361,360,367,366,824,823],
[291,290,297,296,303,302,309,308,315,314,321,320,327,326,333,332,339,338,345,344,351,350,357,356,363,362,369,368,825, -3],
[293,292,299,298,305,304,311,310,317,316,323,322,329,328,335,334,341,340,347,346,353,352,359,358,365,364,371,370,827,826],
[409,408,403,402,397,396,391,390, 79, 78, -2, -2, 13, 12, 37, 36, 2, -1, 44, 43,109,108,385,384,379,378,373,372,828, -3],
[411,410,405,404,399,398,393,392, 81, 80, 40, -2, 15, 14, 39, 38, 3, -1, -1, 45,111,110,387,386,381,380,375,374,830,829],
[413,412,407,406,401,400,395,394, 83, 82, 41, -3, -3, -3, -3, -3, 5, 4, 47, 46,113,112,389,388,383,382,377,376,831, -3],
[415,414,421,420,427,426,103,102, 55, 54, 16, -3, -3, -3, -3, -3, -3, -3, 20, 19, 85, 84,433,432,439,438,445,444,833,832],
[417,416,423,422,429,428,105,104, 57, 56, -3, -3, -3, -3, -3, -3, -3, -3, 22, 21, 87, 86,435,434,441,440,447,446,834, -3],
[419,418,425,424,431,430,107,106, 59, 58, -3, -3, -3, -3, -3, -3, -3, -3, -3, 23, 89, 88,437,436,443,442,449,448,836,835],
[481,480,475,474,469,468, 48, -2, 30, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0, 53, 52,463,462,457,456,451,450,837, -3],
[483,482,477,476,471,470, 49, -1, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2, -1,465,464,459,458,453,452,839,838],
[485,484,479,478,473,472, 51, 50, 31, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 1, -2, 42,467,466,461,460,455,454,840, -3],
[487,486,493,492,499,498, 97, 96, 61, 60, -3, -3, -3, -3, -3, -3, -3, -3, -3, 26, 91, 90,505,504,511,510,517,516,842,841],
[489,488,495,494,501,500, 99, 98, 63, 62, -3, -3, -3, -3, -3, -3, -3, -3, 28, 27, 93, 92,507,506,513,512,519,518,843, -3],
[491,490,497,496,503,502,101,100, 65, 64, 17, -3, -3, -3, -3, -3, -3, -3, 18, 29, 95, 94,509,508,515,514,521,520,845,844],
[559,558,553,552,547,546,541,540, 73, 72, 32, -3, -3, -3, -3, -3, -3, 10, 67, 66,115,114,535,534,529,528,523,522,846, -3],
[561,560,555,554,549,548,543,542, 75, 74, -2, -1, 7, 6, 35, 34, 11, -2, 69, 68,117,116,537,536,531,530,525,524,848,847],
[563,562,557,556,551,550,545,544, 77, 76, -2, 33, 9, 8, 25, 24, -1, -2, 71, 70,119,118,539,538,533,532,527,526,849, -3],
[565,564,571,570,577,576,583,582,589,588,595,594,601,600,607,606,613,612,619,618,625,624,631,630,637,636,643,642,851,850],
[567,566,573,572,579,578,585,584,591,590,597,596,603,602,609,608,615,614,621,620,627,626,633,632,639,638,645,644,852, -3],
[569,568,575,574,581,580,587,586,593,592,599,598,605,604,611,610,617,616,623,622,629,628,635,634,641,640,647,646,854,853],
[727,726,721,720,715,714,709,708,703,702,697,696,691,690,685,684,679,678,673,672,667,666,661,660,655,654,649,648,855, -3],
[729,728,723,722,717,716,711,710,705,704,699,698,693,692,687,686,681,680,675,674,669,668,663,662,657,656,651,650,857,856],
[731,730,725,724,719,718,713,712,707,706,701,700,695,694,689,688,683,682,677,676,671,670,665,664,659,658,653,652,858, -3],
[733,732,739,738,745,744,751,750,757,756,763,762,769,768,775,774,781,780,787,786,793,792,799,798,805,804,811,810,860,859],
[735,734,741,740,747,746,753,752,759,758,765,764,771,770,777,776,783,782,789,788,795,794,801,800,807,806,813,812,861, -3],
[737,736,743,742,749,748,755,754,761,760,767,766,773,772,779,778,785,784,791,790,797,796,803,802,809,808,815,814,863,862]
[
121, 120, 127, 126, 133, 132, 139, 138, 145, 144, 151, 150, 157, 156, 163, 162, 169, 168,
175, 174, 181, 180, 187, 186, 193, 192, 199, 198, -2, -2,
],
[
123, 122, 129, 128, 135, 134, 141, 140, 147, 146, 153, 152, 159, 158, 165, 164, 171, 170,
177, 176, 183, 182, 189, 188, 195, 194, 201, 200, 816, -3,
],
[
125, 124, 131, 130, 137, 136, 143, 142, 149, 148, 155, 154, 161, 160, 167, 166, 173, 172,
179, 178, 185, 184, 191, 190, 197, 196, 203, 202, 818, 817,
],
[
283, 282, 277, 276, 271, 270, 265, 264, 259, 258, 253, 252, 247, 246, 241, 240, 235, 234,
229, 228, 223, 222, 217, 216, 211, 210, 205, 204, 819, -3,
],
[
285, 284, 279, 278, 273, 272, 267, 266, 261, 260, 255, 254, 249, 248, 243, 242, 237, 236,
231, 230, 225, 224, 219, 218, 213, 212, 207, 206, 821, 820,
],
[
287, 286, 281, 280, 275, 274, 269, 268, 263, 262, 257, 256, 251, 250, 245, 244, 239, 238,
233, 232, 227, 226, 221, 220, 215, 214, 209, 208, 822, -3,
],
[
289, 288, 295, 294, 301, 300, 307, 306, 313, 312, 319, 318, 325, 324, 331, 330, 337, 336,
343, 342, 349, 348, 355, 354, 361, 360, 367, 366, 824, 823,
],
[
291, 290, 297, 296, 303, 302, 309, 308, 315, 314, 321, 320, 327, 326, 333, 332, 339, 338,
345, 344, 351, 350, 357, 356, 363, 362, 369, 368, 825, -3,
],
[
293, 292, 299, 298, 305, 304, 311, 310, 317, 316, 323, 322, 329, 328, 335, 334, 341, 340,
347, 346, 353, 352, 359, 358, 365, 364, 371, 370, 827, 826,
],
[
409, 408, 403, 402, 397, 396, 391, 390, 79, 78, -2, -2, 13, 12, 37, 36, 2, -1, 44, 43, 109,
108, 385, 384, 379, 378, 373, 372, 828, -3,
],
[
411, 410, 405, 404, 399, 398, 393, 392, 81, 80, 40, -2, 15, 14, 39, 38, 3, -1, -1, 45, 111,
110, 387, 386, 381, 380, 375, 374, 830, 829,
],
[
413, 412, 407, 406, 401, 400, 395, 394, 83, 82, 41, -3, -3, -3, -3, -3, 5, 4, 47, 46, 113,
112, 389, 388, 383, 382, 377, 376, 831, -3,
],
[
415, 414, 421, 420, 427, 426, 103, 102, 55, 54, 16, -3, -3, -3, -3, -3, -3, -3, 20, 19, 85,
84, 433, 432, 439, 438, 445, 444, 833, 832,
],
[
417, 416, 423, 422, 429, 428, 105, 104, 57, 56, -3, -3, -3, -3, -3, -3, -3, -3, 22, 21, 87,
86, 435, 434, 441, 440, 447, 446, 834, -3,
],
[
419, 418, 425, 424, 431, 430, 107, 106, 59, 58, -3, -3, -3, -3, -3, -3, -3, -3, -3, 23, 89,
88, 437, 436, 443, 442, 449, 448, 836, 835,
],
[
481, 480, 475, 474, 469, 468, 48, -2, 30, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0, 53,
52, 463, 462, 457, 456, 451, 450, 837, -3,
],
[
483, 482, 477, 476, 471, 470, 49, -1, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -2,
-1, 465, 464, 459, 458, 453, 452, 839, 838,
],
[
485, 484, 479, 478, 473, 472, 51, 50, 31, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 1, -2,
42, 467, 466, 461, 460, 455, 454, 840, -3,
],
[
487, 486, 493, 492, 499, 498, 97, 96, 61, 60, -3, -3, -3, -3, -3, -3, -3, -3, -3, 26, 91,
90, 505, 504, 511, 510, 517, 516, 842, 841,
],
[
489, 488, 495, 494, 501, 500, 99, 98, 63, 62, -3, -3, -3, -3, -3, -3, -3, -3, 28, 27, 93,
92, 507, 506, 513, 512, 519, 518, 843, -3,
],
[
491, 490, 497, 496, 503, 502, 101, 100, 65, 64, 17, -3, -3, -3, -3, -3, -3, -3, 18, 29, 95,
94, 509, 508, 515, 514, 521, 520, 845, 844,
],
[
559, 558, 553, 552, 547, 546, 541, 540, 73, 72, 32, -3, -3, -3, -3, -3, -3, 10, 67, 66,
115, 114, 535, 534, 529, 528, 523, 522, 846, -3,
],
[
561, 560, 555, 554, 549, 548, 543, 542, 75, 74, -2, -1, 7, 6, 35, 34, 11, -2, 69, 68, 117,
116, 537, 536, 531, 530, 525, 524, 848, 847,
],
[
563, 562, 557, 556, 551, 550, 545, 544, 77, 76, -2, 33, 9, 8, 25, 24, -1, -2, 71, 70, 119,
118, 539, 538, 533, 532, 527, 526, 849, -3,
],
[
565, 564, 571, 570, 577, 576, 583, 582, 589, 588, 595, 594, 601, 600, 607, 606, 613, 612,
619, 618, 625, 624, 631, 630, 637, 636, 643, 642, 851, 850,
],
[
567, 566, 573, 572, 579, 578, 585, 584, 591, 590, 597, 596, 603, 602, 609, 608, 615, 614,
621, 620, 627, 626, 633, 632, 639, 638, 645, 644, 852, -3,
],
[
569, 568, 575, 574, 581, 580, 587, 586, 593, 592, 599, 598, 605, 604, 611, 610, 617, 616,
623, 622, 629, 628, 635, 634, 641, 640, 647, 646, 854, 853,
],
[
727, 726, 721, 720, 715, 714, 709, 708, 703, 702, 697, 696, 691, 690, 685, 684, 679, 678,
673, 672, 667, 666, 661, 660, 655, 654, 649, 648, 855, -3,
],
[
729, 728, 723, 722, 717, 716, 711, 710, 705, 704, 699, 698, 693, 692, 687, 686, 681, 680,
675, 674, 669, 668, 663, 662, 657, 656, 651, 650, 857, 856,
],
[
731, 730, 725, 724, 719, 718, 713, 712, 707, 706, 701, 700, 695, 694, 689, 688, 683, 682,
677, 676, 671, 670, 665, 664, 659, 658, 653, 652, 858, -3,
],
[
733, 732, 739, 738, 745, 744, 751, 750, 757, 756, 763, 762, 769, 768, 775, 774, 781, 780,
787, 786, 793, 792, 799, 798, 805, 804, 811, 810, 860, 859,
],
[
735, 734, 741, 740, 747, 746, 753, 752, 759, 758, 765, 764, 771, 770, 777, 776, 783, 782,
789, 788, 795, 794, 801, 800, 807, 806, 813, 812, 861, -3,
],
[
737, 736, 743, 742, 749, 748, 755, 754, 761, 760, 767, 766, 773, 772, 779, 778, 785, 784,
791, 790, 797, 796, 803, 802, 809, 808, 815, 814, 863, 862,
],
];
/**
@@ -59,7 +158,6 @@ const BITNR : [[i16;30];33] = [
pub struct BitMatrixParser(BitMatrix);
impl BitMatrixParser {
/**
* @param bitMatrix {@link BitMatrix} to parse
*/
@@ -84,5 +182,4 @@ impl BitMatrixParser {
}
result
}
}

View File

@@ -254,8 +254,10 @@ fn subtract_two_single_char_strings(str1: &str, str2: &str) -> usize {
let str1_bytes = str1.as_bytes();
let str2_bytes = str2.as_bytes();
let str1_u16 = ((str1_bytes[0] as usize) << 4) + ((str1_bytes[1] as usize) << 2) + str1_bytes[2] as usize;
let str2_u16 = ((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize;
let str1_u16 =
((str1_bytes[0] as usize) << 4) + ((str1_bytes[1] as usize) << 2) + str1_bytes[2] as usize;
let str2_u16 =
((str2_bytes[0] as usize) << 4) + ((str2_bytes[1] as usize) << 2) + str2_bytes[2] as usize;
(str1_u16 - str2_u16) as usize
}

View File

@@ -1,4 +1,3 @@
// /*
// * Copyright 2013 ZXing authors
// *

View File

@@ -14,12 +14,9 @@
* limitations under the License.
*/
use std::{
collections::HashMap,
path::{ PathBuf},
};
use std::{collections::HashMap, path::PathBuf};
use image::{DynamicImage};
use image::DynamicImage;
use crate::{
common::BitMatrix, qrcode::QRCodeWriter, BarcodeFormat, EncodeHintType, EncodeHintValue, Writer,

View File

@@ -28,21 +28,18 @@ type MaskCondition = fn(u32, u32) -> bool;
fn testMask0() {
testMaskAcrossDimensions(DataMask::DATA_MASK_000, |i, j| ((i + j) % 2 == 0));
testMaskAcrossDimensionsU8(0, |i, j| ((i + j) % 2 == 0));
}
#[test]
fn testMask1() {
testMaskAcrossDimensions(DataMask::DATA_MASK_001, |i, j| i % 2 == 0);
testMaskAcrossDimensionsU8(1, |i, j| i % 2 == 0);
}
#[test]
fn testMask2() {
testMaskAcrossDimensions(DataMask::DATA_MASK_010, |i, j| j % 3 == 0);
testMaskAcrossDimensionsU8(2, |i, j| j % 3 == 0);
}
#[test]
@@ -62,9 +59,7 @@ fn testMask5() {
testMaskAcrossDimensions(DataMask::DATA_MASK_101, |i, j| {
(i * j) % 2 + (i * j) % 3 == 0
});
testMaskAcrossDimensionsU8(5, |i, j| {
(i * j) % 2 + (i * j) % 3 == 0
});
testMaskAcrossDimensionsU8(5, |i, j| (i * j) % 2 + (i * j) % 3 == 0);
}
#[test]
@@ -72,9 +67,7 @@ fn testMask6() {
testMaskAcrossDimensions(DataMask::DATA_MASK_110, |i, j| {
((i * j) % 2 + (i * j) % 3) % 2 == 0
});
testMaskAcrossDimensionsU8(6, |i, j| {
((i * j) % 2 + (i * j) % 3) % 2 == 0
});
testMaskAcrossDimensionsU8(6, |i, j| ((i * j) % 2 + (i * j) % 3) % 2 == 0);
}
#[test]
@@ -82,9 +75,7 @@ fn testMask7() {
testMaskAcrossDimensions(DataMask::DATA_MASK_111, |i, j| {
((i + j) % 2 + (i * j) % 3) % 2 == 0
});
testMaskAcrossDimensionsU8(7, |i, j| {
((i + j) % 2 + (i * j) % 3) % 2 == 0
});
testMaskAcrossDimensionsU8(7, |i, j| ((i + j) % 2 + (i * j) % 3) % 2 == 0);
}
fn testMaskAcrossDimensionsU8(mask: u8, condition: MaskCondition) {

View File

@@ -14,13 +14,12 @@
* limitations under the License.
*/
use crate::qrcode::decoder::{FormatInformation, ErrorCorrectionLevel};
use crate::qrcode::decoder::{ErrorCorrectionLevel, FormatInformation};
/**
* @author Sean Owen
*/
const MASKED_TEST_FORMAT_INFO: u32 = 0x2BED;
const UNMASKED_TEST_FORMAT_INFO: u32 = MASKED_TEST_FORMAT_INFO ^ 0x5412;
@@ -35,36 +34,77 @@ use crate::qrcode::decoder::{FormatInformation, ErrorCorrectionLevel};
#[test]
fn testDecode() {
// Normal case
let expected =
FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO);
let expected = FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO,
MASKED_TEST_FORMAT_INFO,
);
assert!(expected.is_some());
let expected = expected.unwrap();
assert_eq!(0x07, expected.getDataMask());
assert_eq!(ErrorCorrectionLevel::Q, expected.getErrorCorrectionLevel());
// where the code forgot the mask!
assert_eq!(expected,
FormatInformation::decodeFormatInformation(UNMASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).expect("return"));
assert_eq!(
expected,
FormatInformation::decodeFormatInformation(
UNMASKED_TEST_FORMAT_INFO,
MASKED_TEST_FORMAT_INFO
)
.expect("return")
);
}
#[test]
fn testDecodeWithBitDifference() {
let expected =
FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).unwrap();
let expected = FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO,
MASKED_TEST_FORMAT_INFO,
)
.unwrap();
// 1,2,3,4 bits difference
assert_eq!(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x01, MASKED_TEST_FORMAT_INFO ^ 0x01).expect("return"));
assert_eq!(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x03).expect("return"));
assert_eq!(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x07, MASKED_TEST_FORMAT_INFO ^ 0x07).expect("return"));
assert_eq!(
expected,
FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x01,
MASKED_TEST_FORMAT_INFO ^ 0x01
)
.expect("return")
);
assert_eq!(
expected,
FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03,
MASKED_TEST_FORMAT_INFO ^ 0x03
)
.expect("return")
);
assert_eq!(
expected,
FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x07,
MASKED_TEST_FORMAT_INFO ^ 0x07
)
.expect("return")
);
assert!(FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x0F, MASKED_TEST_FORMAT_INFO ^ 0x0F).is_none());
MASKED_TEST_FORMAT_INFO ^ 0x0F,
MASKED_TEST_FORMAT_INFO ^ 0x0F
)
.is_none());
}
#[test]
fn testDecodeWithMisread() {
let expected =
FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO).unwrap();
assert_eq!(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x0F).unwrap());
let expected = FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO,
MASKED_TEST_FORMAT_INFO,
)
.unwrap();
assert_eq!(
expected,
FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03,
MASKED_TEST_FORMAT_INFO ^ 0x0F
)
.unwrap()
);
}

View File

@@ -18,7 +18,6 @@ use crate::qrcode::decoder::Version;
use super::Mode;
/**
* @author Sean Owen
*/
@@ -41,11 +40,28 @@ use super::Mode;
#[test]
fn testCharacterCount() {
// Spot check a few values
assert_eq!(10, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(5).unwrap()));
assert_eq!(12, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(26).unwrap()));
assert_eq!(14, Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(40).unwrap()));
assert_eq!(9, Mode::ALPHANUMERIC.getCharacterCountBits(Version::getVersionForNumber(6).unwrap()));
assert_eq!(8, Mode::BYTE.getCharacterCountBits(Version::getVersionForNumber(7).unwrap()));
assert_eq!(8, Mode::KANJI.getCharacterCountBits(Version::getVersionForNumber(8).unwrap()));
assert_eq!(
10,
Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(5).unwrap())
);
assert_eq!(
12,
Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(26).unwrap())
);
assert_eq!(
14,
Mode::NUMERIC.getCharacterCountBits(Version::getVersionForNumber(40).unwrap())
);
assert_eq!(
9,
Mode::ALPHANUMERIC.getCharacterCountBits(Version::getVersionForNumber(6).unwrap())
);
assert_eq!(
8,
Mode::BYTE.getCharacterCountBits(Version::getVersionForNumber(7).unwrap())
);
assert_eq!(
8,
Mode::KANJI.getCharacterCountBits(Version::getVersionForNumber(8).unwrap())
);
}

View File

@@ -14,14 +14,15 @@
* limitations under the License.
*/
use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions};
use crate::{
qrcode::decoder::{ErrorCorrectionLevel, Version},
Exceptions,
};
/**
* @author Sean Owen
*/
#[test]
#[should_panic]
fn testBadVersion() {
@@ -62,7 +63,12 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions};
fn testGetProvisionalVersionForDimension() {
for i in 1..=40 {
// for (int i = 1; i <= 40; i++) {
assert_eq!(i, Version::getProvisionalVersionForDimension(4 * i + 17).expect("must exist for supplied values").getVersionNumber());
assert_eq!(
i,
Version::getProvisionalVersionForDimension(4 * i + 17)
.expect("must exist for supplied values")
.getVersionNumber()
);
}
}
@@ -82,4 +88,3 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions};
assert!(version.is_ok());
assert_eq!(expectedVersion, version.unwrap().getVersionNumber());
}

View File

@@ -16,7 +16,7 @@
use crate::Exceptions;
use super::{VersionRef, ErrorCorrectionLevel};
use super::{ErrorCorrectionLevel, VersionRef};
/**
* <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into
@@ -26,13 +26,11 @@ use super::{VersionRef, ErrorCorrectionLevel};
* @author Sean Owen
*/
pub struct DataBlock {
numDataCodewords: u32,
codewords: Vec<u8>,
}
impl DataBlock {
fn new(numDataCodewords: u32, codewords: Vec<u8>) -> Self {
Self {
numDataCodewords,
@@ -51,12 +49,13 @@ impl DataBlock {
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* QR Code
*/
pub fn getDataBlocks( rawCodewords:&[u8],
pub fn getDataBlocks(
rawCodewords: &[u8],
version: VersionRef,
ecLevel:ErrorCorrectionLevel) -> Result<Vec<Self>,Exceptions> {
ecLevel: ErrorCorrectionLevel,
) -> Result<Vec<Self>, Exceptions> {
if rawCodewords.len() as u32 != version.getTotalCodewords() {
return Err(Exceptions::IllegalArgumentException("".to_owned()))
return Err(Exceptions::IllegalArgumentException("".to_owned()));
}
// Figure out the number and size of data blocks used by this version and
@@ -81,7 +80,10 @@ impl DataBlock {
let numDataCodewords = ecBlock.getDataCodewords();
let numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords;
// result[numRXingResultBlocks] = DataBlock::new(numDataCodewords, vec![0u8;numBlockCodewords as usize]);
result.push( DataBlock::new(numDataCodewords, vec![0u8;numBlockCodewords as usize]));
result.push(DataBlock::new(
numDataCodewords,
vec![0u8; numBlockCodewords as usize],
));
numRXingResultBlocks += 1;
}
}
@@ -100,7 +102,8 @@ impl DataBlock {
}
longerBlocksStartAt += 1;
let shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock() as usize;
let shorterBlocksNumDataCodewords =
shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock() as usize;
// The last elements of result may be 1 element longer;
// first fill out as many elements as all of them have
let mut rawCodewordsOffset = 0;
@@ -139,5 +142,4 @@ impl DataBlock {
pub fn getCodewords(&self) -> &[u8] {
&self.codewords
}
}

View File

@@ -230,7 +230,10 @@ impl TryFrom<u8> for DataMask {
5 => Ok(DataMask::DATA_MASK_101),
6 => Ok(DataMask::DATA_MASK_110),
7 => Ok(DataMask::DATA_MASK_111),
_=>Err(Exceptions::IllegalArgumentException(format!("{} is not between 0 and 7",value))),
_ => Err(Exceptions::IllegalArgumentException(format!(
"{} is not between 0 and 7",
value
))),
}
}
}

View File

@@ -286,7 +286,9 @@ fn decodeByteSegment(
encoding = CharacterSetECI::getCharset(currentCharacterSetECI.as_ref().unwrap());
}
let encode_string = if currentCharacterSetECI.is_some() && currentCharacterSetECI.as_ref().unwrap() == &CharacterSetECI::Cp437 {
let encode_string = if currentCharacterSetECI.is_some()
&& currentCharacterSetECI.as_ref().unwrap() == &CharacterSetECI::Cp437
{
{
use codepage_437::BorrowFromCp437;
use codepage_437::CP437_CONTROL;

View File

@@ -110,7 +110,10 @@ impl FromStr for ErrorCorrectionLevel {
return number_possible.unwrap().try_into();
}
return Err(Exceptions::IllegalArgumentException(format!("could not parse {} into an ec level", s)))
return Err(Exceptions::IllegalArgumentException(format!(
"could not parse {} into an ec level",
s
)));
}
}

View File

@@ -101,7 +101,7 @@ impl FormatInformation {
) -> Option<FormatInformation> {
let formatInfo = Self::doDecodeFormatInformation(masked_format_info1, masked_format_info2);
if formatInfo.is_some() {
return formatInfo
return formatInfo;
}
// Should return null, but, some QR codes apparently
// do not mask this info. Try again by actually masking the pattern

View File

@@ -1,32 +1,32 @@
mod version;
mod mode;
mod error_correction_level;
mod format_information;
mod data_block;
mod qr_code_decoder_meta_data;
mod data_mask;
mod bit_matrix_parser;
mod data_block;
mod data_mask;
pub mod decoded_bit_stream_parser;
pub mod decoder;
mod error_correction_level;
mod format_information;
mod mode;
mod qr_code_decoder_meta_data;
mod version;
#[cfg(test)]
mod ErrorCorrectionLevelTestCase;
#[cfg(test)]
mod ModeTestCase;
#[cfg(test)]
mod VersionTestCase;
#[cfg(test)]
mod FormatInformationTestCase;
#[cfg(test)]
mod DataMaskTestCase;
#[cfg(test)]
mod DecodedBitStreamParserTestCase;
#[cfg(test)]
mod ErrorCorrectionLevelTestCase;
#[cfg(test)]
mod FormatInformationTestCase;
#[cfg(test)]
mod ModeTestCase;
#[cfg(test)]
mod VersionTestCase;
pub use version::*;
pub use mode::*;
pub use bit_matrix_parser::*;
pub use data_block::*;
pub use data_mask::*;
pub use error_correction_level::*;
pub use format_information::*;
pub use data_block::*;
pub use mode::*;
pub use qr_code_decoder_meta_data::*;
pub use data_mask::*;
pub use bit_matrix_parser::*;
pub use version::*;

View File

@@ -43,12 +43,11 @@ impl QRCodeDecoderMetaData {
*/
pub fn applyMirroredCorrection(&self, points: &mut [RXingResultPoint]) {
if !self.0 || points.is_empty() || points.len() < 3 {
return
return;
}
let bottom_left = points[0];
points[0] = points[2];
points[2] = bottom_left;
// No need to 'fix' top-left and alignment pattern.
}
}

View File

@@ -40,7 +40,10 @@ impl ResultPoint for AlignmentPattern {
}
fn into_rxing_result_point(self) -> RXingResultPoint {
RXingResultPoint { x: self.point.0, y: self.point.1 }
RXingResultPoint {
x: self.point.0,
y: self.point.1,
}
}
}

View File

@@ -238,14 +238,20 @@ impl AlignmentPatternFinder {
// Now also count down from center
i = startI as i32 + 1;
while i < maxI as i32 && image.get(centerJ, i as u32) && self.crossCheckStateCount[1] <= maxCount {
while i < maxI as i32
&& image.get(centerJ, i as u32)
&& self.crossCheckStateCount[1] <= maxCount
{
self.crossCheckStateCount[1] += 1;
i += 1;
}
if i == maxI as i32 || self.crossCheckStateCount[1] > maxCount {
return f32::NAN;
}
while i < maxI as i32 && !image.get(centerJ, i as u32) && self.crossCheckStateCount[2] <= maxCount {
while i < maxI as i32
&& !image.get(centerJ, i as u32)
&& self.crossCheckStateCount[2] <= maxCount
{
self.crossCheckStateCount[2] += 1;
i += 1;
}

View File

@@ -18,8 +18,7 @@ use std::collections::HashMap;
use crate::{
common::{
detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler,
PerspectiveTransform,
detector::MathUtils, BitMatrix, DefaultGridSampler, GridSampler, PerspectiveTransform,
},
qrcode::decoder::Version,
result_point_utils, DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
@@ -341,7 +340,8 @@ impl Detector {
scale = fromX as f32 / (fromX as i32 - otherToX) as f32;
otherToX = 0;
} else if otherToX as u32 >= self.image.getWidth() {
scale = (self.image.getWidth() as i32 - 1 - fromX as i32) as f32 / (otherToX - fromX as i32) as f32;
scale = (self.image.getWidth() as i32 - 1 - fromX as i32) as f32
/ (otherToX - fromX as i32) as f32;
otherToX = self.image.getWidth() as i32 - 1;
}
let mut otherToY = (fromY as f32 - (toY as f32 - fromY as f32) * scale).floor() as i32;
@@ -351,12 +351,18 @@ impl Detector {
scale = fromY as f32 / (fromY as i32 - otherToY) as f32;
otherToY = 0;
} else if otherToY as u32 >= self.image.getHeight() {
scale = (self.image.getHeight() as i32 - 1 - fromY as i32) as f32 / (otherToY - fromY as i32) as f32;
scale = (self.image.getHeight() as i32 - 1 - fromY as i32) as f32
/ (otherToY - fromY as i32) as f32;
otherToY = self.image.getHeight() as i32 - 1;
}
otherToX = (fromX as f32 + (otherToX as f32 - fromX as f32) * scale).floor() as i32;
result += self.sizeOfBlackWhiteBlackRun(fromX as u32, fromY as u32, otherToX as u32, otherToY as u32);
result += self.sizeOfBlackWhiteBlackRun(
fromX as u32,
fromY as u32,
otherToX as u32,
otherToY as u32,
);
// Middle pixel is double-counted this way; subtract 1
return result - 1.0;

View File

@@ -40,7 +40,10 @@ impl ResultPoint for FinderPattern {
}
fn into_rxing_result_point(self) -> RXingResultPoint {
RXingResultPoint { x: self.point.0, y: self.point.1 }
RXingResultPoint {
x: self.point.0,
y: self.point.1,
}
}
}

View File

@@ -76,7 +76,6 @@ impl FinderPatternFinder {
&mut self,
hints: &DecodingHintDictionary,
) -> Result<FinderPatternInfo, Exceptions> {
let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER);
let maxI = self.image.getHeight();
let maxJ = self.image.getWidth();
@@ -136,7 +135,9 @@ impl FinderPatternFinder {
// Skip by rowSkip, but back off by stateCount[2] (size of last center
// of pattern we saw) to be conservative, and also back off by iSkip which
// is about to be re-added
i += rowSkip as i32 - stateCount[2] as i32 - iSkip as i32;
i += rowSkip as i32
- stateCount[2] as i32
- iSkip as i32;
// i += rowSkip - stateCount[2] - iSkip ;
j = maxJ - 1;
}
@@ -379,7 +380,10 @@ impl FinderPatternFinder {
if i < 0 {
return f32::NAN;
}
while i >= 0 && !self.image.get(centerJ, i as u32) && self.crossCheckStateCount[1] <= maxCount {
while i >= 0
&& !self.image.get(centerJ, i as u32)
&& self.crossCheckStateCount[1] <= maxCount
{
self.crossCheckStateCount[1] += 1;
i -= 1;
}
@@ -387,7 +391,10 @@ impl FinderPatternFinder {
if i < 0 || self.crossCheckStateCount[1] > maxCount {
return f32::NAN;
}
while i >= 0 && self.image.get(centerJ, i as u32) && self.crossCheckStateCount[0] <= maxCount {
while i >= 0
&& self.image.get(centerJ, i as u32)
&& self.crossCheckStateCount[0] <= maxCount
{
self.crossCheckStateCount[0] += 1;
i -= 1;
}
@@ -404,14 +411,20 @@ impl FinderPatternFinder {
if i == maxI {
return f32::NAN;
}
while i < maxI && !self.image.get(centerJ, i as u32) && self.crossCheckStateCount[3] < maxCount {
while i < maxI
&& !self.image.get(centerJ, i as u32)
&& self.crossCheckStateCount[3] < maxCount
{
self.crossCheckStateCount[3] += 1;
i += 1;
}
if i == maxI || self.crossCheckStateCount[3] >= maxCount {
return f32::NAN;
}
while i < maxI && self.image.get(centerJ, i as u32) && self.crossCheckStateCount[4] < maxCount {
while i < maxI
&& self.image.get(centerJ, i as u32)
&& self.crossCheckStateCount[4] < maxCount
{
self.crossCheckStateCount[4] += 1;
i += 1;
}
@@ -426,7 +439,9 @@ impl FinderPatternFinder {
+ self.crossCheckStateCount[2]
+ self.crossCheckStateCount[3]
+ self.crossCheckStateCount[4];
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) >= 2 * originalStateCountTotal as i64 {
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64)
>= 2 * originalStateCountTotal as i64
{
return f32::NAN;
}
@@ -462,14 +477,20 @@ impl FinderPatternFinder {
if j < 0 {
return f32::NAN;
}
while j >= 0 && !self.image.get(j as u32, centerI) && self.crossCheckStateCount[1] <= maxCount {
while j >= 0
&& !self.image.get(j as u32, centerI)
&& self.crossCheckStateCount[1] <= maxCount
{
self.crossCheckStateCount[1] += 1;
j -= 1;
}
if j < 0 || self.crossCheckStateCount[1] > maxCount {
return f32::NAN;
}
while j >= 0 && self.image.get(j as u32 as u32, centerI) && self.crossCheckStateCount[0] <= maxCount {
while j >= 0
&& self.image.get(j as u32 as u32, centerI)
&& self.crossCheckStateCount[0] <= maxCount
{
self.crossCheckStateCount[0] += 1;
j -= 1;
}
@@ -485,14 +506,20 @@ impl FinderPatternFinder {
if j == maxJ as i32 {
return f32::NAN;
}
while j < maxJ as i32 && !self.image.get(j as u32, centerI) && self.crossCheckStateCount[3] < maxCount {
while j < maxJ as i32
&& !self.image.get(j as u32, centerI)
&& self.crossCheckStateCount[3] < maxCount
{
self.crossCheckStateCount[3] += 1;
j += 1;
}
if j == (maxJ as i32) || self.crossCheckStateCount[3] >= maxCount {
return f32::NAN;
}
while j < (maxJ as i32) && self.image.get(j as u32, centerI) && self.crossCheckStateCount[4] < maxCount {
while j < (maxJ as i32)
&& self.image.get(j as u32, centerI)
&& self.crossCheckStateCount[4] < maxCount
{
self.crossCheckStateCount[4] += 1;
j += 1;
}
@@ -507,7 +534,9 @@ impl FinderPatternFinder {
+ self.crossCheckStateCount[2]
+ self.crossCheckStateCount[3]
+ self.crossCheckStateCount[4];
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64) >= originalStateCountTotal as i64 {
if 5 * (stateCountTotal as i64 - originalStateCountTotal as i64)
>= originalStateCountTotal as i64
{
return f32::NAN;
}
@@ -559,7 +588,8 @@ impl FinderPatternFinder {
let stateCountTotal =
stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
let mut centerJ = Self::centerFromEnd(stateCount, j);
let centerI = self.crossCheckVertical(i, centerJ.floor() as u32, stateCount[2], stateCountTotal);
let centerI =
self.crossCheckVertical(i, centerJ.floor() as u32, stateCount[2], stateCountTotal);
if !centerI.is_nan() {
// Re-cross check
centerJ = self.crossCheckHorizontal(
@@ -568,7 +598,9 @@ impl FinderPatternFinder {
stateCount[2],
stateCountTotal,
);
if !centerJ.is_nan() && self.crossCheckDiagonal(centerI.floor() as u32, centerJ.floor() as u32) {
if !centerJ.is_nan()
&& self.crossCheckDiagonal(centerI.floor() as u32, centerJ.floor() as u32)
{
let estimatedModuleSize = stateCountTotal as f32 / 7.0;
let mut found = false;
for index in 0..self.possibleCenters.len() {

View File

@@ -1,17 +1,17 @@
mod finder_pattern_info;
mod finder_pattern;
mod alignment_pattern;
mod alignment_pattern_finder;
mod finder_pattern_finder;
mod detector;
mod finder_pattern;
mod finder_pattern_finder;
mod finder_pattern_info;
mod qrcode_detector_result;
pub use finder_pattern_info::*;
pub use finder_pattern::*;
pub use alignment_pattern::*;
pub use alignment_pattern_finder::*;
pub use finder_pattern_finder::*;
pub use detector::*;
pub use finder_pattern::*;
pub use finder_pattern_finder::*;
pub use finder_pattern_info::*;
pub use qrcode_detector_result::*;
#[cfg(test)]

View File

@@ -415,7 +415,8 @@ fn testAppendLengthInfo() {
Version::getVersionForNumber(1).unwrap(),
Mode::NUMERIC,
&mut bits,
).expect("ok");
)
.expect("ok");
assert_eq!(" ........ .X", bits.to_string()); // 10 bits.
let mut bits = BitArray::new();
encoder::appendLengthInfo(
@@ -423,7 +424,8 @@ fn testAppendLengthInfo() {
Version::getVersionForNumber(10).unwrap(),
Mode::ALPHANUMERIC,
&mut bits,
).expect("ok");
)
.expect("ok");
assert_eq!(" ........ .X.", bits.to_string()); // 11 bits.
let mut bits = BitArray::new();
encoder::appendLengthInfo(
@@ -431,7 +433,8 @@ fn testAppendLengthInfo() {
Version::getVersionForNumber(27).unwrap(),
Mode::BYTE,
&mut bits,
).expect("ok");
)
.expect("ok");
assert_eq!(" ........ XXXXXXXX", bits.to_string()); // 16 bits.
let mut bits = BitArray::new();
encoder::appendLengthInfo(
@@ -439,7 +442,8 @@ fn testAppendLengthInfo() {
Version::getVersionForNumber(40).unwrap(),
Mode::KANJI,
&mut bits,
).expect("ok");
)
.expect("ok");
assert_eq!(" ..X..... ....", bits.to_string()); // 12 bits.
}
@@ -453,7 +457,8 @@ fn testAppendBytes() {
Mode::NUMERIC,
&mut bits,
encoder::DEFAULT_BYTE_MODE_ENCODING,
).expect("ok");
)
.expect("ok");
assert_eq!(" ...X", bits.to_string());
// Should use appendAlphanumericBytes.
// A = 10 = 0xa = 001010 in 6 bits
@@ -463,7 +468,8 @@ fn testAppendBytes() {
Mode::ALPHANUMERIC,
&mut bits,
encoder::DEFAULT_BYTE_MODE_ENCODING,
).expect("ok");
)
.expect("ok");
assert_eq!(" ..X.X.", bits.to_string());
// Lower letters such as 'a' cannot be encoded in MODE_ALPHANUMERIC.
//try {
@@ -488,7 +494,8 @@ fn testAppendBytes() {
Mode::BYTE,
&mut bits,
encoder::DEFAULT_BYTE_MODE_ENCODING,
).expect("ok");
)
.expect("ok");
assert_eq!(" .XX....X .XX...X. .XX...XX", bits.to_string());
// Anything can be encoded in QRCode.MODE_8BIT_BYTE.
encoder::appendBytes(
@@ -496,7 +503,8 @@ fn testAppendBytes() {
Mode::BYTE,
&mut bits,
encoder::DEFAULT_BYTE_MODE_ENCODING,
).expect("ok");
)
.expect("ok");
// Should use appendKanjiBytes.
// 0x93, 0x5f
let mut bits = BitArray::new();
@@ -505,7 +513,8 @@ fn testAppendBytes() {
Mode::KANJI,
&mut bits,
encoder::DEFAULT_BYTE_MODE_ENCODING,
).expect("ok");
)
.expect("ok");
assert_eq!(" .XX.XX.. XXXXX", bits.to_string());
}
@@ -540,80 +549,45 @@ fn testTerminateBits() {
#[test]
fn testGetNumDataBytesAndNumECBytesForBlockID() {
// Version 1-H.
let (numDataBytes,numEcBytes) = encoder::getNumDataBytesAndNumECBytesForBlockID(
26,
9,
1,
0,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(26, 9, 1, 0).expect("ok");
assert_eq!(9, numDataBytes);
assert_eq!(17, numEcBytes);
// Version 3-H. 2 blocks.
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
70,
26,
2,
0,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 0).expect("ok");
assert_eq!(13, numDataBytes);
assert_eq!(22, numEcBytes);
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
70,
26,
2,
1,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 1).expect("ok");
assert_eq!(13, numDataBytes);
assert_eq!(22, numEcBytes);
// Version 7-H. (4 + 1) blocks.
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
196,
66,
5,
0,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 0).expect("ok");
assert_eq!(13, numDataBytes);
assert_eq!(26, numEcBytes);
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
196,
66,
5,
4,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 4).expect("ok");
assert_eq!(14, numDataBytes);
assert_eq!(26, numEcBytes);
// Version 40-H. (20 + 61) blocks.
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
3706,
1276,
81,
0,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 0).expect("ok");
assert_eq!(15, numDataBytes);
assert_eq!(30, numEcBytes);
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
3706,
1276,
81,
20,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 20).expect("ok");
assert_eq!(16, numDataBytes);
assert_eq!(30, numEcBytes);
let (numDataBytes,numEcBytes) =encoder::getNumDataBytesAndNumECBytesForBlockID(
3706,
1276,
81,
80,
).expect("ok");
let (numDataBytes, numEcBytes) =
encoder::getNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 80).expect("ok");
assert_eq!(16, numDataBytes);
assert_eq!(30, numEcBytes);
}
@@ -738,7 +712,8 @@ fn testAppendAlphanumericBytes() {
fn testAppend8BitBytes() {
// 0x61, 0x62, 0x63
let mut bits = BitArray::new();
encoder::append8BitBytes("abc", &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING).expect("append");
encoder::append8BitBytes("abc", &mut bits, encoder::DEFAULT_BYTE_MODE_ENCODING)
.expect("append");
assert_eq!(" .XX....X .XX...X. .XX...XX", bits.to_string());
// Empty.
let mut bits = BitArray::new();

View File

@@ -254,7 +254,8 @@ fn testBuildMatrix() {
Version::getVersionForNumber(1).expect("version"), // Version 1
3, // Mask pattern 3
&mut matrix,
).expect("append");
)
.expect("append");
let expected = r" 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1
1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1
1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1

View File

@@ -14,17 +14,18 @@
* limitations under the License.
*/
use crate::qrcode::{decoder::{Mode, ErrorCorrectionLevel, Version}, encoder::ByteMatrix};
use crate::qrcode::{
decoder::{ErrorCorrectionLevel, Mode, Version},
encoder::ByteMatrix,
};
use super::QRCode;
/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author mysen@google.com (Chris Mysen) - ported from C++
*/
#[test]
fn test() {
let mut qrCode = QRCode::new();
@@ -119,4 +120,3 @@ use super::QRCode;
assert!(QRCode::isValidMaskPattern(7));
assert!(!QRCode::isValidMaskPattern(8));
}

View File

@@ -155,7 +155,9 @@ pub fn encode_with_hints(
let encoding = if encoding.is_some() {
encoding.unwrap()
} else {
if let Ok(_encs) = DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict){
if let Ok(_encs) =
DEFAULT_BYTE_MODE_ENCODING.encode(content, encoding::EncoderTrap::Strict)
{
DEFAULT_BYTE_MODE_ENCODING
} else {
has_encoding_hint = true;
@@ -302,8 +304,12 @@ fn recommendVersion(
// 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:
let provisional_bits_needed =
calculateBitsNeeded(mode, header_bits, data_bits, Version::getVersionForNumber(1)?);
let provisional_bits_needed = calculateBitsNeeded(
mode,
header_bits,
data_bits,
Version::getVersionForNumber(1)?,
);
let provisional_version = chooseVersion(provisional_bits_needed, ec_level)?;
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.

View File

@@ -154,7 +154,8 @@ pub fn applyMaskPenaltyRule4(matrix: &ByteMatrix) -> u32 {
}
}
let numTotalCells = matrix.getHeight() * matrix.getWidth();
let fivePercentVariances = (numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells;
let fivePercentVariances =
(numDarkCells as i64 * 2 - numTotalCells as i64).abs() as u32 * 10 / numTotalCells;
return fivePercentVariances * N4;
}

View File

@@ -24,7 +24,7 @@ use crate::{
Exceptions,
};
use unicode_segmentation::{ UnicodeSegmentation};
use unicode_segmentation::UnicodeSegmentation;
use super::encoder;
@@ -834,7 +834,8 @@ impl RXingResultList {
}
let first = list.get(0);
// prepend or insert a FNC1_FIRST_POSITION after the ECI (if any)
if first.is_some() && first.as_ref().unwrap().mode != Mode::ECI {//&& containsECI {
if first.is_some() && first.as_ref().unwrap().mode != Mode::ECI {
//&& containsECI {
list.insert(
if first.as_ref().unwrap().mode != Mode::ECI {
//first

Some files were not shown because too many files have changed in this diff Show More