Enum icu::pattern::MultiNamedPlaceholder

source ·
pub enum MultiNamedPlaceholder {}
Expand description

Backend for patterns containing zero or more named placeholders.

This empty type is not constructible.

§Placeholder Keys

The placeholder is MultiNamedPlaceholderKey.

In Pattern::interpolate(), pass a map-like structure. Missing keys will be replaced with the Unicode replacement character U+FFFD.

§Encoding Details

The literals and placeholders are stored in context. A placeholder is encoded as a name length in octal code points followed by the placeholder name.

For example, consider the pattern: “Hello, {user} and {someone_else}!”

The encoding for this would be:

Hello, \x00\x04user and \x01\x04someone_else!

where \x00\x04 and \x01\x04 are a big-endian octal number representing the lengths of their respective placeholder names.

Consequences of this encoding:

  1. The maximum placeholder name length is 64 bytes
  2. Code points in the range \x00 through \x07 are reserved for the placeholder name

§Examples

Example patterns supported by this backend:

use core::str::FromStr;
use icu_pattern::MultiNamedPlaceholder;
use icu_pattern::Pattern;
use std::collections::BTreeMap;

let placeholder_value_map: BTreeMap<&str, &str> = [
    ("num", "5"),
    ("letter", "X"),
    ("", "empty"),
    ("unused", "unused"),
]
.into_iter()
.collect();

// Single placeholder:
assert_eq!(
    Pattern::<MultiNamedPlaceholder>::try_from_str(
        "{num} days ago",
        Default::default()
    )
    .unwrap()
    .try_interpolate_to_string(&placeholder_value_map)
    .unwrap(),
    "5 days ago",
);

// No placeholder (note, the placeholder value is never accessed):
assert_eq!(
    Pattern::<MultiNamedPlaceholder>::try_from_str(
        "yesterday",
        Default::default()
    )
    .unwrap()
    .try_interpolate_to_string(&placeholder_value_map)
    .unwrap(),
    "yesterday",
);

// No literals, only placeholders:
assert_eq!(
    Pattern::<MultiNamedPlaceholder>::try_from_str(
        "{letter}{num}{}",
        Default::default()
    )
    .unwrap()
    .try_interpolate_to_string(&placeholder_value_map)
    .unwrap(),
    "X5empty",
);

Use LiteMap for alloc-free formatting:

use core::str::FromStr;
use icu_pattern::MultiNamedPlaceholderPattern;
use litemap::LiteMap;
use writeable::TryWriteable;

static placeholder_value_map: LiteMap<&str, usize, &[(&str, usize)]> =
    LiteMap::from_sorted_store_unchecked(&[("seven", 11)]);

// Note: String allocates, but this could be a non-allocating sink
let mut sink = String::new();

MultiNamedPlaceholderPattern::try_from_str("{seven}", Default::default())
    .unwrap()
    .try_interpolate(&placeholder_value_map)
    .try_write_to(&mut sink)
    .unwrap()
    .unwrap();

assert_eq!(sink, "11");

Missing placeholder values cause an error result to be returned. However, based on the design of TryWriteable, the error can be discarded to get a best-effort interpolation with potential replacement characters.

use core::str::FromStr;
use icu_pattern::MultiNamedPlaceholder;
use icu_pattern::Pattern;
use std::collections::BTreeMap;

let placeholder_value_map: BTreeMap<&str, &str> =
    [("num", "5"), ("letter", "X")].into_iter().collect();

Pattern::<MultiNamedPlaceholder>::try_from_str(
    "Your name is {your_name}",
    Default::default(),
)
.unwrap()
.try_interpolate_to_string(&placeholder_value_map)
.unwrap();

Recover the best-effort lossy string by directly using Pattern::try_interpolate():

use core::str::FromStr;
use icu_pattern::MissingNamedPlaceholderError;
use icu_pattern::MultiNamedPlaceholder;
use icu_pattern::Pattern;
use std::borrow::Cow;
use std::collections::BTreeMap;
use writeable::TryWriteable;

let placeholder_value_map: BTreeMap<&str, &str> =
    [("num", "5"), ("letter", "X")].into_iter().collect();

let pattern = Pattern::<MultiNamedPlaceholder>::try_from_str(
    "Your name is {your_name}",
    Default::default(),
)
.unwrap();

let mut buffer = String::new();
let result = pattern
    .try_interpolate(&placeholder_value_map)
    .try_write_to(&mut buffer)
    .expect("infallible write to String");

assert!(matches!(result, Err(MissingNamedPlaceholderError { .. })));
assert_eq!(result.unwrap_err().name, "your_name");
assert_eq!(buffer, "Your name is {your_name}");

Trait Implementations§

source§

impl Clone for MultiNamedPlaceholder

source§

fn clone(&self) -> MultiNamedPlaceholder

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 MultiNamedPlaceholder

source§

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

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

impl PartialEq for MultiNamedPlaceholder

source§

fn eq(&self, other: &MultiNamedPlaceholder) -> 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 PatternBackend for MultiNamedPlaceholder

source§

type PlaceholderKey<'a> = MultiNamedPlaceholderKey<'a>

The type to be used as the placeholder key in code.
source§

type PlaceholderKeyCow<'a> = MultiNamedPlaceholderKeyCow<'a>

Cowable version of the type to be used as the placeholder key in code.
source§

type Error<'a> = MissingNamedPlaceholderError<'a>

The type of error that the TryWriteable for this backend can return.
source§

impl Copy for MultiNamedPlaceholder

source§

impl Eq for MultiNamedPlaceholder

source§

impl StructuralPartialEq for MultiNamedPlaceholder

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 T)

🔬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, 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,

source§

impl<T> MaybeSendSync for T
where T: Send + Sync,