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

@@ -75,7 +75,7 @@ fn test_crop() {
.unwrap();
assert!(source.isCropSupported());
let cropMatrix = source.getMatrix();
for r in 0..ROWS-2 {
for r in 0..ROWS - 2 {
// for (int r = 0; r < ROWS - 2; r++) {
assert_equals(
&Y,
@@ -85,7 +85,7 @@ fn test_crop() {
COLS - 2,
);
}
for r in 0..ROWS-2 {
for r in 0..ROWS - 2 {
// for (int r = 0; r < ROWS - 2; r++) {
assert_equals(
&Y,

View File

@@ -24,49 +24,52 @@
// */
// 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() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec());
#[test]
fn testCrop() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec());
assert!(SOURCE.isCropSupported());
let cropped = SOURCE.crop(1, 1, 1, 1).unwrap();
assert_eq!(1, cropped.getHeight());
assert_eq!(1, cropped.getWidth());
assert_eq!(vec![ 0x7F ], cropped.getRow(0, &vec![0;0]));
}
assert_eq!(vec![0x7F], cropped.getRow(0, &vec![0; 0]));
}
#[test]
fn testMatrix() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec());
#[test]
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]
fn testGetRow() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&SRC_DATA.to_vec());
#[test]
fn testGetRow() {
let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3, 3, &SRC_DATA.to_vec());
assert_eq!(vec![ 0x3F, 0x7F, 0x3F ], SOURCE.getRow(2, &vec![0;3]));
}
assert_eq!(vec![0x3F, 0x7F, 0x3F], SOURCE.getRow(2, &vec![0; 3]));
}
// #[test]
// fn testToString() {
// let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&src_data.to_vec());
// #[test]
// fn testToString() {
// let SOURCE = RGBLuminanceSource::new_with_width_height_pixels(3,3,&src_data.to_vec());
// assert_eq!("#+ \n#+#\n#+#\n", SOURCE.toString());
// }
// assert_eq!("#+ \n#+#\n#+#\n", SOURCE.toString());
// }
// }

View File

@@ -176,8 +176,10 @@ 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 writer = AztecWriter {};
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

@@ -319,7 +319,7 @@ impl Detector {
color = !color;
self.nb_center_layers+=1;
self.nb_center_layers += 1;
}
if self.nb_center_layers != 5 && self.nb_center_layers != 7 {
@@ -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,
},
@@ -157,7 +157,7 @@ pub fn encode_bytes_with_charset(
let ecc_bits = bits.getSize() as u32 * min_eccpercent / 100 + 11;
let total_size_bits = bits.getSize() as u32 + ecc_bits;
let mut compact;
let mut layers:u32;
let mut layers: u32;
let mut total_bits_in_layer_var;
let mut word_size;
let mut stuffed_bits;

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

@@ -36,7 +36,7 @@ impl TokenType {
}
}
#[derive(Debug,Clone,PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
tokens: Vec<TokenType>,
//current_pointer: usize,

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

@@ -5,11 +5,11 @@ use crate::common::BitArray;
use lazy_static::lazy_static;
lazy_static! {
static ref SPACES: Regex =Regex::new("\\s+").unwrap();
static ref SPACES: Regex = Regex::new("\\s+").unwrap();
static ref DOTX: Regex = Regex::new("[^.X]").unwrap();
}
pub fn toBitArray( bits:&str) -> BitArray{
pub fn toBitArray(bits: &str) -> BitArray {
let mut ba_in = BitArray::new();
let str = DOTX.replace_all(bits, "");
for a_str in str.chars() {
@@ -18,17 +18,17 @@ pub fn toBitArray( bits:&str) -> BitArray{
}
ba_in
}
}
pub fn toBooleanArray( bitArray:&BitArray) ->Vec<bool>{
let mut result = vec![false;bitArray.getSize()];
pub fn toBooleanArray(bitArray: &BitArray) -> Vec<bool> {
let mut result = vec![false; bitArray.getSize()];
for i in 0..result.len() {
// for (int i = 0; i < result.length; i++) {
result[i] = bitArray.get(i);
}
result
}
}
pub fn stripSpace( s:&str) -> String{
pub fn stripSpace(s: &str) -> String {
SPACES.replace_all(s, "").to_string()
}
}

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

@@ -27,7 +27,7 @@ use imageproc::geometric_transformations::rotate_about_center;
use crate::LuminanceSource;
// const MINUS_45_IN_RADIANS: f32 = -0.7853981633974483; // Math.toRadians(-45.0)
const MINUS_45_IN_RADIANS : f32 = std::f32::consts::FRAC_PI_4;
const MINUS_45_IN_RADIANS: f32 = std::f32::consts::FRAC_PI_4;
/**
* This LuminanceSource implementation is meant for J2SE clients and our blackbox unit tests.

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

@@ -62,7 +62,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
Vec::new()
},
Vec::new(),
pronunciation.unwrap_or_default(),//"".to_owned(),
pronunciation.unwrap_or_default(), //"".to_owned(),
phoneNumbers,
Vec::new(),
emails, //Vec::new(),

View File

@@ -117,17 +117,17 @@ impl AddressBookParsedRXingResult {
urls: Vec<String>,
geo: Vec<String>,
) -> Result<Self, Exceptions> {
if phone_numbers.len() != phone_types.len() && phone_types.len() > 0{
if phone_numbers.len() != phone_types.len() && phone_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Phone numbers and types lengths differ".to_owned(),
));
}
if emails.len() != email_types.len() && email_types.len() > 0{
if emails.len() != email_types.len() && email_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Emails and types lengths differ".to_owned(),
));
}
if addresses.len() != address_types.len() && address_types.len() > 0{
if addresses.len() != address_types.len() && address_types.len() > 0 {
return Err(Exceptions::IllegalArgumentException(
"Addresses and types lengths differ".to_owned(),
));

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

@@ -27,16 +27,14 @@
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
use chrono::{ DateTime, NaiveDateTime, TimeZone, Utc};
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)?)?";
@@ -49,8 +47,9 @@ 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 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();
}
// 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

@@ -16,7 +16,7 @@
// package com.google.zxing.client.result;
use super::{ ParsedRXingResult, ParsedRXingResultType, ResultParser};
use super::{ParsedRXingResult, ParsedRXingResultType, ResultParser};
/**
* Represents a parsed result that encodes an email message including recipients, subject

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

@@ -27,11 +27,14 @@ use crate::RXingResult;
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 COMMA: Regex = Regex::new(",").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
@@ -39,14 +42,14 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
*
* @author Sean Owen
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// let comma_regex = Regex::new(",").unwrap();
// private static final Pattern COMMA = Pattern.compile(",");
let rawText = ResultParser::getMassagedText(result);
if rawText.starts_with("mailto:") || rawText.starts_with("MAILTO:") {
// If it starts with mailto:, assume it is definitely trying to be an email address
let mut hostEmail = &rawText[7..];
if let Some(queryStart) = hostEmail.find('?'){
if let Some(queryStart) = hostEmail.find('?') {
hostEmail = &hostEmail[..queryStart];
}
// int queryStart = hostEmail.indexOf('?');
@@ -54,9 +57,9 @@ use super::{ParsedClientResult, ResultParser, EmailDoCoMoResultParser, EmailAddr
// hostEmail = hostEmail.substring(0, queryStart);
// }
// try {
let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail){
let tmp = if let Ok(res) = ResultParser::urlDecode(hostEmail) {
res
}else {
} else {
return None;
};
hostEmail = tmp.as_str();
@@ -65,35 +68,51 @@ 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()
} else {
COMMA
.split(hostEmail)
.into_iter()
.map(|s| s.to_owned())
.collect()
};
// if (!hostEmail.isEmpty()) {
// tos = COMMA.split(hostEmail);
// }
let nameValues = ResultParser::parseNameValuePairs(&rawText);
let mut ccs:Vec<String> = Vec::new();
let mut bccs:Vec<String> = Vec::new();
let mut ccs: Vec<String> = Vec::new();
let mut bccs: Vec<String> = Vec::new();
let mut subject = "".to_owned();
let mut body = "".to_owned();
if let Some(nv) = nameValues {
// 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();
if let Some(tosString) = nv.get("to") {
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();
if let Some(ccString) = nv.get("cc") {
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();
if let Some(bccString) = nv.get("bcc") {
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) {
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();
}
/**
@@ -40,8 +40,7 @@ lazy_static! {
*
* @author Sean Owen
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if !rawText.starts_with("MATMSG:") {
return None;
@@ -53,25 +52,29 @@ 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),
))
}
/**
/**
* This implements only the most basic checking for an email address's validity -- that it contains
* an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of
* validity. We want to generally be lenient here since this class is only intended to encapsulate what's
* in a barcode, not "judge" it.
*/
pub fn isBasicallyValidEmailAddress( email:&str, regex:&Regex)-> bool {
pub fn isBasicallyValidEmailAddress(email: &str, regex: &Regex) -> bool {
let email_exists = !email.is_empty();
let email_has_at = matches!(email.find('@'),Some(_));
let email_has_at = matches!(email.find('@'), Some(_));
let email_alphamatcher = if let Some(mtch) = regex.find(email) {
mtch.start() ==0 && mtch.end() == email.len()
}else{
mtch.start() == 0 && mtch.end() == email.len()
} else {
false
};
email_exists && email_alphamatcher && email_has_at
// return email != null && ATEXT_ALPHANUMERIC.matcher(email).matches() && email.indexOf('@') >= 0;
}
}

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

@@ -26,7 +26,7 @@ use super::{GeoParsedRXingResult, ParsedClientResult, ResultParser};
use lazy_static::lazy_static;
lazy_static! {
static ref GEO_URL :regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap();
static ref GEO_URL: regex::Regex = regex::Regex::new(GEO_URL_PATTERN).unwrap();
}
const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?";
@@ -42,7 +42,7 @@ const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9
// pub struct GeoRXingResultParser {}
// impl RXingResultParser for GeoRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
if let Some(captures) = GEO_URL.captures(&rawText.to_lowercase()) {
@@ -126,5 +126,5 @@ const GEO_URL_PATTERN: &'static str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9
// if (!matcher.matches()) {
// return null;
// }
}
}
// }

View File

@@ -24,10 +24,9 @@ use super::ParsedRXingResult;
* @author jbreiden@google.com (Jeff Breidenbach)
*/
pub struct ISBNParsedRXingResult {
isbn:String,
isbn: String,
}
impl ParsedRXingResult for ISBNParsedRXingResult {
impl ParsedRXingResult for ISBNParsedRXingResult {
fn getType(&self) -> super::ParsedRXingResultType {
super::ParsedRXingResultType::ISBN
}
@@ -37,14 +36,12 @@ pub struct ISBNParsedRXingResult {
}
}
impl ISBNParsedRXingResult {
pub fn new( isbn:String)->Self {
Self{ isbn }
impl ISBNParsedRXingResult {
pub fn new(isbn: String) -> Self {
Self { isbn }
}
pub fn getISBN(&self) -> &str{
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.
@@ -31,10 +31,10 @@ use super::{ ResultParser, ISBNParsedRXingResult, ParsedClientResult};
// pub struct ISBNRXingResultParser {}
// impl RXingResultParser for ISBNRXingResultParser {
/**
/**
* See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a>
*/
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
let format = theRXingResult.getBarcodeFormat();
if *format != BarcodeFormat::EAN_13 {
return None;
@@ -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

@@ -22,9 +22,8 @@
*
* @author Sean Owen
*/
#[derive(Debug,PartialEq, Eq,Hash)]
#[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,
product_id: String,
normalized_product_id: String,
}
impl ParsedRXingResult for ProductParsedRXingResult {
fn getType(&self) -> super::ParsedRXingResultType {
@@ -39,23 +37,22 @@ impl ParsedRXingResult for ProductParsedRXingResult {
}
}
impl ProductParsedRXingResult {
pub fn new(product_id:String) -> Self {
pub fn new(product_id: String) -> Self {
Self::with_normalized_id(product_id.clone(), product_id)
}
pub fn with_normalized_id( product_id: String, normalized_product_id:String) -> Self {
Self{
pub fn with_normalized_id(product_id: String, normalized_product_id: String) -> Self {
Self {
product_id,
normalized_product_id,
}
}
pub fn getProductID(&self) -> &str{
pub fn getProductID(&self) -> &str {
&self.product_id
}
pub fn getNormalizedProductID(&self) -> &str {
&self.normalized_product_id
}
}

View File

@@ -27,20 +27,22 @@
* @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;
#[test]
fn test_product() {
#[test]
fn test_product() {
do_test("123456789012", "123456789012", BarcodeFormat::UPC_A);
do_test("00393157", "00393157", BarcodeFormat::EAN_8);
do_test("5051140178499", "5051140178499", BarcodeFormat::EAN_13);
do_test("01234565", "012345000065", BarcodeFormat::UPC_E);
}
}
fn do_test( contents:&str, normalized:&str, format:BarcodeFormat) {
fn do_test(contents: &str, normalized: &str, format: BarcodeFormat) {
let fake_rxing_result = RXingResult::new(contents, Vec::new(), Vec::new(), format);
let result = ResultParser::parseRXingResult(&fake_rxing_result);
assert_eq!(ParsedRXingResultType::PRODUCT, result.getType());
@@ -48,10 +50,9 @@ use super::ResultParser;
if let ParsedClientResult::ProductResult(product_rxing_result) = result {
assert_eq!(contents, product_rxing_result.getProductID());
assert_eq!(normalized, product_rxing_result.getNormalizedProductID());
}else{
} 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};
@@ -30,11 +30,14 @@ use super::{ParsedClientResult, ProductParsedRXingResult, ResultParser};
* @author dswitkin@google.com (Daniel Switkin)
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
// 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,
};
/**
@@ -92,7 +93,7 @@ use super::{
pub type ParserFunction = dyn Fn(&RXingResult) -> Option<ParsedClientResult>;
lazy_static! {
static ref DIGITS :Regex = Regex::new("\\d+").unwrap();
static ref DIGITS: Regex = Regex::new("\\d+").unwrap();
}
// const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+");

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

@@ -32,10 +32,13 @@ use super::{ParsedClientResult, ResultParser, SMSParsedRXingResult};
*
* @author Sean Owen
*/
pub fn parse(result:&RXingResult) -> Option<ParsedClientResult> {
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:
@@ -37,10 +37,10 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let mut subject = "";
let mut body = "";
if let Some(colon) = emailAddress.find(':') {
subject = &emailAddress[colon+1..];
subject = &emailAddress[colon + 1..];
emailAddress = &emailAddress[..colon];
if let Some(new_colon) = subject.find(':') {
body = &subject[new_colon+1..];
body = &subject[new_colon + 1..];
subject = &subject[..new_colon];
}
}
@@ -54,10 +54,18 @@ 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,
// subject,
// body);
}
}

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.
@@ -29,21 +29,29 @@ use super::{TelParsedRXingResult, ParsedClientResult, ResultParser};
// impl RXingResultParser for TelRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult> {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(theRXingResult);
if !rawText.starts_with("tel:") && !rawText.starts_with("TEL:") {
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 {
&rawText[4..v+4]
}else {
&rawText[4..v + 4]
} else {
&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,
}
}
@@ -79,7 +79,7 @@ impl URIParsedRXingResult {
uri = format!("http://{}", &uri);
// uri = updated_uri.as_str()
}
}else {
} else {
uri = format!("http://{}", &uri);
}

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 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 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();
}
const ALLOWED_URI_CHARS_PATTERN: &'static str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+";
@@ -79,14 +82,13 @@ 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){
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) {
if fnd.start() == 0 && fnd.end() == uri.len() {
true
}else {
} else {
false
}
}else{
} else {
false
};
let user = USER_IN_HOST.is_match(uri);

View File

@@ -41,14 +41,15 @@ use uriparse::URI;
use super::{AddressBookParsedRXingResult, ParsedClientResult, ResultParser};
lazy_static! {
static ref BEGIN_VCARD :Regex= Regex::new("(?i:BEGIN:VCARD)").unwrap();
static ref VCARD_LIKE_DATE : Regex = Regex::new("\\d{4}-?\\d{2}-?\\d{2}").unwrap();
static ref CR_LF_SPACE_TAB : Regex = Regex::new("\r\n[ \t]").unwrap();
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 SEMICOLON_OR_COMMA : Regex = Regex::new("[;,]").unwrap();
static ref BEGIN_VCARD: Regex = Regex::new("(?i:BEGIN:VCARD)").unwrap();
static ref VCARD_LIKE_DATE: Regex = Regex::new("\\d{4}-?\\d{2}-?\\d{2}").unwrap();
static ref CR_LF_SPACE_TAB: Regex = Regex::new("\r\n[ \t]").unwrap();
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 SEMICOLON_OR_COMMA: Regex = Regex::new("[;,]").unwrap();
}
// const BEGIN_VCARD: &'static str = "(?i:BEGIN:VCARD)"; //, Pattern.CASE_INSENSITIVE);
@@ -262,7 +263,7 @@ pub fn matchVCardPrefixedField(
// if matches == null {
// matches = new ArrayList<>(1); // lazy init
// }
if i >= 1 && rawText.chars().nth(i as usize- 1)? == '\r' {
if i >= 1 && rawText.chars().nth(i as usize - 1)? == '\r' {
i -= 1; // Back up over \r, which really should be there
}
let mut element = rawText[matchStart as usize..i as usize].to_owned();
@@ -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

@@ -131,20 +131,20 @@ fn matchSingleVCardPrefixedField(prefix: &str, rawText: &str) -> String {
"".to_owned()
} else {
let tz_mod = if values.len() > 1 {
if let Some(v) = values.get(values.len()-2) {
if let Some(v) = values.get(values.len() - 2) {
if let Some(tz_loc) = v.find("TZID=") {
v[tz_loc+5..].to_owned()
}else {
v[tz_loc + 5..].to_owned()
} else {
"".to_owned()
}
}else {
} else {
"".to_owned()
}
}else {
} else {
"".to_owned()
};
let root_time = values.last().unwrap().clone();
format!("{}{}",root_time,tz_mod)
format!("{}{}", root_time, tz_mod)
}
} else {
"".to_owned()

View File

@@ -32,7 +32,7 @@ use super::ParsedClientResult;
use lazy_static::lazy_static;
lazy_static! {
static ref IOQ_MATCHER : Regex = Regex::new(IOQ).unwrap();
static ref IOQ_MATCHER: Regex = Regex::new(IOQ).unwrap();
static ref AZ09_MATCHER: Regex = Regex::new(AZ09).unwrap();
}

View File

@@ -27,74 +27,139 @@
* @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;
#[test]
fn testNoPassword() {
#[test]
fn testNoPassword() {
doTest("WIFI:S:NoPassword;P:;T:;;", "NoPassword", "", "nopass");
doTest("WIFI:S:No Password;P:;T:;;", "No Password", "", "nopass");
}
}
#[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");
#[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",
);
// 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.
}
}
/**
/**
* Put in checks for the length of the password for wep.
*/
#[test]
fn testWpa() {
#[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");
}
#[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",
);
}
/**
/**
* 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
assert_eq!(ParsedRXingResultType::WIFI, result.getType());
if let ParsedClientResult::WiFiResult(wifiRXingResult) = result{
if let ParsedClientResult::WiFiResult(wifiRXingResult) = result {
assert_eq!(ssid, wifiRXingResult.getSsid());
assert_eq!(password, wifiRXingResult.getPassword());
assert_eq!(n_type, wifiRXingResult.getNetworkEncryption());
}else {
} else {
panic!("Expected WIFI");
}
}
}
// }

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")
/**
@@ -43,22 +43,25 @@ use super::{ResultParser};
// pub struct WifiRXingResultParser {}
// impl RXingResultParser for WifiRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST : &'static str = "WIFI:";
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST: &'static str = "WIFI:";
let rawText_unstripped = ResultParser::getMassagedText(theRXingResult);
if !rawText_unstripped.starts_with(WIFI_TEST) {
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 {
} else {
String::from("nopass")
};
@@ -67,22 +70,38 @@ 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);
hidden = hv.parse().unwrap(); //Boolean.parseBoolean(hValue);
} else {
phase2Method = Some(hv.clone());
}
hv
}else {
} else {
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),
@@ -143,6 +143,6 @@ impl ParsedRXingResult for ParsedClientResult {
impl fmt::Display for ParsedClientResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f,"{}", self.getDisplayRXingResult())
write!(f, "{}", self.getDisplayRXingResult())
}
}

View File

@@ -29,8 +29,8 @@
use super::BitArray;
use rand::Rng;
#[test]
fn test_get_set() {
#[test]
fn test_get_set() {
let mut array = BitArray::with_size(33);
for i in 0..33 {
// for (int i = 0; i < 33; i++) {
@@ -38,44 +38,44 @@ use rand::Rng;
array.set(i);
assert!(array.get(i));
}
}
}
#[test]
fn test_get_next_set1() {
#[test]
fn test_get_next_set1() {
let array = BitArray::with_size(32);
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!( 32, array.getNextSet(i), "{}", i);
assert_eq!(32, array.getNextSet(i), "{}", i);
}
let array = BitArray::with_size(33);
for i in 0..array.getSize(){
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!( 33, array.getNextSet(i), "{}", i);
}
assert_eq!(33, array.getNextSet(i), "{}", i);
}
}
#[test]
fn test_get_next_set2() {
#[test]
fn test_get_next_set2() {
let mut array = BitArray::with_size(33);
array.set(31);
for i in 0 ..array.getSize() {
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(if i <= 31 { 31} else {33}, array.getNextSet(i), "{}", i);
assert_eq!(if i <= 31 { 31 } else { 33 }, array.getNextSet(i), "{}", i);
}
array = BitArray::with_size(33);
array.set(32);
for i in 0 ..array.getSize(){
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(32, array.getNextSet(i), "{}", i);
}
}
}
#[test]
fn test_get_next_set3() {
#[test]
fn test_get_next_set3() {
let mut array = BitArray::with_size(63);
array.set(31);
array.set(32);
for i in 0 .. array.getSize() {
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
let expected;
if i <= 31 {
@@ -87,14 +87,14 @@ use rand::Rng;
}
assert_eq!(expected, array.getNextSet(i), "{}", i);
}
}
}
#[test]
fn test_get_next_set4() {
#[test]
fn test_get_next_set4() {
let mut array = BitArray::with_size(63);
array.set(33);
array.set(40);
for i in 0..array.getSize(){
for i in 0..array.getSize() {
// for (int i = 0; i < array.getSize(); i++) {
let expected;
if i <= 33 {
@@ -104,14 +104,14 @@ use rand::Rng;
} else {
expected = 63;
}
assert_eq!( expected, array.getNextSet(i), "{}", i);
}
assert_eq!(expected, array.getNextSet(i), "{}", i);
}
}
#[test]
fn test_get_next_set5() {
#[test]
fn test_get_next_set5() {
let mut r = rand::thread_rng();
for _i in 0 .. 10 {
for _i in 0..10 {
// for (int i = 0; i < 10; i++) {
let mut array = BitArray::with_size(1 + r.gen_range(0..100));
let numSet = r.gen_range(0..20);
@@ -125,17 +125,16 @@ use rand::Rng;
let query = r.gen_range(0..array.getSize());
let mut expected = query;
while expected < array.getSize() && !array.get(expected) {
expected+=1;
expected += 1;
}
let actual = array.getNextSet(query);
assert_eq!(expected, actual);
}
}
}
}
#[test]
fn test_set_bulk() {
#[test]
fn test_set_bulk() {
let mut array = BitArray::with_size(64);
array.setBulk(32, 0xFFFF0000);
for i in 0..48 {
@@ -146,10 +145,10 @@ use rand::Rng;
// for (int i = 48; i < 64; i++) {
assert!(array.get(i));
}
}
}
#[test]
fn test_append_bit(){
#[test]
fn test_append_bit() {
let mut array = BitArray::new();
array.appendBits(0x000001E, 6).expect("must append)");
let mut array_2 = BitArray::new();
@@ -161,10 +160,10 @@ use rand::Rng;
array_2.appendBit(false);
assert_eq!(array, array_2)
}
}
#[test]
fn test_set_range() {
#[test]
fn test_set_range() {
let mut array = BitArray::with_size(64);
array.setRange(28, 36).unwrap();
assert!(!array.get(27));
@@ -173,10 +172,10 @@ use rand::Rng;
assert!(array.get(i));
}
assert!(!array.get(36));
}
}
#[test]
fn test_clear() {
#[test]
fn test_clear() {
let mut array = BitArray::with_size(32);
for i in 0..32 {
// for (int i = 0; i < 32; i++) {
@@ -187,30 +186,30 @@ use rand::Rng;
// for (int i = 0; i < 32; i++) {
assert!(!array.get(i));
}
}
}
#[test]
fn test_flip() {
#[test]
fn test_flip() {
let mut array = BitArray::with_size(32);
assert!(!array.get(5));
array.flip(5);
assert!(array.get(5));
array.flip(5);
assert!(!array.get(5));
}
}
#[test]
fn test_get_array() {
#[test]
fn test_get_array() {
let mut array = BitArray::with_size(64);
array.set(0);
array.set(63);
let ints = array.getBitArray();
assert_eq!(1, ints[0]);
assert_eq!(0b10_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00, ints[1]);
}
}
#[test]
fn test_is_range() {
#[test]
fn test_is_range() {
let mut array = BitArray::with_size(64);
assert!(array.isRange(0, 64, false).unwrap());
assert!(!array.isRange(0, 64, true).unwrap());
@@ -231,30 +230,34 @@ use rand::Rng;
}
assert!(array.isRange(0, 64, true).unwrap());
assert!(!array.isRange(0, 64, false).unwrap());
}
}
#[test]
fn reverse_algorithm_test() {
let oldBits:Vec<u32> = vec![128, 256, 512, 6453324, 50934953];
#[test]
fn reverse_algorithm_test() {
let oldBits: Vec<u32> = vec![128, 256, 512, 6453324, 50934953];
for size in 1..160 {
// for (int size = 1; size < 160; size++) {
let newBitsOriginal = reverse_original(&oldBits.clone(), size);
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
));
}
}
#[test]
fn test_clone() {
#[test]
fn test_clone() {
let array = BitArray::with_size(32);
array.clone().set(0);
assert!(!array.get(0));
}
}
#[test]
fn test_equals() {
#[test]
fn test_equals() {
let mut a = BitArray::with_size(32);
let mut b = BitArray::with_size(32);
assert_eq!(a, b);
@@ -266,10 +269,10 @@ use rand::Rng;
b.set(16);
assert_eq!(a, b);
// assert_eq!(a.hash(), b.hash());
}
}
fn reverse_original( oldBits:&[u32], size:usize) -> Vec<u32>{
let mut newBits = vec![0;oldBits.len()];
fn reverse_original(oldBits: &[u32], size: usize) -> Vec<u32> {
let mut newBits = vec![0; oldBits.len()];
for i in 0..size {
// for (int i = 0; i < size; i++) {
if bit_set(oldBits, size - i - 1) {
@@ -277,13 +280,13 @@ use rand::Rng;
}
}
return newBits;
}
}
fn bit_set( bits:&[u32], i:usize) -> bool{
fn bit_set(bits: &[u32], i: usize) -> bool {
return (bits[i / 32] & (1 << (i & 0x1F))) != 0;
}
}
fn arrays_are_equal( left :&[u32], right:&[u32], size:usize) -> bool{
fn arrays_are_equal(left: &[u32], right: &[u32], size: usize) -> bool {
for i in 0..size {
// for (int i = 0; i < size; i++) {
if left[i] != right[i] {
@@ -291,6 +294,6 @@ use rand::Rng;
}
}
return true;
}
}
// }

View File

@@ -31,10 +31,10 @@ use crate::common::BitArray;
use super::BitMatrix;
static BIT_MATRIX_POINTS : [u32;6] = [ 1, 2, 2, 0, 3, 1 ];
static BIT_MATRIX_POINTS: [u32; 6] = [1, 2, 2, 0, 3, 1];
#[test]
fn test_get_set() {
#[test]
fn test_get_set() {
let mut matrix = BitMatrix::with_single_dimension(33);
assert_eq!(33, matrix.getHeight());
for y in 0..33 {
@@ -53,51 +53,51 @@ use super::BitMatrix;
assert_eq!(y * x % 3 == 0, matrix.get(x, y));
}
}
}
}
#[test]
fn test_set_region() {
#[test]
fn test_set_region() {
let mut matrix = BitMatrix::with_single_dimension(5);
matrix.setRegion(1, 1, 3, 3).expect("must set");
for y in 0..5 {
// for (int y = 0; y < 5; y++) {
for x in 0..5{
for x in 0..5 {
// for (int x = 0; x < 5; x++) {
assert_eq!(y >= 1 && y <= 3 && x >= 1 && x <= 3, matrix.get(x, y));
}
}
}
}
#[test]
fn test_enclosing() {
#[test]
fn test_enclosing() {
let mut matrix = BitMatrix::with_single_dimension(5);
assert!(matrix.getEnclosingRectangle().is_none());
matrix.setRegion(1, 1, 1, 1).expect("must set");
assert_eq!(vec![ 1, 1, 1, 1 ], matrix.getEnclosingRectangle().unwrap());
assert_eq!(vec![1, 1, 1, 1], matrix.getEnclosingRectangle().unwrap());
matrix.setRegion(1, 1, 3, 2).expect("must set");
assert_eq!(vec![ 1, 1, 3, 2 ], matrix.getEnclosingRectangle().unwrap());
assert_eq!(vec![1, 1, 3, 2], matrix.getEnclosingRectangle().unwrap());
matrix.setRegion(0, 0, 5, 5).expect("must set");
assert_eq!(vec![ 0, 0, 5, 5 ], matrix.getEnclosingRectangle().unwrap());
}
assert_eq!(vec![0, 0, 5, 5], matrix.getEnclosingRectangle().unwrap());
}
#[test]
fn test_on_bit() {
#[test]
fn test_on_bit() {
let mut matrix = BitMatrix::with_single_dimension(5);
assert!(matrix.getTopLeftOnBit().is_none());
assert!(matrix.getBottomRightOnBit().is_none());
matrix.setRegion(1, 1, 1, 1).expect("must set");
assert_eq!(vec![ 1, 1 ], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![ 1, 1 ], matrix.getBottomRightOnBit().unwrap());
assert_eq!(vec![1, 1], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![1, 1], matrix.getBottomRightOnBit().unwrap());
matrix.setRegion(1, 1, 3, 2).expect("must set");
assert_eq!(vec![ 1, 1 ], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![ 3, 2 ], matrix.getBottomRightOnBit().unwrap());
assert_eq!(vec![1, 1], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![3, 2], matrix.getBottomRightOnBit().unwrap());
matrix.setRegion(0, 0, 5, 5).expect("must set");
assert_eq!(vec![ 0, 0 ], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![ 4, 4 ], matrix.getBottomRightOnBit().unwrap());
}
assert_eq!(vec![0, 0], matrix.getTopLeftOnBit().unwrap());
assert_eq!(vec![4, 4], matrix.getBottomRightOnBit().unwrap());
}
#[test]
fn test_rectangular_matrix() {
#[test]
fn test_rectangular_matrix() {
let mut matrix = BitMatrix::new(75, 20).unwrap();
assert_eq!(75, matrix.getWidth());
assert_eq!(20, matrix.getHeight());
@@ -121,10 +121,10 @@ use super::BitMatrix;
matrix.flip_coords(51, 3);
assert!(!matrix.get(50, 2));
assert!(!matrix.get(51, 3));
}
}
#[test]
fn test_rectangular_set_region() {
#[test]
fn test_rectangular_set_region() {
let mut matrix = BitMatrix::new(320, 240).unwrap();
assert_eq!(320, matrix.getWidth());
assert_eq!(240, matrix.getHeight());
@@ -133,15 +133,15 @@ use super::BitMatrix;
// Only bits in the region should be on
for y in 0..240 {
// for (int y = 0; y < 240; y++) {
for x in 0..320{
for x in 0..320 {
// for (int x = 0; x < 320; x++) {
assert_eq!(y >= 22 && y < 34 && x >= 105 && x < 185, matrix.get(x, y));
}
}
}
}
#[test]
fn test_get_row() {
#[test]
fn test_get_row() {
let mut matrix = BitMatrix::new(102, 5).unwrap();
for x in 0..102 {
// for (int x = 0; x < 102; x++) {
@@ -171,10 +171,10 @@ use super::BitMatrix;
assert_eq!(on, array2.get(x));
assert_eq!(on, array3.get(x));
}
}
}
#[test]
fn test_rotate90_simple() {
#[test]
fn test_rotate90_simple() {
let mut matrix = BitMatrix::new(3, 3).unwrap();
matrix.set(0, 0);
matrix.set(0, 1);
@@ -187,10 +187,10 @@ use super::BitMatrix;
assert!(matrix.get(1, 2));
assert!(matrix.get(2, 1));
assert!(matrix.get(1, 0));
}
}
#[test]
fn test_rotate180_simple() {
#[test]
fn test_rotate180_simple() {
let mut matrix = BitMatrix::new(3, 3).unwrap();
matrix.set(0, 0);
matrix.set(0, 1);
@@ -203,18 +203,18 @@ use super::BitMatrix;
assert!(matrix.get(2, 1));
assert!(matrix.get(1, 0));
assert!(matrix.get(0, 1));
}
}
#[test]
fn test_rotate180_case() {
#[test]
fn test_rotate180_case() {
test_rotate_180(7, 4);
test_rotate_180(7, 5);
test_rotate_180(8, 4);
test_rotate_180(8, 5);
}
}
#[test]
fn test_parse() {
#[test]
fn test_parse() {
let emptyMatrix = BitMatrix::new(3, 3).unwrap();
let mut fullMatrix = BitMatrix::new(3, 3).unwrap();
fullMatrix.setRegion(0, 0, 3, 3).expect("must set");
@@ -222,25 +222,48 @@ 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]
fn test_parse_boolean() {
#[test]
fn test_parse_boolean() {
let emptyMatrix = BitMatrix::new(3, 3).unwrap();
let mut fullMatrix = BitMatrix::new(3, 3).unwrap();
fullMatrix.setRegion(0, 0, 3, 3).expect("must set");
@@ -248,7 +271,7 @@ use super::BitMatrix;
centerMatrix.setRegion(1, 1, 1, 1).expect("must set");
let emptyMatrix24 = BitMatrix::new(2, 4).unwrap();
let mut matrix = vec![vec![false;3];3];
let mut matrix = vec![vec![false; 3]; 3];
// boolean[][] matrix = new boolean[3][3];
assert_eq!(emptyMatrix, BitMatrix::parse_bools(&matrix));
matrix[1][1] = true;
@@ -258,10 +281,10 @@ use super::BitMatrix;
arr[..].clone_from_slice(&[true, true, true])
}
assert_eq!(fullMatrix, BitMatrix::parse_bools(&matrix));
}
}
#[test]
fn test_unset() {
#[test]
fn test_unset() {
let emptyMatrix = BitMatrix::new(3, 3).unwrap();
let mut matrix = emptyMatrix.clone();
matrix.set(1, 1);
@@ -270,10 +293,10 @@ use super::BitMatrix;
assert_eq!(emptyMatrix, matrix);
matrix.unset(1, 1);
assert_eq!(emptyMatrix, matrix);
}
}
#[test]
fn test_xor_case() {
#[test]
fn test_xor_case() {
let emptyMatrix = BitMatrix::new(3, 3).unwrap();
let mut fullMatrix = BitMatrix::new(3, 3).unwrap();
fullMatrix.setRegion(0, 0, 3, 3).expect("must set");
@@ -314,58 +337,61 @@ use super::BitMatrix;
// } catch (IllegalArgumentException ex) {
// // good
// }
}
}
fn matrix_to_string( result:&BitMatrix) -> String{
fn matrix_to_string(result: &BitMatrix) -> String {
assert_eq!(1, result.getHeight());
let mut builder = String::with_capacity(result.getWidth().try_into().unwrap());
for i in 0..result.getWidth() {
// for (int i = 0; i < result.getWidth(); i++) {
builder.push(if result.get(i, 0) {'1'} else {'0'});
builder.push(if result.get(i, 0) { '1' } else { '0' });
}
return builder;
}
}
fn test_XOR( dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) {
fn test_XOR(dataMatrix: &BitMatrix, flipMatrix: &BitMatrix, expectedMatrix: &BitMatrix) {
let mut matrix = dataMatrix.clone();
matrix.xor(flipMatrix).expect("must set");
assert_eq!(*expectedMatrix, matrix);
}
}
fn test_rotate_180( width:u32, height:u32) {
fn test_rotate_180(width: u32, height: u32) {
let mut input = get_input(width, height);
input.rotate180();
let expected = get_expected(width, height);
for y in 0..height{
for y in 0..height {
// for (int y = 0; y < height; y++) {
for x in 0..width{
for x in 0..width {
// for (int x = 0; x < width; x++) {
assert_eq!( expected.get(x, y), input.get(x, y), "({},{})", x, y);
}
assert_eq!(expected.get(x, y), input.get(x, y), "({},{})", x, y);
}
}
}
fn get_expected( width:u32, height:u32) -> BitMatrix{
fn get_expected(width: u32, height: u32) -> BitMatrix {
let mut result = BitMatrix::new(width, height).unwrap();
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;
}
}
fn get_input( width:u32, height:u32) -> BitMatrix{
fn get_input(width: u32, height: u32) -> BitMatrix {
let mut result = BitMatrix::new(width, height).unwrap();
let mut i = 0;
while i < BIT_MATRIX_POINTS.len(){
while i < BIT_MATRIX_POINTS.len() {
// for (int i = 0; i < BIT_MATRIX_POINTS.length; i += 2) {
result.set(BIT_MATRIX_POINTS[i], BIT_MATRIX_POINTS[i + 1]);
i+=2;
i += 2;
}
return result;
}
}
// }

View File

@@ -26,9 +26,9 @@
use super::BitSource;
#[test]
fn test_source() {
let bytes:Vec<u8> = vec![ 1, 2, 3, 4, 5];
#[test]
fn test_source() {
let bytes: Vec<u8> = vec![1, 2, 3, 4, 5];
let mut source = BitSource::new(bytes);
assert_eq!(40, source.available());
assert_eq!(0, source.readBits(1).unwrap());
@@ -45,6 +45,6 @@ use super::BitSource;
assert_eq!(6, source.available());
assert_eq!(5, source.readBits(6).unwrap());
assert_eq!(0, source.available());
}
}
// }

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(),
}
}
/**
@@ -50,7 +52,7 @@ impl MonochromeRectangleDetector {
pub fn detect(&self) -> Result<Vec<RXingResultPoint>, Exceptions> {
let height = self.image.getHeight() as i32;
let width = self.image.getWidth() as i32;
let halfHeight= height / 2;
let halfHeight = height / 2;
let halfWidth = width / 2;
let deltaY = 1.max(height as i32 / (MAX_MODULES * 8));
let deltaX = 1.max(width as i32 / (MAX_MODULES * 8));
@@ -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;
@@ -81,7 +75,7 @@ impl WhiteRectangleDetector {
return Err(Exceptions::NotFoundException("".to_owned()));
}
Ok(Self{
Ok(Self {
image: image.clone(),
height: image.getHeight() as i32,
width: image.getWidth() as i32,
@@ -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;
@@ -141,7 +141,7 @@ impl ECIInput for MinimalECIInput {
if index >= self.length() as u32 {
return Err(Exceptions::IndexOutOfBoundsException(index.to_string()));
}
Ok(self.bytes[index as usize] > 255)// && self.bytes[index as usize] <= u16::MAX)
Ok(self.bytes[index as usize] > 255) // && self.bytes[index as usize] <= u16::MAX)
}
/**
@@ -383,7 +383,7 @@ impl MinimalECIInput {
}
}
struct InputEdge {
struct InputEdge {
c: String,
encoderIndex: usize, //the encoding of this edge
previous: Option<Rc<InputEdge>>,

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

@@ -1,6 +1,6 @@
use std::{error::Error, fmt};
#[derive(Debug,PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq)]
pub enum Exceptions {
IllegalArgumentException(String),
UnsupportedOperationException(String),

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

@@ -16,40 +16,139 @@
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]
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,
],
];
/**
@@ -59,16 +158,15 @@ const BITNR : [[i16;30];33] = [
pub struct BitMatrixParser(BitMatrix);
impl BitMatrixParser {
/**
* @param bitMatrix {@link BitMatrix} to parse
*/
pub fn new( bitMatrix: BitMatrix) -> Self{
pub fn new(bitMatrix: BitMatrix) -> Self {
Self(bitMatrix)
}
pub fn readCodewords(&self) -> [u8;144] {
let mut result = [0u8;144];
pub fn readCodewords(&self) -> [u8; 144] {
let mut result = [0u8; 144];
let height = self.0.getHeight() as usize;
let width = self.0.getWidth() as usize;
for y in 0..height {
@@ -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,57 +14,97 @@
* 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;
const MASKED_TEST_FORMAT_INFO : u32 = 0x2BED;
const UNMASKED_TEST_FORMAT_INFO : u32= MASKED_TEST_FORMAT_INFO ^ 0x5412;
#[test]
fn testBitsDiffering() {
#[test]
fn testBitsDiffering() {
assert_eq!(0, FormatInformation::numBitsDiffering(1, 1));
assert_eq!(1, FormatInformation::numBitsDiffering(0, 2));
assert_eq!(2, FormatInformation::numBitsDiffering(1, 2));
assert_eq!(32, FormatInformation::numBitsDiffering(-1i32 as u32, 0));
}
}
#[test]
fn testDecode() {
#[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!(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();
#[test]
fn testDecodeWithBitDifference() {
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());
}
#[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()
);
}

View File

@@ -18,34 +18,50 @@ use crate::qrcode::decoder::Version;
use super::Mode;
/**
* @author Sean Owen
*/
#[test]
fn testForBits() {
#[test]
fn testForBits() {
assert_eq!(Mode::TERMINATOR, Mode::forBits(0x00).unwrap());
assert_eq!(Mode::NUMERIC, Mode::forBits(0x01).unwrap());
assert_eq!(Mode::ALPHANUMERIC, Mode::forBits(0x02).unwrap());
assert_eq!(Mode::BYTE, Mode::forBits(0x04).unwrap());
assert_eq!(Mode::KANJI, Mode::forBits(0x08).unwrap());
}
}
#[test]
#[should_panic]
fn testBadMode() {
#[test]
#[should_panic]
fn testBadMode() {
assert!(Mode::forBits(0x10).is_ok());
}
}
#[test]
fn testCharacterCount() {
#[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,29 +14,30 @@
* 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() {
#[test]
#[should_panic]
fn testBadVersion() {
assert!(Version::getVersionForNumber(0).is_ok());
}
}
#[test]
fn testVersionForNumber() {
#[test]
fn testVersionForNumber() {
for i in 1..=40 {
// for (int i = 1; i <= 40; i++) {
checkVersion(Version::getVersionForNumber(i), i, 4 * i + 17);
}
}
}
fn checkVersion( version:Result<&Version,Exceptions>, number:u32, dimension:u32) {
fn checkVersion(version: Result<&Version, Exceptions>, number: u32, dimension: u32) {
assert!(version.is_ok());
let version = version.unwrap();
assert_eq!(number, version.getVersionNumber());
@@ -56,18 +57,23 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions};
// assertNotNull(version.getECBlocksForLevel(ErrorCorrectionLevel::M));
// assertNotNull(version.getECBlocksForLevel(ErrorCorrectionLevel::Q));
// assertNotNull(version.buildFunctionPattern());
}
}
#[test]
fn testGetProvisionalVersionForDimension() {
#[test]
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()
);
}
}
#[test]
fn testDecodeVersionInformation() {
#[test]
fn testDecodeVersionInformation() {
// Spot check
doTestVersion(7, 0x07C94);
doTestVersion(12, 0x0C762);
@@ -75,11 +81,10 @@ use crate::{qrcode::decoder::{Version, ErrorCorrectionLevel}, Exceptions};
doTestVersion(22, 0x168C9);
doTestVersion(27, 0x1B08E);
doTestVersion(32, 0x209D5);
}
}
fn doTestVersion( expectedVersion:u32, mask:u32) {
fn doTestVersion(expectedVersion: u32, mask: u32) {
let version = Version::decodeVersionInformation(mask);
assert!(version.is_ok());
assert_eq!(expectedVersion, version.unwrap().getVersionNumber());
}
}

View File

@@ -82,7 +82,7 @@ impl BitMatrixParser {
let dimension = self.bitMatrix.getHeight();
let mut formatInfoBits2 = 0;
let jMin = dimension - 7;
for j in (jMin..=dimension-1).rev() {
for j in (jMin..=dimension - 1).rev() {
// for (int j = dimension - 1; j >= jMin; j--) {
formatInfoBits2 = self.copyBit(8, j, formatInfoBits2);
}

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,15 +26,13 @@ use super::{VersionRef, ErrorCorrectionLevel};
* @author Sean Owen
*/
pub struct DataBlock {
numDataCodewords:u32,
codewords:Vec<u8>,
numDataCodewords: u32,
codewords: Vec<u8>,
}
impl DataBlock {
fn new( numDataCodewords:u32, codewords:Vec<u8>) -> Self{
Self{
fn new(numDataCodewords: u32, codewords: Vec<u8>) -> Self {
Self {
numDataCodewords,
codewords,
}
@@ -51,12 +49,13 @@ impl DataBlock {
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* QR Code
*/
pub fn getDataBlocks( rawCodewords:&[u8],
version:VersionRef,
ecLevel:ErrorCorrectionLevel) -> Result<Vec<Self>,Exceptions> {
pub fn getDataBlocks(
rawCodewords: &[u8],
version: VersionRef,
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;
}
}
@@ -96,11 +98,12 @@ impl DataBlock {
if numCodewords == shorterBlocksTotalCodewords {
break;
}
longerBlocksStartAt-=1;
longerBlocksStartAt -= 1;
}
longerBlocksStartAt+=1;
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;
@@ -113,7 +116,7 @@ impl DataBlock {
}
}
// Fill out the last data block in the longer ones
for j in longerBlocksStartAt..numRXingResultBlocks{
for j in longerBlocksStartAt..numRXingResultBlocks {
// for (int j = longerBlocksStartAt; j < numRXingResultBlocks; j++) {
result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
@@ -124,7 +127,7 @@ impl DataBlock {
// for (int i = shorterBlocksNumDataCodewords; i < max; i++) {
for j in 0..numRXingResultBlocks {
// for (int j = 0; j < numRXingResultBlocks; j++) {
let iOffset = if j < longerBlocksStartAt {i} else {i + 1};
let iOffset = if j < longerBlocksStartAt { i } else { i + 1 };
result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset];
rawCodewordsOffset += 1;
}
@@ -132,12 +135,11 @@ impl DataBlock {
Ok(result)
}
pub fn getNumDataCodewords(&self) -> u32{
self. numDataCodewords
pub fn getNumDataCodewords(&self) -> u32 {
self.numDataCodewords
}
pub fn getCodewords(&self) -> &[u8] {
&self.codewords
}
}

View File

@@ -27,7 +27,7 @@ use crate::{common::BitMatrix, Exceptions};
*
* @author Sean Owen
*/
#[derive(Copy,Clone,Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum DataMask {
// See ISO 18004:2006 6.8.1
/**
@@ -222,15 +222,18 @@ impl TryFrom<u8> for DataMask {
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0=>Ok(DataMask::DATA_MASK_000),
1=>Ok(DataMask::DATA_MASK_001),
2=>Ok(DataMask::DATA_MASK_010),
3=>Ok(DataMask::DATA_MASK_011),
4=>Ok(DataMask::DATA_MASK_100),
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))),
0 => Ok(DataMask::DATA_MASK_000),
1 => Ok(DataMask::DATA_MASK_001),
2 => Ok(DataMask::DATA_MASK_010),
3 => Ok(DataMask::DATA_MASK_011),
4 => Ok(DataMask::DATA_MASK_100),
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
))),
}
}
}

View File

@@ -286,14 +286,16 @@ 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;
String::borrow_from_cp437(&readBytes, &CP437_CONTROL)
}
}else {
} else {
encoding
.decode(&readBytes, encoding::DecoderTrap::Strict)
.unwrap()

View File

@@ -198,7 +198,7 @@ fn correctErrors(codewordBytes: &mut [u8], numDataCodewords: usize) -> Result<()
codewordsInts[i] = codewordBytes[i]; // & 0xFF;
}
let mut sending_code_words : Vec<i32> = codewordsInts.iter().map(|x| *x as i32).collect();
let mut sending_code_words: Vec<i32> = codewordsInts.iter().map(|x| *x as i32).collect();
if let Err(e) = RS_DECODER.decode(
&mut sending_code_words,

View File

@@ -88,15 +88,15 @@ impl From<ErrorCorrectionLevel> for u8 {
}
impl FromStr for ErrorCorrectionLevel {
type Err=Exceptions;
type Err = Exceptions;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// First try to see if the string is just the name of the value
let as_str = match s.to_uppercase().as_str() {
"L" => Some(ErrorCorrectionLevel::L),
"M" => Some(ErrorCorrectionLevel::M),
"Q" =>Some(ErrorCorrectionLevel::Q),
"H" =>Some(ErrorCorrectionLevel::H),
"Q" => Some(ErrorCorrectionLevel::Q),
"H" => Some(ErrorCorrectionLevel::H),
_ => None,
};
@@ -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

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