Implement clippy suggestions

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

View File

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

View File

@@ -37,7 +37,7 @@ fn testAddressBookDocomo() {
doTest(
"MECARD:N:Sean Owen;;",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&Vec::new(),
&Vec::new(),
@@ -51,14 +51,14 @@ fn testAddressBookDocomo() {
doTest(
"MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;;",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&Vec::new(),
&vec!["srowen@example.org"],
&["srowen@example.org"],
&Vec::new(),
&Vec::new(),
"",
&vec!["google.com"],
&["google.com"],
"",
"ZXing Team",
);
@@ -69,11 +69,11 @@ fn testAddressBookAU() {
doTest(
"MEMORY:foo\r\nNAME1:Sean\r\nTEL1:+12125551212\r\n",
"",
&vec!["Sean"],
&["Sean"],
"",
&Vec::new(),
&Vec::new(),
&vec!["+12125551212"],
&["+12125551212"],
&Vec::new(),
"",
&Vec::new(),
@@ -87,9 +87,9 @@ fn testVCard() {
doTest(
"BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&vec!["123 Main St"],
&["123 Main St"],
&Vec::new(),
&Vec::new(),
&Vec::new(),
@@ -105,7 +105,7 @@ fn testVCardFullN() {
doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;T;Mr.;Esq.\r\nEND:VCARD",
"",
&vec!["Mr. Sean T Owen Esq."],
&["Mr. Sean T Owen Esq."],
"",
&Vec::new(),
&Vec::new(),
@@ -123,7 +123,7 @@ fn testVCardFullN2() {
doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;;;\r\nEND:VCARD",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&Vec::new(),
&Vec::new(),
@@ -141,7 +141,7 @@ fn testVCardFullN3() {
doTest(
"BEGIN:VCARD\r\nVERSION:2.1\r\nN:;Sean;;;\r\nEND:VCARD",
"",
&vec!["Sean"],
&["Sean"],
"",
&Vec::new(),
&Vec::new(),
@@ -159,9 +159,9 @@ fn testVCardCaseInsensitive() {
doTest(
"begin:vcard\r\nadr;HOME:123 Main St\r\nVersion:2.1\r\nn:Owen;Sean\r\nEND:VCARD",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&vec!["123 Main St"],
&["123 Main St"],
&Vec::new(),
&Vec::new(),
&Vec::new(),
@@ -175,7 +175,7 @@ fn testVCardCaseInsensitive() {
#[test]
fn testEscapedVCard() {
doTest("BEGIN:VCARD\r\nADR;HOME:123\\;\\\\ Main\\, St\\nHome\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD",
"", &vec!["Sean Owen"], "", &vec!["123;\\ Main, St\nHome"],
"", &["Sean Owen"], "", &["123;\\ Main, St\nHome"],
&Vec::new(), &Vec::new(), &Vec::new(), "", &Vec::new(), "", "");
}
@@ -184,11 +184,11 @@ fn testBizcard() {
doTest(
"BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12125551212;E:srowen@example.org;",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&vec!["123 Main St"],
&vec!["srowen@example.org"],
&vec!["+12125551212"],
&["123 Main St"],
&["srowen@example.org"],
&["+12125551212"],
&Vec::new(),
"Google",
&Vec::new(),
@@ -200,9 +200,9 @@ fn testBizcard() {
#[test]
fn testSeveralAddresses() {
doTest("MECARD:N:Foo Bar;ORG:Company;TEL:5555555555;EMAIL:foo.bar@xyz.com;ADR:City, 10001;ADR:City, 10001;NOTE:This is the memo.;;",
"", &vec!["Foo Bar"], "", &vec!["City, 10001", "City, 10001"],
&vec!["foo.bar@xyz.com"],
&vec!["5555555555" ], &Vec::new(), "Company", &Vec::new(), "", "This is the memo.");
"", &["Foo Bar"], "", &["City, 10001", "City, 10001"],
&["foo.bar@xyz.com"],
&["5555555555"], &Vec::new(), "Company", &Vec::new(), "", "This is the memo.");
}
#[test]
@@ -212,7 +212,7 @@ fn testQuotedPrintable() {
"",
&Vec::new(),
"",
&vec!["88 Lynbrook\r\nCO 69999"],
&["88 Lynbrook\r\nCO 69999"],
&Vec::new(),
&Vec::new(),
&Vec::new(),
@@ -292,8 +292,8 @@ fn testVCardValueURI() {
"",
&Vec::new(),
&Vec::new(),
&vec!["+1-555-555-1212"],
&vec![""],
&["+1-555-555-1212"],
&[""],
"",
&Vec::new(),
"",
@@ -303,7 +303,7 @@ fn testVCardValueURI() {
doTest(
"BEGIN:VCARD\r\nN;VALUE=text:Owen;Sean\r\nEND:VCARD",
"",
&vec!["Sean Owen"],
&["Sean Owen"],
"",
&Vec::new(),
&Vec::new(),
@@ -325,8 +325,8 @@ fn testVCardTypes() {
"",
&Vec::new(),
&Vec::new(),
&vec!["10", "20", "30"],
&vec!["WORK", "", "CELL"],
&["10", "20", "30"],
&["WORK", "", "CELL"],
"",
&Vec::new(),
"",

View File

@@ -120,11 +120,9 @@ fn buildPhoneNumbers(number1: String, number2: String, number3: String) -> Vec<S
fn buildName(firstName: &str, lastName: &str) -> String {
if firstName.is_empty() {
lastName.to_owned()
} else if lastName.is_empty() {
firstName.to_owned()
} else {
if lastName.is_empty() {
firstName.to_owned()
} else {
format!("{} {}", firstName, lastName)
}
format!("{} {}", firstName, lastName)
}
}

View File

@@ -32,14 +32,12 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
}
let title = ResultParser::match_single_do_co_mo_prefixed_field("TITLE:", rawText, true);
let rawUri = ResultParser::match_do_co_mo_prefixed_field("URL:", rawText);
if rawUri.is_none() {
return None;
}
rawUri.as_ref()?;
let uri = rawUri?[0].clone();
if URIResultParser::is_basically_valid_uri(&uri) {
Some(ParsedClientResult::URIResult(URIParsedRXingResult::new(
uri,
title.unwrap_or("".to_owned()),
title.unwrap_or_else(|| "".to_owned()),
)))
} else {
None

View File

@@ -120,8 +120,6 @@ impl CalendarParsedRXingResult {
} else {
Self::parseDate(endString.clone())?
};
let startAllDay;
let endAllDay;
// try {
// this.start = parseDate(startString);
@@ -140,8 +138,8 @@ impl CalendarParsedRXingResult {
// }
// }
startAllDay = startString.len() == 8;
endAllDay = !endString.is_empty() && endString.len() == 8;
let startAllDay = startString.len() == 8;
let endAllDay = !endString.is_empty() && endString.len() == 8;
Ok(Self {
summary,
@@ -168,7 +166,7 @@ impl CalendarParsedRXingResult {
fn parseDate(when: String) -> Result<i64, Exceptions> {
// let date_time_regex = Regex::new(DATE_TIME).unwrap();
if !DATE_TIME.is_match(&when) {
return Err(Exceptions::ParseException(when));
return Err(Exceptions::ParseException(Some(when)));
}
if when.len() == 8 {
// Show only year/month/day
@@ -196,10 +194,10 @@ impl CalendarParsedRXingResult {
if when.len() == 16 && when.chars().nth(15).unwrap() == 'Z' {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%SZ") {
Ok(dtm) => Ok(dtm.with_timezone(&Utc).timestamp()),
Err(e) => Err(Exceptions::ParseException(format!(
Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse string: {}",
e
))),
)))),
};
// let dtm = DateTime::parse_from_str(&when, "%Y%m%dT%H%M%S").unwrap().with_timezone(&Utc);
// //let milliseconds = Self::parseDateTimeString(&when[0..15]);
@@ -219,18 +217,18 @@ impl CalendarParsedRXingResult {
let tz_parsed: Tz = match tz_part.parse() {
Ok(time_zone) => time_zone,
Err(e) => {
return Err(Exceptions::ParseException(format!(
return Err(Exceptions::ParseException(Some(format!(
"couldn't parse timezone '{}': {}",
tz_part, e
)))
))))
}
};
return match Utc.datetime_from_str(time_part, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.with_timezone(&tz_parsed).timestamp()),
Err(e) => Err(Exceptions::ParseException(format!(
Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse string: {}",
e
))),
)))),
};
}
@@ -238,10 +236,10 @@ impl CalendarParsedRXingResult {
if when.len() == 15 {
return match Utc.datetime_from_str(&when, "%Y%m%dT%H%M%S") {
Ok(dtm) => Ok(dtm.timestamp()),
Err(e) => Err(Exceptions::ParseException(format!(
Err(e) => Err(Exceptions::ParseException(Some(format!(
"couldn't parse local time: {}",
e
))),
)))),
};
}
Self::parseDateTimeString(&when)
@@ -270,12 +268,13 @@ impl CalendarParsedRXingResult {
// let regex = Regex::new(RFC2445_DURATION).unwrap();
if let Some(m) = RFC2445_DURATION.captures(durationString) {
let mut durationMS = 0i64;
for i in 0..RFC2445_DURATION_FIELD_UNITS.len() {
for (i, unit) in RFC2445_DURATION_FIELD_UNITS.iter().enumerate() {
// for i in 0..RFC2445_DURATION_FIELD_UNITS.len() {
// for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.length; i++) {
let fieldValue = m.get(i + 1);
if fieldValue.is_some() {
let z = fieldValue.unwrap().as_str().parse::<i64>().unwrap();
durationMS += RFC2445_DURATION_FIELD_UNITS[i] * z;
if let Some(parseable) = fieldValue {
let z = parseable.as_str().parse::<i64>().unwrap();
durationMS += unit * z;
}
}
durationMS
@@ -299,10 +298,10 @@ impl CalendarParsedRXingResult {
if let Ok(dtm) = DateTime::parse_from_str(dateTimeString, "%Y%m%dT%H%M%S") {
Ok(dtm.timestamp())
} else {
Err(Exceptions::ParseException(format!(
Err(Exceptions::ParseException(Some(format!(
"Couldn't parse {}",
dateTimeString
)))
))))
}
// DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
// return format.parse(dateTimeString).getTime();

View File

@@ -150,7 +150,7 @@ fn testAttendees() {
doTest(
"BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20080504T123456Z\r\nATTENDEE:mailto:bob@example.org\r\nATTENDEE:mailto:alice@example.org\r\nEND:VEVENT\r\nEND:VCALENDAR",
"", "", "", "20080504T123456Z", "", "",
&vec!["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN);
&["bob@example.org", "alice@example.org"], f64::NAN, f64::NAN);
}
#[test]

View File

@@ -42,7 +42,7 @@ fn testEmailAddress() {
fn testTos() {
do_test(
"mailto:srowen@example.org,bob@example.org",
&vec!["srowen@example.org", "bob@example.org"],
&["srowen@example.org", "bob@example.org"],
&Vec::new(),
&Vec::new(),
"",
@@ -50,7 +50,7 @@ fn testTos() {
);
do_test(
"mailto:?to=srowen@example.org,bob@example.org",
&vec!["srowen@example.org", "bob@example.org"],
&["srowen@example.org", "bob@example.org"],
&Vec::new(),
&Vec::new(),
"",
@@ -63,7 +63,7 @@ fn testCCs() {
do_test(
"mailto:?cc=srowen@example.org",
&Vec::new(),
&vec!["srowen@example.org"],
&["srowen@example.org"],
&Vec::new(),
"",
"",
@@ -71,7 +71,7 @@ fn testCCs() {
do_test(
"mailto:?cc=srowen@example.org,bob@example.org",
&Vec::new(),
&vec!["srowen@example.org", "bob@example.org"],
&["srowen@example.org", "bob@example.org"],
&Vec::new(),
"",
"",
@@ -84,7 +84,7 @@ fn testBCCs() {
"mailto:?bcc=srowen@example.org",
&Vec::new(),
&Vec::new(),
&vec!["srowen@example.org"],
&["srowen@example.org"],
"",
"",
);
@@ -92,7 +92,7 @@ fn testBCCs() {
"mailto:?bcc=srowen@example.org,bob@example.org",
&Vec::new(),
&Vec::new(),
&vec!["srowen@example.org", "bob@example.org"],
&["srowen@example.org", "bob@example.org"],
"",
"",
);
@@ -102,9 +102,9 @@ fn testBCCs() {
fn testAll() {
do_test(
"mailto:bob@example.org?cc=foo@example.org&bcc=srowen@example.org&subject=baz&body=buzz",
&vec!["bob@example.org"],
&vec!["foo@example.org"],
&vec!["srowen@example.org"],
&["bob@example.org"],
&["foo@example.org"],
&["srowen@example.org"],
"baz",
"buzz",
);
@@ -151,7 +151,7 @@ fn testSMTP() {
}
fn do_test_single(contents: &str, to: &str, subject: &str, body: &str) {
do_test(contents, &vec![to], &Vec::new(), &Vec::new(), subject, body);
do_test(contents, &[to], &Vec::new(), &Vec::new(), subject, body);
}
fn do_test(contents: &str, tos: &[&str], ccs: &[&str], bccs: &[&str], subject: &str, body: &str) {

View File

@@ -120,22 +120,16 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
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(),
),
));
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::with_details(tos, ccs, bccs, subject, body),
))
} else {
// let atext_alphanumeric = Regex::new("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+").unwrap();
if !EmailDoCoMoResultParser::isBasicallyValidEmailAddress(&rawText, &ATEXT_ALPHANUMERIC) {
return None;
}
return Some(ParsedClientResult::EmailResult(
Some(ParsedClientResult::EmailResult(
EmailAddressParsedRXingResult::new(rawText),
));
))
}
}

View File

@@ -48,7 +48,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let tos = ResultParser::match_do_co_mo_prefixed_field("TO:", &rawText)?;
for to in &tos {
if !isBasicallyValidEmailAddress(&to, &ATEXT_ALPHANUMERIC) {
if !isBasicallyValidEmailAddress(to, &ATEXT_ALPHANUMERIC) {
return None;
}
}

View File

@@ -251,7 +251,7 @@ fn findAIvalue(i: usize, rawText: &str) -> Option<String> {
if currentChar == ')' {
return Some(buf);
}
if currentChar < '0' || currentChar > '9' {
if !('0'..='9').contains(&currentChar) {
return None;
}
buf.push(currentChar);
@@ -270,7 +270,7 @@ fn findValue(i: usize, rawText: &str) -> String {
if c == '(' {
// We look for a new AI. If it doesn't exist (ERROR), we continue
// with the iteration
if let Some(_) = findAIvalue(index, rawTextAux) {
if findAIvalue(index, rawTextAux).is_some() {
break;
}
// if findAIvalue(index, rawTextAux) != null {

View File

@@ -29,7 +29,7 @@ lazy_static! {
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.]+))?(?:\\?(.*))?";
const GEO_URL_PATTERN: &str = "geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?";
/**
* Parses a "geo:" URI result, which specifies a location on the surface of
@@ -54,7 +54,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
let latitude = if let Some(la) = captures.get(1) {
if let Ok(laf64) = la.as_str().parse::<f64>() {
if laf64 > 90.0 || laf64 < -90.0 {
if !(-90.0..=90.0).contains(&laf64) {
return None;
}
laf64
@@ -67,7 +67,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
let longitude = if let Some(lo) = captures.get(2) {
if let Ok(lof64) = lo.as_str().parse::<f64>() {
if lof64 > 180.0 || lof64 < -180.0 {
if !(-180.0..=180.0).contains(&lof64) {
return None;
}
lof64
@@ -119,7 +119,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
String::from(query),
)))
} else {
return None;
None
}
// Matcher matcher = GEO_URL_PATTERN.matcher(rawText);

View File

@@ -44,7 +44,7 @@ pub trait ParsedRXingResult {
fn maybe_append(&self, value: &str, result: &mut String) {
if !value.is_empty() {
// Don't add a newline before the first value
if result.len() > 0 {
if !result.is_empty() {
result.push('\n');
}
result.push_str(value);

View File

@@ -46,14 +46,14 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
}
// Not actually checking the checksum again here
let normalizedProductID;
let normalizedProductID=
// Expand UPC-E for purposes of searching
if format == &BarcodeFormat::UPC_E && rawText.len() == 8 {
// unimplemented!("UPCEReader is required to parse this");
normalizedProductID = crate::oned::convertUPCEtoUPCA(&rawText);
crate::oned::convertUPCEtoUPCA(&rawText)
} else {
normalizedProductID = rawText.clone();
}
rawText.clone()
};
Some(ParsedClientResult::ProductResult(
ProductParsedRXingResult::with_normalized_id(rawText, normalizedProductID),

View File

@@ -97,9 +97,9 @@ lazy_static! {
}
// const DIGITS: &'static str = "\\d+"; //= Pattern.compile("\\d+");
const AMPERSAND: &'static str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&");
const EQUALS: &'static str = "="; //private static final Pattern EQUALS = Pattern.compile("=");
const BYTE_ORDER_MARK: &'static str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff";
const AMPERSAND: &str = "&"; // private static final Pattern AMPERSAND = Pattern.compile("&");
const EQUALS: &str = "="; //private static final Pattern EQUALS = Pattern.compile("=");
const BYTE_ORDER_MARK: &str = "\u{feff}"; //private static final String BYTE_ORDER_MARK = "\ufeff";
// const EMPTY_STR_ARRAY: &'static str = "";
@@ -108,7 +108,7 @@ pub fn getMassagedText(result: &RXingResult) -> String {
if text.starts_with(BYTE_ORDER_MARK) {
text = text[1..].to_owned();
}
return text;
text
}
pub fn parse_result_with_parsers(
@@ -117,8 +117,8 @@ pub fn parse_result_with_parsers(
) -> ParsedClientResult {
for parser in parsers {
let result = parser(the_rxing_result);
if result.is_some() {
return result.unwrap();
if let Some(res) = result {
return res;
}
}
parseRXingResult(the_rxing_result)
@@ -150,8 +150,8 @@ pub fn parseRXingResult(the_rxing_result: &RXingResult) -> ParsedClientResult {
for parser in PARSERS {
let result = parser(the_rxing_result);
if result.is_some() {
return result.unwrap();
if let Some(res) = result {
return res;
}
}
// ParsedRXingResult result = parser.parse(theRXingResult);
@@ -193,7 +193,7 @@ pub fn maybeWrap(value: Option<String>) -> Option<Vec<String>> {
if value.is_none() {
None
} else {
Some(vec![value.unwrap().to_owned()])
Some(vec![value.unwrap()])
}
}
@@ -222,16 +222,16 @@ pub fn unescapeBackslash(escaped: &str) -> String {
}
pub fn parseHexDigit(c: char) -> i32 {
if c >= '0' && c <= '9' {
return (c as u8 - '0' as u8) as i32;
if ('0'..='9').contains(&c) {
return (c as u8 - b'0') as i32;
}
if c >= 'a' && c <= 'f' {
return 10 + (c as u8 - 'a' as u8) as i32;
if ('a'..='f').contains(&c) {
return 10 + (c as u8 - b'a') as i32;
}
if c >= 'A' && c <= 'F' {
return 10 + (c as u8 - 'A' as u8) as i32;
if ('A'..='F').contains(&c) {
return 10 + (c as u8 - b'A') as i32;
}
return -1;
-1
}
pub fn isStringOfDigits(value: &str, length: usize) -> bool {
@@ -242,16 +242,12 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool {
if value.is_empty() || length == 0 {
return false;
}
let max = offset as usize + length;
let max = offset + length;
let sub_seq = &value[offset as usize..max];
let sub_seq = &value[offset..max];
let is_a_match = if let Some(mtch) = DIGITS.find(sub_seq) {
if mtch.start() == 0 && mtch.end() == sub_seq.len() {
true
} else {
false
}
mtch.start() == 0 && mtch.end() == sub_seq.len()
} else {
false
};
@@ -261,9 +257,7 @@ pub fn isSubstringOfDigits(value: &str, offset: usize, length: usize) -> bool {
pub fn parseNameValuePairs(uri: &str) -> Option<HashMap<String, String>> {
let paramStart = uri.find('?');
if paramStart.is_none() {
return None;
}
paramStart?;
let mut result = HashMap::with_capacity(3);
let paramStart = paramStart.unwrap_or(0);
@@ -285,7 +279,7 @@ pub fn appendKeyValue(keyValue: &str, result: &mut HashMap<String, String>) {
let kvp: Vec<&str> = keyValueTokens.take(2).collect();
if let [key, value] = kvp[..] {
let p_value = urlDecode(value).unwrap_or("".to_owned());
let p_value = urlDecode(value).unwrap_or_else(|_| "".to_owned());
result.insert(key.to_owned(), p_value);
}
@@ -305,9 +299,9 @@ pub fn urlDecode(encoded: &str) -> Result<String, Exceptions> {
if let Ok(decoded) = decode(encoded) {
Ok(decoded.to_string())
} else {
Err(Exceptions::IllegalStateException(
Err(Exceptions::IllegalStateException(Some(
"UnsupportedEncodingException".to_owned(),
))
)))
}
}
@@ -334,14 +328,13 @@ pub fn matchPrefixedField(
let start = i; // Found the start of a match here
let mut more = true;
while more {
let next_index = rawText[i..].find(endChar);
if next_index.is_none() {
if let Some(next_index) = rawText[i..].find(endChar) {
i += next_index;
} else {
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.len();
more = false;
continue;
} else {
i += next_index.unwrap();
}
if countPrecedingBackslashes(rawText, i) % 2 != 0 {
@@ -399,7 +392,7 @@ pub fn countPrecedingBackslashes(s: &str, pos: usize) -> u32 {
break;
}
}
return count;
count
}
pub fn matchSinglePrefixedField(
@@ -409,11 +402,7 @@ pub fn matchSinglePrefixedField(
trim: bool,
) -> Option<String> {
let matches = matchPrefixedField(prefix, rawText, endChar, trim);
if let Some(m) = matches {
Some(m[0].clone())
} else {
None
}
matches.map(|m| m[0].clone())
// return matches == null ? null : matches[0];
}

View File

@@ -69,13 +69,13 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// Drop sms, query portion
let query_start = raw_text[4..].find('?');
let sms_uriwithout_query;
let sms_uriwithout_query=
// If it's not query syntax, the question mark is part of the subject or message
if query_start.is_none() || !querySyntax {
sms_uriwithout_query = &raw_text[4..];
&raw_text[4..]
} else {
sms_uriwithout_query = &raw_text[4..4 + query_start.unwrap_or(0)];
}
&raw_text[4..4 + query_start.unwrap_or(0)]
};
let mut last_comma: i32 = -1;
let mut comma: i32 = sms_uriwithout_query[(last_comma + 1) as usize..]
@@ -103,7 +103,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
);
Some(ParsedClientResult::SMSResult(
SMSParsedRXingResult::with_arrays(numbers, vias, subject.to_owned(), body.to_owned()),
SMSParsedRXingResult::with_arrays(numbers, vias, subject, body),
))
// return new SMSParsedRXingResult(numbers.toArray(EMPTY_STR_ARRAY),
@@ -120,8 +120,8 @@ fn add_number_via(numbers: &mut Vec<String>, vias: &mut Vec<String>, number_part
// if numberEnd < 0 {
numbers.push(number_part[..number_end].to_string());
let maybe_via = &number_part[number_end + 1..];
let via = if maybe_via.starts_with("via=") {
&maybe_via[4..]
let via = if let Some(stripped) = maybe_via.strip_prefix("via=") {
stripped
} else {
""
};

View File

@@ -60,6 +60,6 @@ impl TelParsedRXingResult {
}
pub fn getTitle(&self) -> &str {
&&self.title
&self.title
}
}

View File

@@ -35,8 +35,8 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult>
return None;
}
// Normalize "TEL:" to "tel:"
let telURI = if rawText.starts_with("TEL:") {
format!("tel:{}", &rawText[4..])
let telURI = if let Some(stripped) = rawText.strip_prefix("TEL:") {
format!("tel:{}", stripped)
} else {
rawText.clone()
};
@@ -50,7 +50,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<ParsedClientResult>
// let number = queryStart < 0 ? : ;
Some(ParsedClientResult::TelResult(TelParsedRXingResult::new(
number.to_owned(),
telURI.to_owned(),
telURI,
"".to_owned(),
)))
}

View File

@@ -63,7 +63,7 @@ impl URIParsedRXingResult {
*/
#[deprecated]
pub fn is_possibly_malicious_uri(&self) -> bool {
return URIResultParser::is_possibly_malicious_uri(&self.uri);
URIResultParser::is_possibly_malicious_uri(&self.uri)
}
/**
@@ -98,6 +98,6 @@ impl URIParsedRXingResult {
// if (nextSlash < 0) {
// nextSlash = uri.length();
// }
return ResultParser::isSubstringOfDigits(uri, start, nextSlash - start);
ResultParser::isSubstringOfDigits(uri, start, nextSlash - start)
}
}

View File

@@ -44,7 +44,7 @@ lazy_static! {
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]+";
const ALLOWED_URI_CHARS_PATTERN: &str = "[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+";
// const USER_IN_HOST: &'static str = ":/*([^/@]+)@[^/]+";
/// See http://www.ietf.org/rfc/rfc2396.txt
// const URL_WITH_PROTOCOL_PATTERN: &'static str = "[a-zA-Z][a-zA-Z0-9+-.]+:";
@@ -83,11 +83,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
*/
pub fn is_possibly_malicious_uri(uri: &str) -> bool {
let allowed = if let Some(fnd) = ALLOWED_URI_CHARS.find(uri) {
if fnd.start() == 0 && fnd.end() == uri.len() {
true
} else {
false
}
fnd.start() == 0 && fnd.end() == uri.len()
} else {
false
};
@@ -97,7 +93,7 @@ pub fn is_possibly_malicious_uri(uri: &str) -> bool {
}
pub fn is_basically_valid_uri(uri: &str) -> bool {
if uri.contains(" ") {
if uri.contains(' ') {
// Quick hack check for a common case
return false;
}
@@ -111,12 +107,7 @@ pub fn is_basically_valid_uri(uri: &str) -> bool {
// let m = Regex::new(URL_WITHOUT_PROTOCOL_PATTERN).expect("Regex patterns should always copile"); //.matcher(uri);
if let Some(found) = URL_WITHOUT_PROTOCOL_PATTERN.find(uri) {
if found.start() == 0 {
// match at start only
true
} else {
false
}
found.start() == 0
} else {
false
}

View File

@@ -58,9 +58,9 @@ lazy_static! {
// const NEWLINE_ESCAPE: &'static str = "\\\\[nN]";
// const VCARD_ESCAPES: &'static str = "\\\\([,;\\\\])";
// const EQUALS: &'static str = "=";
const SEMICOLON: &'static str = ";";
const SEMICOLON: &str = ";";
// const UNESCAPED_SEMICOLONS: &'static str = "(?<!\\\\);+";
const COMMA: &'static str = ",";
const COMMA: &str = ",";
// const SEMICOLON_OR_COMMA: &'static str = "[;,]";
/**
@@ -130,14 +130,14 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let urls = matchVCardPrefixedField("URL", &rawText, true, false);
let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false);
let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false);
let geo = if geoString.is_none() {
Vec::new()
} else {
let geo = if let Some(geo_string) = geoString {
SEMICOLON_OR_COMMA
.split(&geoString.unwrap()[0])
.split(&geo_string[0])
.map(|x| x.to_owned())
.collect()
// SEMICOLON_OR_COMMA.split(geoString.unwrap()[0])
} else {
Vec::new()
};
// if geo.len() != 2 {
// geo = null;
@@ -322,7 +322,7 @@ pub fn matchVCardPrefixedField(
// matches.add(match);
// } else {
metadata.push(element);
matches.push(metadata.into_iter().map(|s| s.to_owned()).collect());
matches.push(metadata.into_iter().collect());
// }
i += 1;
} else {
@@ -414,29 +414,22 @@ fn decodeQuotedPrintable(value: &str, charset: &str) -> String {
}
fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut String) {
if fragmentBuffer.len() > 0 {
if !fragmentBuffer.is_empty() {
let fragmentBytes = fragmentBuffer.clone();
let fragment;
if charset.is_empty() {
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned());
fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned());
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} else {
if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
fragment = if let Ok(encoded_result) =
enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict)
{
encoded_result
} else {
String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
}
} else if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
fragment = if let Ok(encoded_result) =
enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict)
{
encoded_result
} else {
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned())
}
// try {
// fragment = new String(fragmentBytes, charset);
// } catch (UnsupportedEncodingException e) {
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
// }
} else {
fragment = String::from_utf8(fragmentBytes).unwrap_or_else(|_| "".to_owned())
}
fragmentBuffer.clear();
result.push_str(&fragment);
@@ -505,7 +498,7 @@ fn toTypes(lists: Option<Vec<Vec<String>>>) -> Vec<String> {
if let Some(value) = list.get(0) {
if !value.is_empty() {
let mut v_type = String::new();
let final_value = list.get(list.len() - 1).unwrap_or(&"".to_owned()).clone();
let final_value = list.last().unwrap_or(&"".to_owned()).clone();
if !final_value.is_empty() {
for i in 0..list.len() - 1 {
// for (int i = 1; i < list.size(); i++) {
@@ -553,7 +546,7 @@ fn formatNames(names: &mut Vec<Vec<String>>) {
for list in names {
// for (List<String> list : names) {
let mut pos = 0;
while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find("=") {
while let Some(_fnd) = list.get(pos).unwrap_or(&"".to_owned()).find('=') {
pos += 1;
}
let name = list.get(pos).unwrap_or(&"".to_owned()).clone();
@@ -584,9 +577,9 @@ fn formatNames(names: &mut Vec<Vec<String>>) {
}
}
fn maybeAppendComponent(components: &Vec<String>, i: usize, newName: &mut String) {
fn maybeAppendComponent(components: &[String], i: usize, newName: &mut String) {
if !components[i].is_empty() {
if newName.len() > 0 {
if !newName.is_empty() {
newName.push(' ');
}
newName.push_str(&components[i]);

View File

@@ -32,7 +32,7 @@ use super::{CalendarParsedRXingResult, ParsedClientResult, ResultParser, VCardRe
*/
pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let rawText = ResultParser::getMassagedText(result);
if let None = rawText.find("BEGIN:VEVENT") {
if !rawText.contains("BEGIN:VEVENT") {
return None;
}
// if (vEventStart < 0) {
@@ -51,9 +51,10 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let mut attendees = matchVCardPrefixedField("ATTENDEE", &rawText);
if !attendees.is_empty() {
for i in 0..attendees.len() {
for attendee in &mut attendees {
// for i in 0..attendees.len() {
// for (int i = 0; i < attendees.length; i++) {
attendees[i] = stripMailto(&attendees[i]);
*attendee = stripMailto(attendee);
}
}
let description = matchSingleVCardPrefixedField("DESCRIPTION", &rawText);
@@ -64,30 +65,19 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
if geoString.is_empty() {
latitude = f64::NAN;
longitude = f64::NAN;
} else {
if let Some(semicolon) = geoString.find(';') {
latitude = if let Ok(l) = geoString[..semicolon].parse() {
l
} else {
return None;
};
longitude = if let Ok(l) = geoString[semicolon + 1..].parse() {
l
} else {
return None;
}
} else if let Some(semicolon) = geoString.find(';') {
latitude = if let Ok(l) = geoString[..semicolon].parse() {
l
} else {
return None;
};
longitude = if let Ok(l) = geoString[semicolon + 1..].parse() {
l
} else {
return None;
}
// if (semicolon < 0) {
// return null;
// }
// try {
// latitude = Double.parseDouble(geoString.substring(0, semicolon));
// longitude = Double.parseDouble(geoString.substring(semicolon + 1));
// } catch (NumberFormatException ignored) {
// return null;
// }
} else {
return None;
}
if let Ok(cpr) = CalendarParsedRXingResult::new(
@@ -159,9 +149,10 @@ fn matchVCardPrefixedField(prefix: &str, rawText: &str) -> Vec<String> {
} else {
let size = values.len();
let mut result = vec!["".to_owned(); size]; //new String[size];
for i in 0..size {
for (i, res) in result.iter_mut().enumerate().take(size) {
// for i in 0..size {
// for (int i = 0; i < size; i++) {
result[i] = values.get(i).unwrap().get(0).unwrap().clone();
*res = values.get(i).unwrap().get(0).unwrap().clone();
}
result
}

View File

@@ -49,9 +49,7 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
let raw_text_res = result.getText().trim();
let raw_text = IOQ_MATCHER.replace_all(raw_text_res, "").to_string();
// rawText = IOQ.matcher(rawText).replaceAll("").trim();
if let None = AZ09_MATCHER.find(&raw_text) {
return None;
}
AZ09_MATCHER.find(&raw_text)?;
// if !AZ09.matcher(rawText).matches() {
// return null;
// }
@@ -95,8 +93,8 @@ pub fn parse(result: &RXingResult) -> Option<ParsedClientResult> {
// }
}
const IOQ: &'static str = "[IOQ]";
const AZ09: &'static str = "[A-Z0-9]{17}";
const IOQ: &str = "[IOQ]";
const AZ09: &str = "[A-Z0-9]{17}";
fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
let mut sum = 0;
@@ -111,13 +109,13 @@ fn check_checksum(vin: &str) -> Result<bool, Exceptions> {
fn vin_char_value(c: char) -> Result<u32, Exceptions> {
match c {
'A'..='I' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 1),
'J'..='R' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1),
'S'..='Z' => Ok((c as u8 as u32 - 'S' as u8 as u32) + 2),
'0'..='9' => Ok(c as u8 as u32 - '0' as u8 as u32),
_ => Err(Exceptions::IllegalArgumentException(
'A'..='I' => Ok((c as u8 as u32 - b'A' as u32) + 1),
'J'..='R' => Ok((c as u8 as u32 - b'J' as u32) + 1),
'S'..='Z' => Ok((c as u8 as u32 - b'S' as u32) + 2),
'0'..='9' => Ok(c as u8 as u32 - b'0' as u32),
_ => Err(Exceptions::IllegalArgumentException(Some(
"vin char out of range".to_owned(),
)),
))),
}
// if c >= 'A' && c <= 'I' {
// return Ok((c as u8 as u32 - 'A' as u8 as u32) + 1);
@@ -142,9 +140,9 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
8 => Ok(10),
9 => Ok(0),
10..=17 => Ok(19 - position),
_ => Err(Exceptions::IllegalArgumentException(
_ => Err(Exceptions::IllegalArgumentException(Some(
"vin position weight out of bounds".to_owned(),
)),
))),
}
// if position >= 1 && position <= 7 {
// return 9 - position;
@@ -163,11 +161,11 @@ fn vin_position_weight(position: usize) -> Result<usize, Exceptions> {
fn check_char(remainder: u8) -> Result<char, Exceptions> {
match remainder {
0..=9 => Ok(('0' as u8 + remainder) as char),
0..=9 => Ok((b'0' + remainder) as char),
10 => Ok('X'),
_ => Err(Exceptions::IllegalArgumentException(
_ => Err(Exceptions::IllegalArgumentException(Some(
"remainder too high".to_owned(),
)),
))),
}
// if remainder < 10 {
// return Ok(('0' as u8 + remainder) as char);
@@ -182,16 +180,16 @@ fn check_char(remainder: u8) -> Result<char, Exceptions> {
fn model_year(c: char) -> Result<u32, Exceptions> {
match c {
'E'..='H' => Ok((c as u8 as u32 - 'E' as u8 as u32) + 1984),
'J'..='N' => Ok((c as u8 as u32 - 'J' as u8 as u32) + 1988),
'E'..='H' => Ok((c as u8 as u32 - b'E' as u32) + 1984),
'J'..='N' => Ok((c as u8 as u32 - b'J' as u32) + 1988),
'P' => Ok(1993),
'R'..='T' => Ok((c as u8 as u32 - 'R' as u8 as u32) + 1994),
'V'..='Y' => Ok((c as u8 as u32 - 'V' as u8 as u32) + 1997),
'1'..='9' => Ok((c as u8 as u32 - '1' as u8 as u32) + 2001),
'A'..='D' => Ok((c as u8 as u32 - 'A' as u8 as u32) + 2010),
_ => Err(Exceptions::IllegalArgumentException(String::from(
'R'..='T' => Ok((c as u8 as u32 - b'R' as u32) + 1994),
'V'..='Y' => Ok((c as u8 as u32 - b'V' as u32) + 1997),
'1'..='9' => Ok((c as u8 as u32 - b'1' as u32) + 2001),
'A'..='D' => Ok((c as u8 as u32 - b'A' as u32) + 2010),
_ => Err(Exceptions::IllegalArgumentException(Some(String::from(
"model year argument out of range",
))),
)))),
}
// if c >= 'E' && c <= 'H' {
// return (c - 'E') + 1984;
@@ -218,24 +216,24 @@ fn model_year(c: char) -> Result<u32, Exceptions> {
}
fn country_code(wmi: &str) -> Option<&'static str> {
let c1 = wmi.chars().nth(0).unwrap();
let c1 = wmi.chars().next().unwrap();
let c2 = wmi.chars().nth(1).unwrap();
match c1 {
'1' | '4' | '5' => Some("US"),
'2' => Some("CA"),
'3' if c2 >= 'A' && c2 <= 'W' => Some("MX"),
'9' if ((c2 >= 'A' && c2 <= 'E') || (c2 >= '3' && c2 <= '9')) => Some("BR"),
'J' if (c2 >= 'A' && c2 <= 'T') => Some("JP"),
'K' if (c2 >= 'L' && c2 <= 'R') => Some("KO"),
'3' if ('A'..='W').contains(&c2) => Some("MX"),
'9' if (('A'..='E').contains(&c2) || ('3'..='9').contains(&c2)) => Some("BR"),
'J' if ('A'..='T').contains(&c2) => Some("JP"),
'K' if ('L'..='R').contains(&c2) => Some("KO"),
'L' => Some("CN"),
'M' if (c2 >= 'A' && c2 <= 'E') => Some("IN"),
'S' if (c2 >= 'A' && c2 <= 'M') => Some("UK"),
'S' if (c2 >= 'N' && c2 <= 'T') => Some("DE"),
'V' if (c2 >= 'F' && c2 <= 'R') => Some("FR"),
'V' if (c2 >= 'S' && c2 <= 'W') => Some("ES"),
'M' if ('A'..='E').contains(&c2) => Some("IN"),
'S' if ('A'..='M').contains(&c2) => Some("UK"),
'S' if ('N'..='T').contains(&c2) => Some("DE"),
'V' if ('F'..='R').contains(&c2) => Some("FR"),
'V' if ('S'..='W').contains(&c2) => Some("ES"),
'W' => Some("DE"),
'X' if (c2 == '0' || (c2 >= '3' && c2 <= '9')) => Some("RU"),
'Z' if (c2 >= 'A' && c2 <= 'R') => Some("IT"),
'X' if (c2 == '0' || ('3'..='9').contains(&c2)) => Some("RU"),
'Z' if ('A'..='R').contains(&c2) => Some("IT"),
_ => None,
}
}

View File

@@ -44,7 +44,7 @@ use super::ResultParser;
// impl RXingResultParser for WifiRXingResultParser {
pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientResult> {
const WIFI_TEST: &'static str = "WIFI:";
const WIFI_TEST: &str = "WIFI:";
let rawText_unstripped = ResultParser::getMassagedText(theRXingResult);
if !rawText_unstripped.starts_with(WIFI_TEST) {
@@ -52,12 +52,12 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
}
let rawText = rawText_unstripped[WIFI_TEST.len()..].to_owned();
let ssid = ResultParser::matchSinglePrefixedField("S:", &rawText, ';', false)
.unwrap_or(String::from(""));
.unwrap_or_else(|| String::from(""));
if ssid.is_empty() {
return None;
}
let pass = ResultParser::matchSinglePrefixedField("P:", &rawText, ';', false)
.unwrap_or(String::from(""));
.unwrap_or_else(|| String::from(""));
let n_type =
if let Some(nt) = ResultParser::matchSinglePrefixedField("T:", &rawText, ';', false) {
nt
@@ -85,11 +85,11 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
};
let identity = ResultParser::matchSinglePrefixedField("I:", &rawText, ';', false)
.unwrap_or(String::from(""));
.unwrap_or_else(|| String::from(""));
let anonymousIdentity = ResultParser::matchSinglePrefixedField("A:", &rawText, ';', false)
.unwrap_or(String::from(""));
.unwrap_or_else(|| String::from(""));
let eapMethod = ResultParser::matchSinglePrefixedField("E:", &rawText, ';', false)
.unwrap_or(String::from(""));
.unwrap_or_else(|| String::from(""));
Some(ParsedClientResult::WiFiResult(
WifiParsedRXingResult::with_details(
@@ -100,7 +100,7 @@ pub fn parse(theRXingResult: &crate::RXingResult) -> Option<super::ParsedClientR
identity,
anonymousIdentity,
eapMethod,
phase2Method.unwrap_or(String::from("")),
phase2Method.unwrap_or_else(|| String::from("")),
),
))
}