vcard port no tests

This commit is contained in:
Henry Schimke
2022-09-11 12:58:56 -05:00
parent 582dd75c02
commit f9e0705b9b
2 changed files with 481 additions and 312 deletions

View File

@@ -13,6 +13,7 @@ regex = "1.6"
encoding = "0.2" encoding = "0.2"
rand = "0.8.5" rand = "0.8.5"
urlencoding = "2.1.2" urlencoding = "2.1.2"
uriparse = "0.6.4"
image = {version = "0.24.3", optional = true} image = {version = "0.24.3", optional = true}
imageproc = {version = "0.23.0", optional = true} imageproc = {version = "0.23.0", optional = true}

View File

@@ -28,9 +28,16 @@
// import java.util.regex.Matcher; // import java.util.regex.Matcher;
// import java.util.regex.Pattern; // import java.util.regex.Pattern;
use std::convert::TryFrom;
use encoding::all::encodings;
use regex::Regex;
use crate::RXingResult; use crate::RXingResult;
use super::ParsedClientResult; use uriparse::URI;
use super::{AddressBookParsedRXingResult, ParsedClientResult, ResultParser};
const BEGIN_VCARD: &'static str = "BEGIN:VCARD"; //, Pattern.CASE_INSENSITIVE); const BEGIN_VCARD: &'static str = "BEGIN:VCARD"; //, Pattern.CASE_INSENSITIVE);
const VCARD_LIKE_DATE: &'static str = "\\d{4}-?\\d{2}-?\\d{2}"; const VCARD_LIKE_DATE: &'static str = "\\d{4}-?\\d{2}-?\\d{2}";
@@ -53,283 +60,439 @@ use super::ParsedClientResult;
// Although we should insist on the raw text ending with "END:VCARD", there's no reason // Although we should insist on the raw text ending with "END:VCARD", there's no reason
// to throw out everything else we parsed just because this was omitted. In fact, Eclair // to throw out everything else we parsed just because this was omitted. In fact, Eclair
// is doing just that, and we can't parse its contacts without this leniency. // is doing just that, and we can't parse its contacts without this leniency.
let rawText = getMassagedText(result); let rawText = ResultParser::getMassagedText(result);
Matcher m = BEGIN_VCARD.matcher(rawText);
if (!m.find() || m.start() != 0) { let semicolon_comma_regex = Regex::new(SEMICOLON_OR_COMMA).unwrap();
return null;
let rg = Regex::new(BEGIN_VCARD).unwrap();
let mtch = rg.find(&rawText)?;
// Matcher m = BEGIN_VCARD.matcher(rawText);
if mtch.start() != 0 {
return None;
} }
List<List<String>> names = matchVCardPrefixedField("FN", rawText, true, false); let names: Vec<Vec<String>> =
if (names == null) { if let Some(m) = matchVCardPrefixedField("FN", &rawText, true, false) {
m
} else {
// If no display names found, look for regular name fields and format them // If no display names found, look for regular name fields and format them
names = matchVCardPrefixedField("N", rawText, true, false); let mut n = matchVCardPrefixedField("N", &rawText, true, false)?;
formatNames(names); formatNames(&mut n);
n
};
// if names == null {
// }
let nicknames = if let Some(nicknameString) =
matchSingleVCardPrefixedField("NICKNAME", &rawText, true, false)
{
nicknameString[0]
.split(COMMA)
.map(|x| x.to_owned())
.collect::<Vec<String>>()
// COMMA.split(nicknameString.get(0)
} else {
Vec::new()
};
// let nicknames = nicknameString == null ? null : COMMA.split(nicknameString.get(0));
let phoneNumbers = matchVCardPrefixedField("TEL", &rawText, true, false);
let emails = matchVCardPrefixedField("EMAIL", &rawText, true, false);
let note = matchSingleVCardPrefixedField("NOTE", &rawText, false, false);
let addresses = matchVCardPrefixedField("ADR", &rawText, true, true);
let org = matchSingleVCardPrefixedField("ORG", &rawText, true, true);
let birthday =
if let Some(bday_array) = matchSingleVCardPrefixedField("BDAY", &rawText, true, false) {
if isLikeVCardDate(&bday_array[0]) {
bday_array
} else {
vec!["".to_owned()]
} }
List<String> nicknameString = matchSingleVCardPrefixedField("NICKNAME", rawText, true, false); } else {
String[] nicknames = nicknameString == null ? null : COMMA.split(nicknameString.get(0)); vec!["".to_owned()]
List<List<String>> phoneNumbers = matchVCardPrefixedField("TEL", rawText, true, false); };
List<List<String>> emails = matchVCardPrefixedField("EMAIL", rawText, true, false); // if birthday != null && !isLikeVCardDate(birthday.get(0)) {
List<String> note = matchSingleVCardPrefixedField("NOTE", rawText, false, false); // birthday = null;
List<List<String>> addresses = matchVCardPrefixedField("ADR", rawText, true, true); // }
List<String> org = matchSingleVCardPrefixedField("ORG", rawText, true, true); let title = matchSingleVCardPrefixedField("TITLE", &rawText, true, false);
List<String> birthday = matchSingleVCardPrefixedField("BDAY", rawText, true, false); let urls = matchVCardPrefixedField("URL", &rawText, true, false);
if (birthday != null && !isLikeVCardDate(birthday.get(0))) { let instantMessenger = matchSingleVCardPrefixedField("IMPP", &rawText, true, false);
birthday = null; let geoString = matchSingleVCardPrefixedField("GEO", &rawText, true, false);
} let geo = if geoString.is_none() {
List<String> title = matchSingleVCardPrefixedField("TITLE", rawText, true, false); Vec::new()
List<List<String>> urls = matchVCardPrefixedField("URL", rawText, true, false); } else {
List<String> instantMessenger = matchSingleVCardPrefixedField("IMPP", rawText, true, false); semicolon_comma_regex
List<String> geoString = matchSingleVCardPrefixedField("GEO", rawText, true, false); .split(&geoString.unwrap()[0])
String[] geo = geoString == null ? null : SEMICOLON_OR_COMMA.split(geoString.get(0)); .map(|x| x.to_owned())
if (geo != null && geo.length != 2) { .collect()
geo = null; // SEMICOLON_OR_COMMA.split(geoString.unwrap()[0])
} };
return new AddressBookParsedRXingResult(toPrimaryValues(names), // if geo.len() != 2 {
// geo = null;
// }
if let Ok(adb) = AddressBookParsedRXingResult::with_details(
toPrimaryValues(Some(names))?,
nicknames, nicknames,
null, "".to_owned(),
toPrimaryValues(phoneNumbers), toPrimaryValues(phoneNumbers.clone())?,
toTypes(phoneNumbers), toTypes(phoneNumbers)?,
toPrimaryValues(emails), toPrimaryValues(emails.clone())?,
toTypes(emails), toTypes(emails)?,
toPrimaryValue(instantMessenger), toPrimaryValue(instantMessenger),
toPrimaryValue(note), toPrimaryValue(note),
toPrimaryValues(addresses), toPrimaryValues(addresses.clone())?,
toTypes(addresses), toTypes(addresses)?,
toPrimaryValue(org), toPrimaryValue(org),
toPrimaryValue(birthday), toPrimaryValue(Some(birthday)),
toPrimaryValue(title), toPrimaryValue(title),
toPrimaryValues(urls), toPrimaryValues(urls)?,
geo); geo,
) {
Some(ParsedClientResult::AddressBookResult(adb))
} else {
None
}
} }
fn matchVCardPrefixedField( prefix:&str, fn matchVCardPrefixedField(
prefix: &str,
rawText: &str, rawText: &str,
trim: bool, trim: bool,
parseFieldDivider:bool) -> Vec<String> { parseFieldDivider: bool,
List<List<String>> matches = null; ) -> Option<Vec<Vec<String>>> {
int i = 0; let mut matches: Vec<Vec<String>> = Vec::new();
int max = rawText.length(); let mut i = 0;
let max = rawText.len();
while (i < max) { let equals_regex = Regex::new(EQUALS).unwrap();
let unescaped_semis = Regex::new(UNESCAPED_SEMICOLONS).unwrap();
let cr_lf_space_tab = Regex::new(CR_LF_SPACE_TAB).unwrap();
let newline_esc = Regex::new(NEWLINE_ESCAPE).unwrap();
let vcard_esc = Regex::new(VCARD_ESCAPES).unwrap();
// At start or after newline, match prefix, followed by optional metadata // At start or after newline, match prefix, followed by optional metadata
// (led by ;) ultimately ending in colon // (led by ;) ultimately ending in colon
Matcher matcher = Pattern.compile("(?:^|\n)" + prefix + "(?:;([^:]*))?:", let matcher_primary = Regex::new(&format!("(?:^|\n){}(?:;([^:]*))?:", prefix)).unwrap();
Pattern.CASE_INSENSITIVE).matcher(rawText); let lower_case_raw_text = rawText.to_lowercase();
if (i > 0) {
i--; // Find from i-1 not i since looking at the preceding character while i < max {
//let rawText = rawText.to_lowercase();
// Pattern.CASE_INSENSITIVE).matcher(rawText);
if i > 0 {
i -= 1; // Find from i-1 not i since looking at the preceding character
} }
if (!matcher.find(i)) { let cap_maybe = matcher_primary.captures(&lower_case_raw_text[i..]);
//let matcher_maybe = matcher_primary.find_at(&lower_case_raw_text, i);
if cap_maybe.is_none() {
break; break;
} }
i = matcher.end(0); // group 0 = whole pattern; end(0) is past final colon let matcher = cap_maybe?;
i = matcher.get(0)?.end(); // group 0 = whole pattern; end(0) is past final colon
String metadataString = matcher.group(1); // group 1 = metadata substring let metadataString = matcher.get(1); // group 1 = metadata substring
List<String> metadata = null; let mut metadata: Vec<String> = Vec::new();
boolean quotedPrintable = false; let mut quotedPrintable = false;
String quotedPrintableCharset = null; let mut quotedPrintableCharset = "";
String valueType = null; let mut valueType = "";
if (metadataString != null) { if metadataString.is_some() {
for (String metadatum : SEMICOLON.split(metadataString)) { // let mds = metadataString?.as_str().split(SEMICOLON).collect();
if (metadata == null) { for metadatum in metadataString?.as_str().split(SEMICOLON) {
metadata = new ArrayList<>(1); // for (String metadatum : SEMICOLON.split(metadataString)) {
} // if (metadata == null) {
metadata.add(metadatum); // metadata = new ArrayList<>(1);
String[] metadatumTokens = EQUALS.split(metadatum, 2); // }
if (metadatumTokens.length > 1) { metadata.push(metadatum.to_owned());
String key = metadatumTokens[0];
String value = metadatumTokens[1]; let metadatumTokens = equals_regex.splitn(metadatum, 2).collect::<Vec<&str>>();
if ("ENCODING".equalsIgnoreCase(key) && "QUOTED-PRINTABLE".equalsIgnoreCase(value)) { if metadatumTokens.len() > 1 {
let key = metadatumTokens[0];
let value = metadatumTokens[1];
if "ENCODING" == key.to_uppercase()
&& "QUOTED-PRINTABLE" == value.to_uppercase()
{
quotedPrintable = true; quotedPrintable = true;
} else if ("CHARSET".equalsIgnoreCase(key)) { } else if "CHARSET" == key.to_uppercase() {
quotedPrintableCharset = value; quotedPrintableCharset = value;
} else if ("VALUE".equalsIgnoreCase(key)) { } else if "VALUE" == key.to_uppercase() {
valueType = value; valueType = value;
} }
} }
} }
} }
int matchStart = i; // Found the start of a match here let matchStart = i; // Found the start of a match here
while let Some(pos) = rawText[i..].find('\n') {
while ((i = rawText.indexOf('\n', i)) >= 0) { // Really, end in \r\n // Really, end in \r\n
if (i < rawText.length() - 1 && // But if followed by tab or space, i = pos;
(rawText.charAt(i + 1) == ' ' || // this is only a continuation // while (i = rawText.indexOf('\n', i)) >= 0 { // Really, end in \r\n
rawText.charAt(i + 1) == '\t')) { if i < rawText.len() - 1 && // But if followed by tab or space,
(rawText.chars().nth(i + 1)? == ' ' || // this is only a continuation
rawText.chars().nth(i + 1)? == '\t')
{
i += 2; // Skip \n and continutation whitespace i += 2; // Skip \n and continutation whitespace
} else if (quotedPrintable && // If preceded by = in quoted printable } else if quotedPrintable && // If preceded by = in quoted printable
((i >= 1 && rawText.charAt(i - 1) == '=') || // this is a continuation ((i >= 1 && rawText.chars().nth(i - 1)? == '=') || // this is a continuation
(i >= 2 && rawText.charAt(i - 2) == '='))) { (i >= 2 && rawText.chars().nth(i - 2)? == '='))
i++; // Skip \n {
i += 1; // Skip \n
} else { } else {
break; break;
} }
} }
if (i < 0) { if i < 0 {
// No terminating end character? uh, done. Set i such that loop terminates and break // No terminating end character? uh, done. Set i such that loop terminates and break
i = max; i = max;
} else if (i > matchStart) { } else if i > matchStart {
// found a match // found a match
if (matches == null) { // if matches == null {
matches = new ArrayList<>(1); // lazy init // matches = new ArrayList<>(1); // lazy init
// }
if i >= 1 && rawText.chars().nth(i - 1)? == '\r' {
i -= 1; // Back up over \r, which really should be there
} }
if (i >= 1 && rawText.charAt(i - 1) == '\r') { let mut element = rawText[matchStart..i].to_owned();
i--; // Back up over \r, which really should be there if trim {
element = element.trim().to_owned();
} }
String element = rawText.substring(matchStart, i);
if (trim) { if quotedPrintable {
element = element.trim(); element = decodeQuotedPrintable(&element, quotedPrintableCharset);
} if parseFieldDivider {
if (quotedPrintable) { element = unescaped_semis
element = decodeQuotedPrintable(element, quotedPrintableCharset); .replace_all(&element, "\n")
if (parseFieldDivider) { .to_mut()
element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim(); .trim()
.to_owned();
// element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
} }
} else { } else {
if (parseFieldDivider) { if parseFieldDivider {
element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim(); element = unescaped_semis
.replace_all(&element, "\n")
.to_mut()
.trim()
.to_owned();
// element = UNESCAPED_SEMICOLONS.matcher(element).replaceAll("\n").trim();
} }
element = CR_LF_SPACE_TAB.matcher(element).replaceAll(""); element = cr_lf_space_tab
element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n"); .replace_all(&element, "")
element = VCARD_ESCAPES.matcher(element).replaceAll("$1"); .to_mut()
.to_owned();
element = newline_esc.replace_all(&element, "\n").to_mut().to_owned();
element = vcard_esc.replace_all(&element, "$1").to_mut().to_owned();
// element = CR_LF_SPACE_TAB.matcher(element).replaceAll("");
// element = NEWLINE_ESCAPE.matcher(element).replaceAll("\n");
// element = VCARD_ESCAPES.matcher(element).replaceAll("$1");
} }
// Only handle VALUE=uri specially // Only handle VALUE=uri specially
if ("uri".equals(valueType)) { if "uri" == valueType.to_lowercase() {
// Don't actually support dereferencing URIs, but use scheme-specific part not URI // Don't actually support dereferencing URIs, but use scheme-specific part not URI
// as value, to support tel: and mailto: // as value, to support tel: and mailto:
try { if let Ok(uri) = URI::try_from(element.as_str()) {
element = URI.create(element).getSchemeSpecificPart(); element = uri.scheme().to_string();
} catch (IllegalArgumentException iae) {
// ignore
} }
// try {
// element = URI.create(element).getSchemeSpecificPart();
// } catch (IllegalArgumentException iae) {
// // ignore
// }
} }
if (metadata == null) { // if metadata == null {
List<String> match = new ArrayList<>(1); // List<String> match = new ArrayList<>(1);
match.add(element); // match.add(element);
matches.add(match); // matches.add(match);
// } else {
metadata.push(element);
matches.push(metadata.into_iter().map(|s| s.to_owned()).collect());
// }
i += 1;
} else { } else {
metadata.add(0, element); i += 1;
matches.add(metadata);
} }
i++;
} else {
i++;
} }
} Some(matches)
return matches;
} }
fn decodeQuotedPrintable(value: &str, charset: &str) -> String { fn decodeQuotedPrintable(value: &str, charset: &str) -> String {
int length = value.length(); let length = value.len();
StringBuilder result = new StringBuilder(length); let mut result = String::with_capacity(length);
ByteArrayOutputStream fragmentBuffer = new ByteArrayOutputStream(); let mut fragmentBuffer: Vec<u8> = Vec::new(); //new ByteArrayOutputStream();
for (int i = 0; i < length; i++) { let mut i = 0;
char c = value.charAt(i); // for i in 0..length {
switch (c) { while i < length {
case '\r': // for (int i = 0; i < length; i++) {
case '\n': let c = value.chars().nth(i).unwrap_or_default();
break; match c {
case '=': '\r' | '\n' => break,
if (i < length - 2) { '=' if i < length - 2 => {
char nextChar = value.charAt(i + 1); let nextChar = value.chars().nth(i + 1).unwrap();
if (nextChar != '\r' && nextChar != '\n') { if nextChar != '\r' && nextChar != '\n' {
char nextNextChar = value.charAt(i + 2); let nextNextChar = value.chars().nth(i + 2).unwrap();
int firstDigit = parseHexDigit(nextChar); let firstDigit = ResultParser::parseHexDigit(nextChar);
int secondDigit = parseHexDigit(nextNextChar); let secondDigit = ResultParser::parseHexDigit(nextNextChar);
if (firstDigit >= 0 && secondDigit >= 0) { if firstDigit >= 0 && secondDigit >= 0 {
fragmentBuffer.write((firstDigit << 4) + secondDigit); fragmentBuffer.push(((firstDigit << 4) + secondDigit) as u8);
} // else ignore it, assume it was incorrectly encoded } // else ignore it, assume it was incorrectly encoded
i += 2; i += 2;
} }
}
break; break;
default: }
maybeAppendFragment(fragmentBuffer, charset, result); _ => {
result.append(c); maybeAppendFragment(&mut fragmentBuffer, charset, &mut result);
result.push(c);
} }
} }
maybeAppendFragment(fragmentBuffer, charset, result); // switch (c) {
return result.toString(); // case '\r':
// case '\n':
// break;
// case '=':
// if (i < length - 2) {
// char nextChar = value.charAt(i + 1);
// if (nextChar != '\r' && nextChar != '\n') {
// char nextNextChar = value.charAt(i + 2);
// int firstDigit = parseHexDigit(nextChar);
// int secondDigit = parseHexDigit(nextNextChar);
// if (firstDigit >= 0 && secondDigit >= 0) {
// fragmentBuffer.write((firstDigit << 4) + secondDigit);
// } // else ignore it, assume it was incorrectly encoded
// i += 2;
// }
// }
// break;
// default:
// maybeAppendFragment(fragmentBuffer, charset, result);
// result.append(c);
// }
}
maybeAppendFragment(&mut fragmentBuffer, charset, &mut result);
result
} }
fn maybeAppendFragment( fragmentBuffer &Vec<u8>, fn maybeAppendFragment(fragmentBuffer: &mut Vec<u8>, charset: &str, result: &mut String) {
charset:&str, if fragmentBuffer.len() > 0 {
result:&mut String) { let fragmentBytes = fragmentBuffer.clone();
if (fragmentBuffer.size() > 0) { let fragment;
byte[] fragmentBytes = fragmentBuffer.toByteArray(); if charset.is_empty() {
String fragment; fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned());
if (charset == null) { // fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} else { } else {
try { if let Some(enc) = encoding::label::encoding_from_whatwg_label(charset) {
fragment = new String(fragmentBytes, charset); fragment = if let Ok(encoded_result) =
} catch (UnsupportedEncodingException e) { enc.decode(&fragmentBytes, encoding::DecoderTrap::Strict)
fragment = new String(fragmentBytes, StandardCharsets.UTF_8); {
encoded_result
} else {
String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
} }
} else {
fragment = String::from_utf8(fragmentBytes).unwrap_or("".to_owned())
} }
fragmentBuffer.reset(); // try {
result.append(fragment); // fragment = new String(fragmentBytes, charset);
// } catch (UnsupportedEncodingException e) {
// fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
// }
}
fragmentBuffer.clear();
result.push_str(&fragment);
} }
} }
fn matchSingleVCardPrefixedField( prefix:&str, fn matchSingleVCardPrefixedField(
prefix: &str,
rawText: &str, rawText: &str,
trim: bool, trim: bool,
parseFieldDivider:bool)->Vec<String> { parseFieldDivider: bool,
List<List<String>> values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider); ) -> Option<Vec<String>> {
return values == null || values.isEmpty() ? null : values.get(0); let values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider)?;
if values.is_empty() {
return None;
}
Some(values.get(0)?.clone())
// return values == null || values.isEmpty() ? null : values.get(0);
} }
fn toPrimaryValue(list:&Vec<String>) -> String{ fn toPrimaryValue(list: Option<Vec<String>>) -> String {
return list == null || list.isEmpty() ? null : list.get(0); if let Some(l) = list {
if l.is_empty() {
"".to_owned()
} else {
l.get(0).unwrap_or(&"".to_owned()).clone()
}
} else {
"".to_owned()
}
// if list.is_empty() {
// "".to_owned()
// }else {
// *list.get(0).unwrap_or(&"".to_owned())
// }
// return list == null || list.isEmpty() ? null : list.get(0);
} }
fn toPrimaryValues( lists:&Vec<String>) -> Vec<String>{ fn toPrimaryValues(lists: Option<Vec<Vec<String>>>) -> Option<Vec<String>> {
if (lists == null || lists.isEmpty()) { let local_lists = lists?;
return null; if local_lists.is_empty() {
return None;
} }
List<String> result = new ArrayList<>(lists.size()); let mut result = vec!["".to_owned(); local_lists.len()]; // new ArrayList<>(lists.size());
for (List<String> list : lists) { for list in local_lists {
String value = list.get(0); // for (List<String> list : lists) {
if (value != null && !value.isEmpty()) { if let Some(value) = list.get(0) {
result.add(value); if !value.is_empty() {
result.push(value.clone());
} }
} }
return result.toArray(EMPTY_STR_ARRAY);
} }
fn toTypes( lists: &Vec<String>) -> Vec<String>{ Some(result)
if (lists == null || lists.isEmpty()) {
return null;
} }
List<String> result = new ArrayList<>(lists.size());
for (List<String> list : lists) { fn toTypes(lists: Option<Vec<Vec<String>>>) -> Option<Vec<String>> {
String value = list.get(0); let local_lists = lists?;
if (value != null && !value.isEmpty()) { if local_lists.is_empty() {
String type = null; return None;
for (int i = 1; i < list.size(); i++) { }
String metadatum = list.get(i); let mut result = vec!["".to_owned(); local_lists.len()]; //new ArrayList<>(lists.size());
int equals = metadatum.indexOf('='); for list in local_lists {
if (equals < 0) { // for (List<String> list : lists) {
if let Some(value) = list.get(0) {
if !value.is_empty() {
let mut v_type = String::new();
for i in 0..list.len() {
// for (int i = 1; i < list.size(); i++) {
let metadatum = list.get(i)?;
if let Some(equals) = metadatum.find('=') {
if "TYPE" == (metadatum[0..equals]).to_uppercase() {
v_type = metadatum[equals + 1..].to_owned();
break;
}
} else {
// if (equals < 0) {
// take the whole thing as a usable label // take the whole thing as a usable label
type = metadatum; v_type = metadatum.to_owned();
break;
}
if ("TYPE".equalsIgnoreCase(metadatum.substring(0, equals))) {
type = metadatum.substring(equals + 1);
break; break;
} }
} }
result.add(type); result.push(v_type);
} }
} }
return result.toArray(EMPTY_STR_ARRAY); }
Some(result)
} }
fn isLikeVCardDate(value: &str) -> bool { fn isLikeVCardDate(value: &str) -> bool {
return value == null || VCARD_LIKE_DATE.matcher(value).matches(); let rg = Regex::new(VCARD_LIKE_DATE).unwrap();
let matches = if let Some(mtch) = rg.find(value) {
mtch.start() == 0 && mtch.end() == value.len()
} else {
false
};
value.is_empty() || matches
} }
/** /**
@@ -338,28 +501,33 @@ use super::ParsedClientResult;
* *
* @param names name values to format, in place * @param names name values to format, in place
*/ */
fn formatNames( names : &mut Vec<String>) { fn formatNames(names: &mut Vec<Vec<String>>) {
if !names.is_empty() { if !names.is_empty() {
for list in names { for list in names {
// for (List<String> list : names) { // for (List<String> list : names) {
let name = list.get(0); let name = list.get(0).unwrap_or(&"".to_owned()).clone();
let components = vec!["";5]; let mut components = vec!["".to_owned(); 5];
let start = 0; let mut start = 0;
let end; let mut end = 0;
let componentIndex = 0; let mut componentIndex = 0;
while componentIndex < components.len() - 1 && (end = name.indexOf(';', start)) >= 0 { while componentIndex < components.len() - 1 && end >= 0 {
components[componentIndex] = name.substring(start, end); end = if let Some(pos) = name[start..].find(';') {
pos + start
} else {
0
};
components[componentIndex] = name[start..end].to_owned();
componentIndex += 1; componentIndex += 1;
start = end + 1; start = end + 1;
} }
components[componentIndex] = name.substring(start); components[componentIndex] = name[start..].to_owned();
let newName = String::with_capacity(100); let mut newName = String::with_capacity(100);
maybeAppendComponent(components, 3, newName); maybeAppendComponent(&components, 3, &mut newName);
maybeAppendComponent(components, 1, newName); maybeAppendComponent(&components, 1, &mut newName);
maybeAppendComponent(components, 2, newName); maybeAppendComponent(&components, 2, &mut newName);
maybeAppendComponent(components, 0, newName); maybeAppendComponent(&components, 0, &mut newName);
maybeAppendComponent(components, 4, newName); maybeAppendComponent(&components, 4, &mut newName);
list.set(0, newName.toString().trim()); list[0] = newName.trim().to_owned();
} }
} }
} }