Struct Parser

Source
pub struct Parser<'a> {
    pub config: Config<'a>,
}
Expand description

The core duration parser to parse strings into a crate::time::Duration

To be able to use the Parser::parse method an implementation of the crate::time::TimeUnitsLike trait is needed for the time units (even if there are no time units) and optionally for time keywords (like yesterday and tomorrow etc.). Optionally, an implementation of the NumbersLike trait can be provided, too. The custom and standard features have such implementations and their parsers are more convenient to use than using this parser directly. However, for example, the custom feature’s fundu::CustomDurationParser cannot be fully built in const context and is a slightly slower than this parser. So, using this parser is more involved but if maximum performance and building a parser in const context is wanted then this parser is the better choice.

§Examples

use fundu_core::error::ParseError;
use fundu_core::parse::Parser;
use fundu_core::time::TimeUnit::*;
use fundu_core::time::{Duration, Multiplier, TimeUnit, TimeUnitsLike};

struct TimeUnits {}

impl TimeUnitsLike for TimeUnits {
    #[inline]
    fn is_empty(&self) -> bool {
        false
    }

    #[inline]
    fn get(&self, identifier: &str) -> Option<(TimeUnit, Multiplier)> {
        match identifier {
            "s" | "sec" | "secs" => Some((Second, Multiplier(1, 0))),
            "m" | "min" | "mins" => Some((Minute, Multiplier(1, 0))),
            _ => None,
        }
    }
}

let parser = Parser::new();
let time_units = TimeUnits {};

assert_eq!(
    parser.parse("1.0s", &time_units, None, None),
    Ok(Duration::positive(1, 0))
);
assert_eq!(
    parser.parse("1min", &time_units, None, None),
    Ok(Duration::positive(60, 0))
);
assert_eq!(
    parser.parse("1ms", &time_units, None, None),
    Err(ParseError::TimeUnit(
        1,
        "Invalid time unit: 'ms'".to_string()
    ))
);

Fields§

§config: Config<'a>

The crate::config::Config of this Parser

For convenience, there are also the const Parser::new and const Parser::with_config methods to create a new Parser.

Implementations§

Source§

impl<'a> Parser<'a>

Source

pub const fn new() -> Self

Convenience method to create a new parser with the default crate::config::Config

Source

pub const fn with_config(config: Config<'a>) -> Self

Convenience method to create a new parser with the the given crate::config::Config

Source

pub fn parse_multiple( &self, source: &str, time_units: &dyn TimeUnitsLike, keywords: Option<&dyn TimeUnitsLike>, numerals: Option<&dyn NumbersLike>, ) -> Result<Duration, ParseError>

Source

pub fn parse_single( &self, source: &str, time_units: &dyn TimeUnitsLike, keywords: Option<&dyn TimeUnitsLike>, numerals: Option<&dyn NumbersLike>, ) -> Result<Duration, ParseError>

Source

pub fn parse( &self, source: &str, time_units: &dyn TimeUnitsLike, keywords: Option<&dyn TimeUnitsLike>, numerals: Option<&dyn NumbersLike>, ) -> Result<Duration, ParseError>

Parse the source string into a saturating crate::time::Duration

This method needs a struct implementing the crate::time::TimeUnitsLike for time units and optionally for time keywords (like yesterday, tomorrow). But also NumbersLike implementations for words like one, next, last are supported. The standard and custom features of fundu offer such implementations and are more convenient to use than using this method directly. They both provide facades and an own parser which calls this method.

§Errors

Returns a crate::error::ParseError if the given source string is invalid

§Examples

An example with a quick and dirty implementation of crate::time::TimeUnitsLike

use fundu_core::error::ParseError;
use fundu_core::parse::Parser;
use fundu_core::time::TimeUnit::*;
use fundu_core::time::{Duration, Multiplier, TimeUnit, TimeUnitsLike};

struct TimeUnits {}

impl TimeUnitsLike for TimeUnits {
    #[inline]
    fn is_empty(&self) -> bool {
        false
    }

    #[inline]
    fn get(&self, identifier: &str) -> Option<(TimeUnit, Multiplier)> {
        match identifier {
            "s" | "sec" | "secs" => Some((Second, Multiplier(1, 0))),
            "m" | "min" | "mins" => Some((Minute, Multiplier(1, 0))),
            _ => None,
        }
    }
}

let parser = Parser::new();
let time_units = TimeUnits {};

assert_eq!(
    parser.parse("1.0s", &time_units, None, None),
    Ok(Duration::positive(1, 0))
);
assert_eq!(
    parser.parse("1min", &time_units, None, None),
    Ok(Duration::positive(60, 0))
);
assert_eq!(
    parser.parse("1ms", &time_units, None, None),
    Err(ParseError::TimeUnit(
        1,
        "Invalid time unit: 'ms'".to_string()
    ))
);

Trait Implementations§

Source§

impl<'a> Debug for Parser<'a>

Source§

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

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

impl<'a> Default for Parser<'a>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'a> PartialEq for Parser<'a>

Source§

fn eq(&self, other: &Parser<'a>) -> 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<'a> Eq for Parser<'a>

Source§

impl<'a> StructuralPartialEq for Parser<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Parser<'a>

§

impl<'a> RefUnwindSafe for Parser<'a>

§

impl<'a> Send for Parser<'a>

§

impl<'a> Sync for Parser<'a>

§

impl<'a> Unpin for Parser<'a>

§

impl<'a> UnwindSafe for Parser<'a>

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