Struct icu_pattern::Parser[][src]

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

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

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
});

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

The type returned in the event of a conversion error.

Performs the conversion.

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.