Struct icu_pattern::Parser[][src]

pub struct Parser<'p, P> { /* fields omitted */ }

Placeholder pattern parser.

The parser allows for handling flexible range of generic patterns with placeholders. A placeholder may be anything that can be parsed from an &str and must be enclosed in { and } characters in the input pattern string.

At the moment the parser is written as a custom fallible iterator.

Examples

use icu_pattern::{Parser, ParserOptions, PatternToken};

let input = "{0}, {1}";

let mut parser = Parser::new(input, ParserOptions {
   allow_raw_letters: false
});

let mut result = vec![];

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

assert_eq!(result, &[
    PatternToken::Placeholder(0),
    PatternToken::Literal { content: ", ".into(), quoted: false },
    PatternToken::Placeholder(1),
]);

Named placeholders

The parser is also capable of parsing different placeholder types such as strings.

Examples

use icu_pattern::{Parser, ParserOptions, PatternToken};

let input = "{start}, {end}";

let mut parser = Parser::new(input, ParserOptions {
    allow_raw_letters: false,
});

let mut result = vec![];

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

assert_eq!(result, &[
    PatternToken::Placeholder("start".to_string()),
    PatternToken::Literal { content: ", ".into(), quoted: false },
    PatternToken::Placeholder("end".to_string()),
]);

Type parameters

Lifetimes

  • p: The life time of an input string slice to be parsed.

Design Decisions

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

Serveral design decisions have been made that the reader should be aware of when using the API.

Zero copy

The parser is intended for runtime use and is optimized for performance and low memory overhad.

Zero copy parsing is a model which allows the parser to produce tokens that are de-facto slices of the input without ever having to modify the input or copy from it.

In case of ICU patterns that decision brings a trade-off around handling of quoted literals. A parser that copies bytes from the input when generating the output can take a pattern literal that contains a quoted portion and concatenace the parts, effectively generating a single literal out of a series of syntactical literal quoted and unquoted nodes. A zero copy parser sacrifices that convenience for marginal performance gains.

The rationale for the decision is that many placeholder patterns do not contain ASCII letters and therefore can benefit from this design decision. Secondly, even in scenarios where ASCII letters, or other quoted literals, are used, the zero-copy design still maintains high performance, only increasing the number of tokens returned by the parser, but without increase to allocations.

Examples

use icu_pattern::{Parser, ParserOptions, PatternToken};

let input = "{0} 'and' {1}";

let mut parser = Parser::new(input, ParserOptions {
    allow_raw_letters: false
});

let mut result = vec![];

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

assert_eq!(result, &[
    PatternToken::Placeholder(0),
    PatternToken::Literal { content: " ".into(), quoted: false },
    PatternToken::Literal { content: "and".into(), quoted: true },
    PatternToken::Literal { content: " ".into(), quoted: false },
    PatternToken::Placeholder(1),
]);

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

That decision impacts the ergonomics of operating on the parser, on one hand making the fallible iteration more ergonomic, at a trade-off of losing access to the wide range of Rust iterator traits.

Generic Placeholder

To handle generic placeholder design, the only constrain necessary in the parser is that a placeholder must be parsed from a string slice. At the moment of writing, Rust is preparing to deprecate FromStr in favor of TryFrom<&str>. Among many benfits of such transition would be the auto-trait behavior of From and a TryFrom<&str> for &str allowing for placeholders to be &str themselves.

Unfortunately, at the moment TryFrom<&str> for usize is not implemented, which would impact the core use case of placeholder patterns.

In result, the decision has been made to use FromStr for the time being, until TryFrom<&str> gets implemented on all types that support FromStr.

Implementations

impl<'p, P> Parser<'p, P>[src]

pub fn new(input: &'p str, options: ParserOptions) -> Self[src]

Creates a new Parser.

The allow_raw_letters controls whether the parser will support ASCII letters without quotes.

Examples

use icu_pattern::{Parser, ParserOptions};
let mut parser = Parser::<usize>::new("{0}, {1}", ParserOptions {
    allow_raw_letters: false
});

pub fn try_next(
    &mut self
) -> Result<Option<PatternToken<'p, P>>, ParserError<<P as FromStr>::Err>> where
    P: FromStr,
    P::Err: Debug
[src]

An iterator method that advances the iterator and returns the result of an attempt to parse the next token.

Examples

use icu_pattern::{Parser, ParserOptions, PatternToken};

let mut parser = Parser::<usize>::new("{0}, {1}", ParserOptions {
    allow_raw_letters: false
});

// A call to try_next() returns the next value…
assert_eq!(Ok(Some(PatternToken::Placeholder(0))), parser.try_next());
assert_eq!(Ok(Some(PatternToken::Literal { content: ", ".into(), quoted: false})), parser.try_next());
assert_eq!(Ok(Some(PatternToken::Placeholder(1))), parser.try_next());

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

Trait Implementations

impl<'p, P> TryFrom<Parser<'p, P>> for Pattern<'p, P> where
    P: FromStr,
    <P as FromStr>::Err: Debug
[src]

type Error = ParserError<<P as FromStr>::Err>

The type returned in the event of a conversion error.

Auto Trait Implementations

impl<'p, P> RefUnwindSafe for Parser<'p, P> where
    P: RefUnwindSafe

impl<'p, P> Send for Parser<'p, P> where
    P: Send

impl<'p, P> Sync for Parser<'p, P> where
    P: Sync

impl<'p, P> Unpin for Parser<'p, P> where
    P: Unpin

impl<'p, P> UnwindSafe for Parser<'p, P> where
    P: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.