icu_locale

Struct DataLocale

#[non_exhaustive]
pub struct DataLocale { pub language: Language, pub script: Option<Script>, pub region: Option<Region>, pub variant: Option<Variant>, pub subdivision: Option<Subtag>, }
Expand description

A locale type optimized for use in fallbacking and the ICU4X data pipeline.

DataLocale contains less functionality than Locale but more than LanguageIdentifier for better size and performance while still meeting the needs of the ICU4X data pipeline.

You can create a DataLocale from a borrowed Locale, which is more efficient than cloning the Locale, but less efficient than converting an owned Locale:

use icu_locale_core::locale;
use icu_provider::DataLocale;

let locale1 = locale!("en-u-ca-buddhist");
let data_locale = DataLocale::from(&locale1);

DataLocale only supports -u-sd keywords, to reflect the current state of CLDR data lookup and fallback. This may change in the future.

use icu_locale_core::{locale, Locale};
use icu_provider::DataLocale;

let locale = "hi-IN-t-en-h0-hybrid-u-attr-ca-buddhist-sd-inas"
    .parse::<Locale>()
    .unwrap();

assert_eq!(
    DataLocale::from(locale),
    DataLocale::from(locale!("hi-IN-u-sd-inas"))
);

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§language: Language

Language subtag

§script: Option<Script>

Script subtag

§region: Option<Region>

Region subtag

§variant: Option<Variant>

Variant subtag

§subdivision: Option<Subtag>

Subivision (-u-sd-) subtag

Implementations§

§

impl DataLocale

pub const fn default() -> DataLocale

const version of Default::default

§

impl DataLocale

pub fn to_string(&self) -> String

Converts the given value to a String.

Under the hood, this uses an efficient [Writeable] implementation. However, in order to avoid allocating a string, it is more efficient to use [Writeable] directly.

§

impl DataLocale

pub fn try_from_str(s: &str) -> Result<DataLocale, ParseError>

Parses a DataLocale.

pub fn try_from_utf8(code_units: &[u8]) -> Result<DataLocale, ParseError>

Parses a DataLocale from a UTF-8 byte slice.

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

Returns an ordering suitable for use in BTreeSet.

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

Compare this DataLocale with BCP-47 bytes.

The return value is equivalent to what would happen if you first converted this DataLocale 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 core::cmp::Ordering;
use icu_provider::DataLocale;

let bcp47_strings: &[&str] = &[
    "ca",
    "ca-ES",
    "ca-ES-u-sd-esct",
    "ca-ES-valencia",
    "cat",
    "pl-Latn-PL",
    "und",
    "und-fonipa",
    "zh",
];

for ab in bcp47_strings.windows(2) {
    let a = ab[0];
    let b = ab[1];
    assert_eq!(a.cmp(b), Ordering::Less, "strings: {} < {}", a, b);
    let a_loc: DataLocale = a.parse().unwrap();
    assert_eq!(
        a_loc.strict_cmp(a.as_bytes()),
        Ordering::Equal,
        "strict_cmp: {} == {}",
        a_loc,
        a
    );
    assert_eq!(
        a_loc.strict_cmp(b.as_bytes()),
        Ordering::Less,
        "strict_cmp: {} < {}",
        a_loc,
        b
    );
    let b_loc: DataLocale = b.parse().unwrap();
    assert_eq!(
        b_loc.strict_cmp(b.as_bytes()),
        Ordering::Equal,
        "strict_cmp: {} == {}",
        b_loc,
        b
    );
    assert_eq!(
        b_loc.strict_cmp(a.as_bytes()),
        Ordering::Greater,
        "strict_cmp: {} > {}",
        b_loc,
        a
    );
}

Comparison against invalid strings:

use icu_provider::DataLocale;

let invalid_strings: &[&str] = &[
    // Less than "ca-ES"
    "CA",
    "ar-x-gbp-FOO",
    // Greater than "ca-AR"
    "ca_ES",
    "ca-ES-x-gbp-FOO",
];

let data_locale = "ca-ES".parse::<DataLocale>().unwrap();

for s in invalid_strings.iter() {
    let expected_ordering = "ca-AR".cmp(s);
    let actual_ordering = data_locale.strict_cmp(s.as_bytes());
    assert_eq!(expected_ordering, actual_ordering, "{}", s);
}

pub fn is_default(&self) -> bool

Returns whether this DataLocale is und in the locale and extensions portion.

§Examples
use icu_provider::DataLocale;

assert!("und".parse::<DataLocale>().unwrap().is_default());
assert!(!"de-u-sd-denw".parse::<DataLocale>().unwrap().is_default());
assert!(!"und-ES".parse::<DataLocale>().unwrap().is_default());

pub fn into_locale(self) -> Locale

Converts this DataLocale into a Locale.

Trait Implementations§

§

impl Clone for DataLocale

§

fn clone(&self) -> DataLocale

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 DataLocale

§

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

Formats the value using the given formatter. Read more
§

impl Default for &DataLocale

§

fn default() -> &DataLocale

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

impl Default for DataLocale

§

fn default() -> DataLocale

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

impl Display for DataLocale

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<&LanguageIdentifier> for DataLocale

§

fn from(langid: &LanguageIdentifier) -> DataLocale

Converts to this type from the input type.
§

impl From<&Locale> for DataLocale

§

fn from(locale: &Locale) -> DataLocale

Converts to this type from the input type.
§

impl From<LanguageIdentifier> for DataLocale

§

fn from(langid: LanguageIdentifier) -> DataLocale

Converts to this type from the input type.
§

impl From<Locale> for DataLocale

§

fn from(locale: Locale) -> DataLocale

Converts to this type from the input type.
§

impl FromStr for DataLocale

§

type Err = ParseError

The associated error which can be returned from parsing.
§

fn from_str(s: &str) -> Result<DataLocale, <DataLocale as FromStr>::Err>

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

impl Hash for DataLocale

§

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 for DataLocale

§

fn eq(&self, other: &DataLocale) -> 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.
§

impl Writeable for DataLocale

§

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 Copy for DataLocale

§

impl Eq for DataLocale

§

impl StructuralPartialEq for DataLocale

Auto Trait Implementations§

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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

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

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