use super::form_address_data::{CountryFormat, COUNTRIES}; use super::funejson::Value; // The UK and the Crown Dependencies share Royal Mail's postcode format. const UK_FAMILY: [&str; 4] = ["GB", "GG", "JE", "IM"]; /// Leading and trailing ASCII whitespace removed, the same in every language. pub fn trim_ascii(value: &str) -> &str { value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b')) } /// ASCII letters upper-cased; everything else as it is. pub fn upper_ascii(value: &str) -> String { value.to_ascii_uppercase() } /// Whether a country code (already upper case) uses the UK postcode format. pub fn is_uk_family(code: &str) -> bool { UK_FAMILY.contains(&code) } /// The country's row, by its code as typed (trimmed, any case), or None. pub fn lookup_country(country: &str) -> Option<&'static CountryFormat> { let code = upper_ascii(trim_ascii(country)); COUNTRIES.iter().find(|row| row.code == code) } /// How an address form for a country labels and checks its fields. /// /// # Panics /// Panics on a code that is not an ISO 3166-1 alpha-2 country. pub fn address_format(country: &str) -> AddressFormat { let row = match lookup_country(country) { Some(row) => row, None => panic!("unknown country \"{}\": give an ISO 3166-1 alpha-2 code, such as GB, US or DE", country), }; AddressFormat { country: row.code.to_string(), name: row.name.to_string(), uk: is_uk_family(row.code), postcode_label: row.postcode_label.to_string(), postcode_required: row.postcode_required, postcode_example: row.postcode_example.map(|s| s.to_string()), region_label: row.region_label.to_string(), } } pub fn address_format_to_value(format: &AddressFormat) -> Value { Value::obj(vec![ ("country", Value::str(&format.country)), ("name", Value::str(&format.name)), ("uk", Value::Bool(format.uk)), ("postcodeLabel", Value::str(&format.postcode_label)), ("postcodeRequired", Value::Bool(format.postcode_required)), ("postcodeExample", format.postcode_example.as_deref().map(Value::str).unwrap_or(Value::Null)), ("regionLabel", Value::str(&format.region_label)), ]) } pub fn fune_vector(args: &[Value]) -> Value { address_format_to_value(&address_format(args[0].as_str())) }