Struct icu_pattern::Interpolator[][src]

pub struct Interpolator<'i, 'p, R, E> where
    R: ReplacementProvider<'i, E>, 
{ /* fields omitted */ }
Expand description

Placeholder pattern interpolator.

The interpolator takes a pattern parser iterator and a replacement provider and generates a new iterator over elements.

The replacement may be any type, and the only bind is on the ReplacementProvider to be able to return an iterator over elements to be interplotted into the pattern in place of the placeholders based on the placeholder keys.

Examples

use icu_pattern::{Parser, Pattern, ParserOptions, Interpolator, InterpolatedKind};
use std::{
    convert::TryInto,
};

#[derive(Debug, PartialEq)]
enum Element {
    Value(usize),
}

let pattern: Pattern<_> = Parser::new("{0} days ago", ParserOptions {
    allow_raw_letters: true
}).try_into().unwrap();

let replacements = vec![
    Element::Value(5),
];

let mut interpolator = Interpolator::new(&pattern, &replacements);

let mut result = vec![];

while let Some(element) = interpolator.try_next().expect("Failed to advance iterator") {
    result.push(element);
}

assert_eq!(result, &[
    InterpolatedKind::Element(&Element::Value(5)),
    InterpolatedKind::Literal(&" days ago".into()),
]);

Type parameters

Lifetimes

  • i: The life time of an input pattern slice.
  • p: The life time of an input PatternToken, which is the life time of the string slice.

Element & Replacement Provider

In order to allow for wide range of inputs to be interpolated using the placeholder pattern, the Element and ReplacementProvider types are generic. This allows the consumer of the API to decide what elements the pattern should return and how will they be identified based on any type of key that can be parsed out of a string slice.

This design allows for the interpolator to remain agnostic and flexible and handles wide range of ownership and life time models.

To simplify the common use cases, the ReplacementProvider comes with implementations for Vec (where the placehoder key is usize) and HashMap (where the placeholder key is String) but the consumer is free to implement their own providers for any type they wish.

Design Decisions

The interpolator is written in an intentionally generic way to enable use against wide range of potential placeholder pattern models and use cases.

Fallible Iterator

Rust providers a strong support for iterators and iterator combinators, which fits very well into the design of this parser/interpolator model.

Unfortunately, Rust iterators at the moment are infallible, while parsers are inhereantely fallible. As such, the decision has been made to design the API in line with what we hope will become a trait signature of a fallible iterator in the future, rather than implementing a reversed infallible iterator (where the Item would be Option<Result<Item>>).

Since the interpolator chains on top of the Parser it inherits the same fallible iterator API and behavior.

Implementations

Creates a new Interpolator.

Examples
use icu_pattern::{Parser, Pattern, ParserOptions, Interpolator};
use std::convert::TryInto;

enum Element {
    Literal(String),
    Token,
}

let pattern: Pattern<usize> = Parser::new("{0}, {1}", ParserOptions {
    allow_raw_letters: false
}).try_into().unwrap();
let replacements = vec![
    vec![
        Element::Token
    ]
];
let mut interpolator = Interpolator::<Vec<Vec<_>>, Element>::new(&pattern, &replacements);

An iterator method that advances the iterator and returns the result of an attempt to interpolate parser and replacement provider tokens.

Examples
use icu_pattern::{Parser, ParserOptions, Pattern, Interpolator, InterpolatedKind};
use std::{
    convert::TryInto,
};

#[derive(Debug, PartialEq)]
enum Element {
    TokenOne,
    TokenTwo,
}

let mut pattern: Pattern<_> = Parser::new("{0}, {1}", ParserOptions {
    allow_raw_letters: false
}).try_into().unwrap();

let replacements = vec![
    vec![
        Element::TokenOne
    ],
    vec![
        Element::TokenTwo
    ]
];
let mut interpolator = Interpolator::new(&pattern, &replacements);


// A call to try_next() returns the next value…
assert_eq!(Ok(Some(InterpolatedKind::Element(&Element::TokenOne))), interpolator.try_next());
assert_eq!(Ok(Some(InterpolatedKind::Literal(&", ".into()))), interpolator.try_next());
assert_eq!(Ok(Some(InterpolatedKind::Element(&Element::TokenTwo))), interpolator.try_next());

// … and then None once it's over.
assert_eq!(Ok(None), interpolator.try_next());

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.