Skip to main content

MultiNamedPlaceholder

Enum 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 duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Copy for MultiNamedPlaceholder

Source§

impl Debug for MultiNamedPlaceholder

Source§

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

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

impl Eq for MultiNamedPlaceholder

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 (const: unstable) · 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§

type Store = str

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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.