pub struct Locale {
pub id: LanguageIdentifier,
pub extensions: Extensions,
}
Expand description
A core struct representing a Unicode Locale Identifier
.
A locale is made of two parts:
- Unicode Language Identifier
- A set of Unicode Extensions
Locale
exposes all of the same fields and methods as LanguageIdentifier
, and
on top of that is able to parse, manipulate and serialize unicode extension fields.
§Ordering
This type deliberately does not implement Ord
or PartialOrd
because there are
multiple possible orderings. Depending on your use case, two orderings are available:
- A string ordering, suitable for stable serialization:
Locale::strict_cmp
- A struct ordering, suitable for use with a BTreeSet:
Locale::total_cmp
See issue: https://github.com/unicode-org/icu4x/issues/1215
§Parsing
Unicode recognizes three levels of standard conformance for a locale:
- well-formed - syntactically correct
- valid - well-formed and only uses registered language subtags, extensions, keywords, types…
- canonical - valid and no deprecated codes or structure.
At the moment parsing normalizes a well-formed locale identifier converting
_
separators to -
and adjusting casing to conform to the Unicode standard.
Any syntactically invalid subtags will cause the parsing to fail with an error.
This operation normalizes syntax to be well-formed. No legacy subtag replacements is performed.
For validation and canonicalization, see LocaleCanonicalizer
.
§Examples
Simple example:
use icu::locale::{
extensions::unicode::{key, value},
locale,
subtags::{language, region},
};
let loc = locale!("en-US-u-ca-buddhist");
assert_eq!(loc.id.language, language!("en"));
assert_eq!(loc.id.script, None);
assert_eq!(loc.id.region, Some(region!("US")));
assert_eq!(loc.id.variants.len(), 0);
assert_eq!(
loc.extensions.unicode.keywords.get(&key!("ca")),
Some(&value!("buddhist"))
);
More complex example:
use icu::locale::{subtags::*, Locale};
let loc: Locale = "eN_latn_Us-Valencia_u-hC-H12"
.parse()
.expect("Failed to parse.");
assert_eq!(loc.id.language, "en".parse::<Language>().unwrap());
assert_eq!(loc.id.script, "Latn".parse::<Script>().ok());
assert_eq!(loc.id.region, "US".parse::<Region>().ok());
assert_eq!(
loc.id.variants.get(0),
"valencia".parse::<Variant>().ok().as_ref()
);
Fields§
§id: LanguageIdentifier
The basic language/script/region components in the locale identifier along with any variants.
extensions: Extensions
Any extensions present in the locale identifier.
Implementations§
source§impl Locale
impl Locale
sourcepub fn try_from_str(s: &str) -> Result<Locale, ParseError>
pub fn try_from_str(s: &str) -> Result<Locale, ParseError>
sourcepub fn try_from_utf8(code_units: &[u8]) -> Result<Locale, ParseError>
pub fn try_from_utf8(code_units: &[u8]) -> Result<Locale, ParseError>
sourcepub const fn default() -> Locale
pub const fn default() -> Locale
Const-friendly version of Default::default
.
sourcepub fn normalize_utf8(input: &[u8]) -> Result<Cow<'_, str>, ParseError>
pub fn normalize_utf8(input: &[u8]) -> Result<Cow<'_, str>, ParseError>
Normalize the locale (operating on UTF-8 formatted byte slices)
This operation will normalize casing and the separator.
§Examples
use icu::locale::Locale;
assert_eq!(
Locale::normalize_utf8(b"pL_latn_pl-U-HC-H12").as_deref(),
Ok("pl-Latn-PL-u-hc-h12")
);
sourcepub fn normalize(input: &str) -> Result<Cow<'_, str>, ParseError>
pub fn normalize(input: &str) -> Result<Cow<'_, str>, ParseError>
Normalize the locale (operating on strings)
This operation will normalize casing and the separator.
§Examples
use icu::locale::Locale;
assert_eq!(
Locale::normalize("pL_latn_pl-U-HC-H12").as_deref(),
Ok("pl-Latn-PL-u-hc-h12")
);
sourcepub fn strict_cmp(&self, other: &[u8]) -> Ordering
pub fn strict_cmp(&self, other: &[u8]) -> Ordering
Compare this Locale
with BCP-47 bytes.
The return value is equivalent to what would happen if you first converted this
Locale
to a BCP-47 string and then performed a byte comparison.
This function is case-sensitive and results in a total order, so it is appropriate for
binary search. The only argument producing Ordering::Equal
is self.to_string()
.
§Examples
Sorting a list of locales with this method requires converting one of them to a string:
use icu::locale::Locale;
use std::cmp::Ordering;
use writeable::Writeable;
// Random input order:
let bcp47_strings: &[&str] = &[
"und-u-ca-hebrew",
"ar-Latn",
"zh-Hant-TW",
"zh-TW",
"und-fonipa",
"zh-Hant",
"ar-SA",
];
let mut locales = bcp47_strings.iter().map(|s| s.parse().unwrap()).collect::<Vec<Locale>>();
locales.sort_by(|a, b| {
let b = b.write_to_string();
a.strict_cmp(b.as_bytes())
});
let strict_cmp_strings = locales.iter().map(|l| l.to_string()).collect::<Vec<String>>();
// Output ordering, sorted alphabetically
let expected_ordering: &[&str] = &[
"ar-Latn",
"ar-SA",
"und-fonipa",
"und-u-ca-hebrew",
"zh-Hant",
"zh-Hant-TW",
"zh-TW",
];
assert_eq!(expected_ordering, strict_cmp_strings);
sourcepub fn total_cmp(&self, other: &Locale) -> Ordering
pub fn total_cmp(&self, other: &Locale) -> Ordering
Returns an ordering suitable for use in BTreeSet
.
Unlike Locale::strict_cmp
, the ordering may or may not be equivalent
to string ordering, and it may or may not be stable across ICU4X releases.
§Examples
This method returns a nonsensical ordering derived from the fields of the struct:
use icu::locale::Locale;
use std::cmp::Ordering;
// Input strings, sorted alphabetically
let bcp47_strings: &[&str] = &[
"ar-Latn",
"ar-SA",
"und-fonipa",
"und-u-ca-hebrew",
"zh-Hant",
"zh-Hant-TW",
"zh-TW",
];
assert!(bcp47_strings.windows(2).all(|w| w[0] < w[1]));
let mut locales = bcp47_strings.iter().map(|s| s.parse().unwrap()).collect::<Vec<Locale>>();
locales.sort_by(Locale::total_cmp);
let total_cmp_strings = locales.iter().map(|l| l.to_string()).collect::<Vec<String>>();
// Output ordering, sorted arbitrarily
let expected_ordering: &[&str] = &[
"ar-SA",
"ar-Latn",
"und-u-ca-hebrew",
"und-fonipa",
"zh-TW",
"zh-Hant",
"zh-Hant-TW",
];
assert_eq!(expected_ordering, total_cmp_strings);
Use a wrapper to add a Locale
to a BTreeSet
:
use icu::locale::Locale;
use std::cmp::Ordering;
use std::collections::BTreeSet;
#[derive(PartialEq, Eq)]
struct LocaleTotalOrd(Locale);
impl Ord for LocaleTotalOrd {
fn cmp(&self, other: &Self) -> Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for LocaleTotalOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
let _: BTreeSet<LocaleTotalOrd> = unimplemented!();
sourcepub fn normalizing_eq(&self, other: &str) -> bool
pub fn normalizing_eq(&self, other: &str) -> bool
Compare this Locale
with a potentially unnormalized BCP-47 string.
The return value is equivalent to what would happen if you first parsed the
BCP-47 string to a Locale
and then performed a structural comparison.
§Examples
use icu::locale::Locale;
let bcp47_strings: &[&str] = &[
"pl-LaTn-pL",
"uNd",
"UND-FONIPA",
"UnD-t-m0-TrUe",
"uNd-u-CA-Japanese",
"ZH",
];
for a in bcp47_strings {
assert!(a.parse::<Locale>().unwrap().normalizing_eq(a));
}
Trait Implementations§
source§impl Display for Locale
impl Display for Locale
This trait is implemented for compatibility with fmt!
.
To create a string, [Writeable::write_to_string
] is usually more efficient.
source§impl From<&Locale> for AnyCalendarPreferences
impl From<&Locale> for AnyCalendarPreferences
source§fn from(loc: &Locale) -> AnyCalendarPreferences
fn from(loc: &Locale) -> AnyCalendarPreferences
source§impl From<&Locale> for CollatorPreferences
impl From<&Locale> for CollatorPreferences
source§fn from(loc: &Locale) -> CollatorPreferences
fn from(loc: &Locale) -> CollatorPreferences
source§impl From<&Locale> for CurrencyFormatterPreferences
impl From<&Locale> for CurrencyFormatterPreferences
source§fn from(loc: &Locale) -> CurrencyFormatterPreferences
fn from(loc: &Locale) -> CurrencyFormatterPreferences
source§impl From<&Locale> for DateTimeFormatterPreferences
impl From<&Locale> for DateTimeFormatterPreferences
source§fn from(loc: &Locale) -> DateTimeFormatterPreferences
fn from(loc: &Locale) -> DateTimeFormatterPreferences
source§impl From<&Locale> for FixedDecimalFormatterPreferences
impl From<&Locale> for FixedDecimalFormatterPreferences
source§fn from(loc: &Locale) -> FixedDecimalFormatterPreferences
fn from(loc: &Locale) -> FixedDecimalFormatterPreferences
source§impl From<&Locale> for ListFormatterPreferences
impl From<&Locale> for ListFormatterPreferences
source§fn from(loc: &Locale) -> ListFormatterPreferences
fn from(loc: &Locale) -> ListFormatterPreferences
source§impl From<&Locale> for LocalePreferences
impl From<&Locale> for LocalePreferences
source§fn from(loc: &Locale) -> LocalePreferences
fn from(loc: &Locale) -> LocalePreferences
source§impl From<&Locale> for PercentFormatterPreferences
impl From<&Locale> for PercentFormatterPreferences
source§fn from(loc: &Locale) -> PercentFormatterPreferences
fn from(loc: &Locale) -> PercentFormatterPreferences
source§impl From<&Locale> for PluralRulesPreferences
impl From<&Locale> for PluralRulesPreferences
source§fn from(loc: &Locale) -> PluralRulesPreferences
fn from(loc: &Locale) -> PluralRulesPreferences
source§impl From<&Locale> for UnitsFormatterPreferences
impl From<&Locale> for UnitsFormatterPreferences
source§fn from(loc: &Locale) -> UnitsFormatterPreferences
fn from(loc: &Locale) -> UnitsFormatterPreferences
source§impl From<(Language, Option<Script>, Option<Region>)> for Locale
impl From<(Language, Option<Script>, Option<Region>)> for Locale
§Examples
use icu::locale::Locale;
use icu::locale::{
locale,
subtags::{language, region, script},
};
assert_eq!(
Locale::from((
language!("en"),
Some(script!("Latn")),
Some(region!("US"))
)),
locale!("en-Latn-US")
);
source§impl From<AnyCalendarPreferences> for Locale
impl From<AnyCalendarPreferences> for Locale
source§fn from(other: AnyCalendarPreferences) -> Locale
fn from(other: AnyCalendarPreferences) -> Locale
source§impl From<CollatorPreferences> for Locale
impl From<CollatorPreferences> for Locale
source§fn from(other: CollatorPreferences) -> Locale
fn from(other: CollatorPreferences) -> Locale
source§impl From<CurrencyFormatterPreferences> for Locale
impl From<CurrencyFormatterPreferences> for Locale
source§fn from(other: CurrencyFormatterPreferences) -> Locale
fn from(other: CurrencyFormatterPreferences) -> Locale
source§impl From<DateTimeFormatterPreferences> for Locale
impl From<DateTimeFormatterPreferences> for Locale
source§fn from(other: DateTimeFormatterPreferences) -> Locale
fn from(other: DateTimeFormatterPreferences) -> Locale
source§impl From<FixedDecimalFormatterPreferences> for Locale
impl From<FixedDecimalFormatterPreferences> for Locale
source§fn from(other: FixedDecimalFormatterPreferences) -> Locale
fn from(other: FixedDecimalFormatterPreferences) -> Locale
source§impl From<HelloWorldFormatterPreferences> for Locale
impl From<HelloWorldFormatterPreferences> for Locale
source§fn from(other: HelloWorldFormatterPreferences) -> Locale
fn from(other: HelloWorldFormatterPreferences) -> Locale
source§impl From<Language> for Locale
impl From<Language> for Locale
§Examples
use icu::locale::Locale;
use icu::locale::{locale, subtags::language};
assert_eq!(Locale::from(language!("en")), locale!("en"));
source§impl From<LanguageIdentifier> for Locale
impl From<LanguageIdentifier> for Locale
source§fn from(id: LanguageIdentifier) -> Locale
fn from(id: LanguageIdentifier) -> Locale
source§impl From<ListFormatterPreferences> for Locale
impl From<ListFormatterPreferences> for Locale
source§fn from(other: ListFormatterPreferences) -> Locale
fn from(other: ListFormatterPreferences) -> Locale
source§impl From<Locale> for AnyCalendarPreferences
impl From<Locale> for AnyCalendarPreferences
source§fn from(loc: Locale) -> AnyCalendarPreferences
fn from(loc: Locale) -> AnyCalendarPreferences
source§impl From<Locale> for CollatorPreferences
impl From<Locale> for CollatorPreferences
source§fn from(loc: Locale) -> CollatorPreferences
fn from(loc: Locale) -> CollatorPreferences
source§impl From<Locale> for CurrencyFormatterPreferences
impl From<Locale> for CurrencyFormatterPreferences
source§fn from(loc: Locale) -> CurrencyFormatterPreferences
fn from(loc: Locale) -> CurrencyFormatterPreferences
source§impl From<Locale> for DateTimeFormatterPreferences
impl From<Locale> for DateTimeFormatterPreferences
source§fn from(loc: Locale) -> DateTimeFormatterPreferences
fn from(loc: Locale) -> DateTimeFormatterPreferences
source§impl From<Locale> for FixedDecimalFormatterPreferences
impl From<Locale> for FixedDecimalFormatterPreferences
source§fn from(loc: Locale) -> FixedDecimalFormatterPreferences
fn from(loc: Locale) -> FixedDecimalFormatterPreferences
source§impl From<Locale> for LanguageIdentifier
impl From<Locale> for LanguageIdentifier
source§fn from(loc: Locale) -> LanguageIdentifier
fn from(loc: Locale) -> LanguageIdentifier
source§impl From<Locale> for ListFormatterPreferences
impl From<Locale> for ListFormatterPreferences
source§fn from(loc: Locale) -> ListFormatterPreferences
fn from(loc: Locale) -> ListFormatterPreferences
source§impl From<Locale> for PercentFormatterPreferences
impl From<Locale> for PercentFormatterPreferences
source§fn from(loc: Locale) -> PercentFormatterPreferences
fn from(loc: Locale) -> PercentFormatterPreferences
source§impl From<Locale> for PluralRulesPreferences
impl From<Locale> for PluralRulesPreferences
source§fn from(loc: Locale) -> PluralRulesPreferences
fn from(loc: Locale) -> PluralRulesPreferences
source§impl From<Locale> for UnitsFormatterPreferences
impl From<Locale> for UnitsFormatterPreferences
source§fn from(loc: Locale) -> UnitsFormatterPreferences
fn from(loc: Locale) -> UnitsFormatterPreferences
source§impl From<LocalePreferences> for Locale
impl From<LocalePreferences> for Locale
source§fn from(prefs: LocalePreferences) -> Locale
fn from(prefs: LocalePreferences) -> Locale
source§impl From<Option<Region>> for Locale
impl From<Option<Region>> for Locale
§Examples
use icu::locale::Locale;
use icu::locale::{locale, subtags::region};
assert_eq!(Locale::from(Some(region!("US"))), locale!("und-US"));
source§impl From<Option<Script>> for Locale
impl From<Option<Script>> for Locale
§Examples
use icu::locale::Locale;
use icu::locale::{locale, subtags::script};
assert_eq!(Locale::from(Some(script!("latn"))), locale!("und-Latn"));
source§impl From<PercentFormatterPreferences> for Locale
impl From<PercentFormatterPreferences> for Locale
source§fn from(other: PercentFormatterPreferences) -> Locale
fn from(other: PercentFormatterPreferences) -> Locale
source§impl From<PluralRulesPreferences> for Locale
impl From<PluralRulesPreferences> for Locale
source§fn from(other: PluralRulesPreferences) -> Locale
fn from(other: PluralRulesPreferences) -> Locale
source§impl From<UnitsFormatterPreferences> for Locale
impl From<UnitsFormatterPreferences> for Locale
source§fn from(other: UnitsFormatterPreferences) -> Locale
fn from(other: UnitsFormatterPreferences) -> Locale
source§impl Writeable for Locale
impl Writeable for Locale
source§fn write_to<W>(&self, sink: &mut W) -> Result<(), Error>
fn write_to<W>(&self, sink: &mut W) -> Result<(), Error>
write_to_parts
, and discards any
Part
annotations.source§fn writeable_length_hint(&self) -> LengthHint
fn writeable_length_hint(&self) -> LengthHint
source§fn write_to_string(&self) -> Cow<'_, str>
fn write_to_string(&self) -> Cow<'_, str>
String
with the data from this Writeable
. Like ToString
,
but smaller and faster. Read moresource§fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>where
S: PartsWrite + ?Sized,
fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>where
S: PartsWrite + ?Sized,
Part
annotations to the given sink. Errors from the
sink are bubbled up. The default implementation delegates to write_to
,
and doesn’t produce any Part
annotations.impl Eq for Locale
impl StructuralPartialEq for Locale
Auto Trait Implementations§
impl Freeze for Locale
impl RefUnwindSafe for Locale
impl Send for Locale
impl Sync for Locale
impl Unpin for Locale
impl UnwindSafe for Locale
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more