icu_locid

Struct Locale

Source
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.

§Examples

use icu::locid::{
    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"))
);

§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 bogus subtags will cause the parsing to fail with an error.

No subtag validation or alias resolution is performed.

§Examples

use icu::locid::{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

Source

pub const UND: Self = _

The default undefined locale “und”. Same as default().

§Examples
use icu::locid::Locale;

assert_eq!(Locale::default(), Locale::UND);
Source

pub fn try_from_bytes(v: &[u8]) -> Result<Self, ParserError>

A constructor which takes a utf8 slice, parses it and produces a well-formed Locale.

§Examples
use icu::locid::Locale;

Locale::try_from_bytes(b"en-US-u-hc-h12").unwrap();
Source

pub fn canonicalize<S: AsRef<[u8]>>(input: S) -> Result<String, ParserError>

This is a best-effort operation that performs all available levels of canonicalization.

At the moment the operation will normalize casing and the separator, but in the future it may also validate and update from deprecated subtags to canonical ones.

§Examples
use icu::locid::Locale;

assert_eq!(
    Locale::canonicalize("pL_latn_pl-U-HC-H12").as_deref(),
    Ok("pl-Latn-PL-u-hc-h12")
);
Source

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
use icu::locid::Locale;
use std::cmp::Ordering;

let bcp47_strings: &[&str] = &[
    "pl-Latn-PL",
    "und",
    "und-fonipa",
    "und-t-m0-true",
    "und-u-ca-hebrew",
    "und-u-ca-japanese",
    "zh",
];

for ab in bcp47_strings.windows(2) {
    let a = ab[0];
    let b = ab[1];
    assert!(a.cmp(b) == Ordering::Less);
    let a_loc = a.parse::<Locale>().unwrap();
    assert!(a_loc.strict_cmp(a.as_bytes()) == Ordering::Equal);
    assert!(a_loc.strict_cmp(b.as_bytes()) == Ordering::Less);
}
Source

pub fn total_cmp(&self, other: &Self) -> Ordering

Returns an ordering suitable for use in BTreeSet.

The ordering may or may not be equivalent to string ordering, and it may or may not be stable across ICU4X releases.

Source

pub fn strict_cmp_iter<'l, I>(&self, subtags: I) -> SubtagOrderingResult<I>
where I: Iterator<Item = &'l [u8]>,

👎Deprecated since 1.5.0: if you need this, please file an issue

Compare this Locale with an iterator of BCP-47 subtags.

This function has the same equality semantics as Locale::strict_cmp. It is intended as a more modular version that allows multiple subtag iterators to be chained together.

For an additional example, see SubtagOrderingResult.

§Examples
use icu::locid::locale;
use std::cmp::Ordering;

let subtags: &[&[u8]] =
    &[b"ca", b"ES", b"valencia", b"u", b"ca", b"hebrew"];

let loc = locale!("ca-ES-valencia-u-ca-hebrew");
assert_eq!(
    Ordering::Equal,
    loc.strict_cmp_iter(subtags.iter().copied()).end()
);

let loc = locale!("ca-ES-valencia");
assert_eq!(
    Ordering::Less,
    loc.strict_cmp_iter(subtags.iter().copied()).end()
);

let loc = locale!("ca-ES-valencia-u-nu-arab");
assert_eq!(
    Ordering::Greater,
    loc.strict_cmp_iter(subtags.iter().copied()).end()
);
Source

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::locid::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 AsMut<LanguageIdentifier> for Locale

Source§

fn as_mut(&mut self) -> &mut LanguageIdentifier

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<LanguageIdentifier> for Locale

Source§

fn as_ref(&self) -> &LanguageIdentifier

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Locale

Source§

fn clone(&self) -> Locale

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Locale

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Locale

Source§

fn default() -> Locale

Returns the “default value” for a type. Read more
Source§

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§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<(Language, Option<Script>, Option<Region>)> for Locale

§Examples

use icu::locid::Locale;
use icu::locid::{
    locale,
    subtags::{language, region, script},
};

assert_eq!(
    Locale::from((
        language!("en"),
        Some(script!("Latn")),
        Some(region!("US"))
    )),
    locale!("en-Latn-US")
);
Source§

fn from(lsr: (Language, Option<Script>, Option<Region>)) -> Self

Converts to this type from the input type.
Source§

impl From<Language> for Locale

§Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags::language};

assert_eq!(Locale::from(language!("en")), locale!("en"));
Source§

fn from(language: Language) -> Self

Converts to this type from the input type.
Source§

impl From<LanguageIdentifier> for Locale

Source§

fn from(id: LanguageIdentifier) -> Self

Converts to this type from the input type.
Source§

impl From<Locale> for LanguageIdentifier

Source§

fn from(loc: Locale) -> Self

Converts to this type from the input type.
Source§

impl From<Option<Region>> for Locale

§Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags::region};

assert_eq!(Locale::from(Some(region!("US"))), locale!("und-US"));
Source§

fn from(region: Option<Region>) -> Self

Converts to this type from the input type.
Source§

impl From<Option<Script>> for Locale

§Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags::script};

assert_eq!(Locale::from(Some(script!("latn"))), locale!("und-Latn"));
Source§

fn from(script: Option<Script>) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Locale

Source§

type Err = ParserError

The associated error which can be returned from parsing.
Source§

fn from_str(source: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Locale

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Locale

Source§

fn eq(&self, other: &Locale) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Writeable for Locale

Source§

fn write_to<W: Write + ?Sized>(&self, sink: &mut W) -> Result

Writes a string to the given sink. Errors from the sink are bubbled up. The default implementation delegates to write_to_parts, and discards any Part annotations.
Source§

fn writeable_length_hint(&self) -> LengthHint

Returns a hint for the number of UTF-8 bytes that will be written to the sink. Read more
Source§

fn write_to_string(&self) -> Cow<'_, str>

Creates a new String with the data from this Writeable. Like ToString, but smaller and faster. Read more
Source§

fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>
where S: PartsWrite + ?Sized,

Write bytes and 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.
Source§

fn writeable_cmp_bytes(&self, other: &[u8]) -> Ordering

Compares the contents of this Writeable to the given bytes without allocating a String to hold the Writeable contents. Read more
Source§

impl Eq for Locale

Source§

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> ErasedDestructor for T
where T: 'static,