Skip to content

Commit

Permalink
Add format_description::parse_owned
Browse files Browse the repository at this point in the history
  • Loading branch information
jhpratt committed Nov 3, 2022
1 parent 2ba92f6 commit 4887aa7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
2 changes: 1 addition & 1 deletion time/src/format_description/mod.rs
Expand Up @@ -19,7 +19,7 @@ pub use owned_format_item::OwnedFormatItem;

pub use self::component::Component;
#[cfg(feature = "alloc")]
pub use self::parse::parse;
pub use self::parse::{parse, parse_owned};

/// Well-known formats, typically standards.
pub mod well_known {
Expand Down
9 changes: 9 additions & 0 deletions time/src/format_description/parse/format_item.rs
Expand Up @@ -50,6 +50,15 @@ impl<'a> From<Item<'a>> for crate::format_description::FormatItem<'a> {
}
}

impl From<Item<'_>> for crate::format_description::OwnedFormatItem {
fn from(item: Item<'_>) -> Self {
match item {
Item::Literal(literal) => Self::Literal(literal.to_vec().into_boxed_slice()),
Item::Component(component) => Self::Component(component.into()),
}
}
}

/// Declare the `Component` struct.
macro_rules! component_definition {
($vis:vis enum $name:ident {
Expand Down
26 changes: 24 additions & 2 deletions time/src/format_description/parse/mod.rs
Expand Up @@ -18,9 +18,31 @@ pub fn parse(
let lexed = lexer::lex(s.as_bytes());
let ast = ast::parse(lexed);
let format_items = format_item::parse(ast);
let items = format_items.collect::<Result<Vec<_>, _>>()?;
Ok(format_items
.map(|res| res.map(Into::into))
.collect::<Result<Vec<_>, _>>()?)
}

Ok(items.into_iter().map(Into::into).collect())
/// Parse a sequence of items from the format description.
///
/// The syntax for the format description can be found in [the
/// book](https://time-rs.github.io/book/api/format-description.html).
///
/// Unlike [`parse`], this function returns [`OwnedFormatItem`], which owns its contents. This means
/// that there is no lifetime that needs to be handled.
///
/// [`OwnedFormatItem`]: crate::format_description::OwnedFormatItem
pub fn parse_owned(
s: &str,
) -> Result<crate::format_description::OwnedFormatItem, crate::error::InvalidFormatDescription> {
let lexed = lexer::lex(s.as_bytes());
let ast = ast::parse(lexed);
let format_items = format_item::parse(ast);
let items = format_items
.map(|res| res.map(Into::into))
.collect::<Result<Vec<_>, _>>()?
.into_boxed_slice();
Ok(crate::format_description::OwnedFormatItem::Compound(items))
}

/// A location within a string.
Expand Down

0 comments on commit 4887aa7

Please sign in to comment.