Struct rialight_intl::Locale

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 as key, extensions_unicode_value as value,
    locale, subtags_language as language, subtags_region as 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 canonicalization 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§

§

impl Locale

pub fn try_from_bytes(v: &[u8]) -> Result<Locale, 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();

pub const UND: Locale = Self{ id: LanguageIdentifier::UND, extensions: extensions::Extensions::new(),}

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

Examples
use icu::locid::Locale;

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

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

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")
);

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);
}

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

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()
);

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 structucal comparison.

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-Japanese",
    "ZH",
];

for a in bcp47_strings {
    assert!(a.parse::<Locale>().unwrap().normalizing_eq(a));
}

Trait Implementations§

§

impl AsMut<LanguageIdentifier> for Locale

§

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

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

impl AsRef<LanguageIdentifier> for Locale

§

fn as_ref(&self) -> &LanguageIdentifier

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

impl Clone for Locale

§

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
§

impl Debug for Locale

§

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

Formats the value using the given formatter. Read more
§

impl Default for Locale

§

fn default() -> Locale

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

impl Display for Locale

This trait is implemented for compatibility with fmt!. To create a string, [Writeable::write_to_string] is usually more efficient.

§

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

Formats the value using the given formatter. Read more
§

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

Examples

use icu::locid::Locale;
use icu::locid::{
    locale, subtags_language as language, subtags_region as region,
    subtags_script as script,
};

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

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

Converts to this type from the input type.
§

impl From<Language> for Locale

Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags_language as language};

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

fn from(language: Language) -> Locale

Converts to this type from the input type.
§

impl From<LanguageIdentifier> for Locale

§

fn from(id: LanguageIdentifier) -> Locale

Converts to this type from the input type.
§

impl From<Locale> for LanguageIdentifier

§

fn from(loc: Locale) -> LanguageIdentifier

Converts to this type from the input type.
§

impl From<Option<Region>> for Locale

Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags_region as region};

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

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

Converts to this type from the input type.
§

impl From<Option<Script>> for Locale

Examples

use icu::locid::Locale;
use icu::locid::{locale, subtags_script as script};

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

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

Converts to this type from the input type.
§

impl FromStr for Locale

§

type Err = ParserError

The associated error which can be returned from parsing.
§

fn from_str(source: &str) -> Result<Locale, <Locale as FromStr>::Err>

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

impl HasTextDirection for Locale

§

impl Hash for Locale

§

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

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
§

impl PartialEq<Locale> for Locale

§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

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

impl Writeable for Locale

§

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

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

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
§

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
§

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

impl Eq for Locale

§

impl StructuralEq for Locale

§

impl StructuralPartialEq for Locale

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AnyEq for Twhere T: Any + PartialEq<T>,

§

fn equals(&self, other: &(dyn Any + 'static)) -> bool

§

fn as_any(&self) -> &(dyn Any + 'static)

source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

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

const: unstable · 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 Twhere T: Clone,

§

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 Twhere 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

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

§

impl<T> MaybeSendSync for T