Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add StrftimeItems::{parse, parse_to_owned} and more documentation #1184

Merged
merged 4 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,22 @@ const fn internal_fixed(val: InternalInternal) -> Item<'static> {
Item::Fixed(Fixed::Internal(InternalFixed { val }))
}

impl<'a> Item<'a> {
/// Convert items that contain a reference to the format string into an owned variant.
#[cfg(any(feature = "alloc", feature = "std"))]
pub fn to_owned(self) -> Item<'static> {
match self {
Item::Literal(s) => Item::OwnedLiteral(Box::from(s)),
Item::Space(s) => Item::OwnedSpace(Box::from(s)),
Item::Numeric(n, p) => Item::Numeric(n, p),
Item::Fixed(f) => Item::Fixed(f),
Item::OwnedLiteral(l) => Item::OwnedLiteral(l),
Item::OwnedSpace(s) => Item::OwnedSpace(s),
Item::Error => Item::Error,
}
}
}

/// An error from the `parse` function.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
pub struct ParseError(ParseErrorKind);
Expand Down
199 changes: 197 additions & 2 deletions src/format/strftime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,35 @@ Notes:
China Daylight Time.
*/

#[cfg(feature = "alloc")]
extern crate alloc;

use super::{fixed, internal_fixed, num, num0, nums};
#[cfg(feature = "unstable-locales")]
use super::{locales, Locale};
use super::{Fixed, InternalInternal, Item, Numeric, Pad};
#[cfg(any(feature = "alloc", feature = "std"))]
use super::{ParseError, BAD_FORMAT};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

/// Parsing iterator for `strftime`-like format strings.
///
/// See the [`format::strftime` module](crate::format::strftime) for supported formatting
/// specifiers.
///
/// `StrftimeItems` is used in combination with more low-level methods such as [`format::parse()`]
/// or [`format_with_items`].
///
/// If formatting or parsing date and time values is not performance-critical, the methods
/// [`parse_from_str`] and [`format`] on types such as [`DateTime`](crate::DateTime) are easier to
/// use.
///
/// [`format`]: crate::DateTime::format
/// [`format_with_items`]: crate::DateTime::format
/// [`parse_from_str`]: crate::DateTime::parse_from_str
/// [`DateTime`]: crate::DateTime
/// [`format::parse()`]: crate::format::parse()
#[derive(Clone, Debug)]
pub struct StrftimeItems<'a> {
/// Remaining portion of the string.
Expand All @@ -176,7 +199,30 @@ pub struct StrftimeItems<'a> {
}

impl<'a> StrftimeItems<'a> {
/// Creates a new parsing iterator from the `strftime`-like format string.
/// Creates a new parsing iterator from a `strftime`-like format string.
///
/// # Errors
///
/// While iterating [`Item::Error`] will be returned if the format string contains an invalid
/// or unrecognized formatting specifier.
///
/// # Example
///
#[cfg_attr(not(any(feature = "alloc", feature = "std")), doc = "```ignore")]
#[cfg_attr(any(feature = "alloc", feature = "std"), doc = "```rust")]
/// use chrono::format::*;
///
/// let strftime_parser = StrftimeItems::new("%F"); // %F: year-month-day (ISO 8601)
///
/// const ISO8601_YMD_ITEMS: &[Item<'static>] = &[
/// Item::Numeric(Numeric::Year, Pad::Zero),
/// Item::Literal("-"),
/// Item::Numeric(Numeric::Month, Pad::Zero),
/// Item::Literal("-"),
/// Item::Numeric(Numeric::Day, Pad::Zero),
/// ];
/// assert!(strftime_parser.eq(ISO8601_YMD_ITEMS.iter().cloned()));
/// ```
#[must_use]
pub const fn new(s: &'a str) -> StrftimeItems<'a> {
#[cfg(not(feature = "unstable-locales"))]
Expand All @@ -189,12 +235,152 @@ impl<'a> StrftimeItems<'a> {
}
}

/// Creates a new parsing iterator from the `strftime`-like format string.
/// Creates a new parsing iterator from a `strftime`-like format string, with some formatting
/// specifiers adjusted to match [`Locale`].
///
/// Note: `StrftimeItems::new_with_locale` only localizes the *format*. You usually want to
/// combine it with other locale-aware methods such as
/// [`DateTime::format_localized_with_items`] to get things like localized month or day names.
///
/// The `%x` formatting specifier will use the local date format, `%X` the local time format,
/// and `%c` the local format for date and time.
/// `%r` will use the local 12-hour clock format (e.g., 11:11:04 PM). Not all locales have such
/// a format, in which case we fall back to a 24-hour clock (`%X`).
///
/// See the [`format::strftime` module](crate::format::strftime) for all supported formatting
/// specifiers.
///
/// [`DateTime::format_localized_with_items`]: crate::DateTime::format_localized_with_items
///
/// # Errors
///
/// While iterating [`Item::Error`] will be returned if the format string contains an invalid
/// or unrecognized formatting specifier.
///
/// # Example
///
#[cfg_attr(not(any(feature = "alloc", feature = "std")), doc = "```ignore")]
#[cfg_attr(any(feature = "alloc", feature = "std"), doc = "```rust")]
/// use chrono::format::{Locale, StrftimeItems};
/// use chrono::{FixedOffset, TimeZone};
///
/// let dt = FixedOffset::east_opt(9 * 60 * 60)
/// .unwrap()
/// .with_ymd_and_hms(2023, 7, 11, 0, 34, 59)
/// .unwrap();
///
/// // Note: you usually want to combine `StrftimeItems::new_with_locale` with other
/// // locale-aware methods such as `DateTime::format_localized_with_items`.
/// // We use the regular `format_with_items` to show only how the formatting changes.
///
/// let fmtr = dt.format_with_items(StrftimeItems::new_with_locale("%x", Locale::en_US));
/// assert_eq!(fmtr.to_string(), "07/11/2023");
/// let fmtr = dt.format_with_items(StrftimeItems::new_with_locale("%x", Locale::ko_KR));
/// assert_eq!(fmtr.to_string(), "2023년 07월 11일");
/// let fmtr = dt.format_with_items(StrftimeItems::new_with_locale("%x", Locale::ja_JP));
/// assert_eq!(fmtr.to_string(), "2023年07月11日");
/// ```
#[cfg(feature = "unstable-locales")]
#[must_use]
pub const fn new_with_locale(s: &'a str, locale: Locale) -> StrftimeItems<'a> {
StrftimeItems { remainder: s, queue: &[], locale_str: "", locale: Some(locale) }
}

/// Parse format string into a `Vec` of formatting [`Item`]'s.
///
/// If you need to format or parse multiple values with the same format string, it is more
/// efficient to convert it to a `Vec` of formatting [`Item`]'s than to re-parse the format
/// string on every use.
///
/// The `format_with_items` methods on [`DateTime`], [`NaiveDateTime`], [`NaiveDate`] and
/// [`NaiveTime`] accept the result for formatting. [`format::parse()`] can make use of it for
/// parsing.
///
/// [`DateTime`]: crate::DateTime::format_with_items
/// [`NaiveDateTime`]: crate::NaiveDateTime::format_with_items
/// [`NaiveDate`]: crate::NaiveDate::format_with_items
/// [`NaiveTime`]: crate::NaiveTime::format_with_items
/// [`format::parse()`]: crate::format::parse()
///
/// # Errors
///
/// Returns an error if the format string contains an invalid or unrecognized formatting
/// specifier.
///
/// # Example
///
/// ```
/// use chrono::format::{parse, Parsed, StrftimeItems};
/// use chrono::NaiveDate;
///
/// let fmt_items = StrftimeItems::new("%e %b %Y %k.%M").parse()?;
/// let datetime = NaiveDate::from_ymd_opt(2023, 7, 11).unwrap().and_hms_opt(9, 0, 0).unwrap();
///
/// // Formatting
/// assert_eq!(
/// datetime.format_with_items(fmt_items.as_slice().iter()).to_string(),
/// "11 Jul 2023 9.00"
/// );
///
/// // Parsing
/// let mut parsed = Parsed::new();
/// parse(&mut parsed, "11 Jul 2023 9.00", fmt_items.as_slice().iter())?;
/// let parsed_dt = parsed.to_naive_datetime_with_offset(0)?;
/// assert_eq!(parsed_dt, datetime);
/// # Ok::<(), chrono::ParseError>(())
/// ```
#[cfg(any(feature = "alloc", feature = "std"))]
pub fn parse(self) -> Result<Vec<Item<'a>>, ParseError> {
djc marked this conversation as resolved.
Show resolved Hide resolved
self.into_iter()
.map(|item| match item == Item::Error {
false => Ok(item),
true => Err(BAD_FORMAT),
})
.collect()
}

/// Parse format string into a `Vec` of [`Item`]'s that contain no references to slices of the
/// format string.
///
/// A `Vec` created with [`StrftimeItems::parse`] contains references to the format string,
/// binding the lifetime of the `Vec` to that string. [`StrftimeItems::parse_to_owned`] will
/// convert the references to owned types.
///
/// # Errors
///
/// Returns an error if the format string contains an invalid or unrecognized formatting
/// specifier.
///
/// # Example
///
/// ```
/// use chrono::format::{Item, ParseError, StrftimeItems};
/// use chrono::NaiveDate;
///
/// fn format_items(date_fmt: &str, time_fmt: &str) -> Result<Vec<Item<'static>>, ParseError> {
/// // `fmt_string` is dropped at the end of this function.
/// let fmt_string = format!("{} {}", date_fmt, time_fmt);
/// StrftimeItems::new(&fmt_string).parse_to_owned()
/// }
///
/// let fmt_items = format_items("%e %b %Y", "%k.%M")?;
/// let datetime = NaiveDate::from_ymd_opt(2023, 7, 11).unwrap().and_hms_opt(9, 0, 0).unwrap();
///
/// assert_eq!(
/// datetime.format_with_items(fmt_items.as_slice().iter()).to_string(),
/// "11 Jul 2023 9.00"
/// );
/// # Ok::<(), ParseError>(())
/// ```
#[cfg(any(feature = "alloc", feature = "std"))]
pub fn parse_to_owned(self) -> Result<Vec<Item<'static>>, ParseError> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, too: why should this be added to the public API? What use case does it address that is currently underserved?

Copy link
Collaborator Author

@pitdicker pitdicker Sep 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Vec returned by StrftimeItems::parse borrows from the input string. While we have items that can take owned strings they were really not easy to use, or even discover.
Somewhat suggested in #852 (comment) (#1183).

self.into_iter()
.map(|item| match item == Item::Error {
false => Ok(item.to_owned()),
true => Err(BAD_FORMAT),
})
.collect()
}
}

const HAVE_ALTERNATES: &str = "z";
Expand Down Expand Up @@ -937,4 +1123,13 @@ mod tests {
assert_eq!(size_of::<StrftimeItems>(), 28);
assert_eq!(size_of::<Locale>(), 2);
}

#[test]
#[cfg(any(feature = "alloc", feature = "std"))]
fn test_strftime_parse() {
let fmt_str = StrftimeItems::new("%Y-%m-%dT%H:%M:%S%z");
let fmt_items = fmt_str.parse().unwrap();
let dt = Utc.with_ymd_and_hms(2014, 5, 7, 12, 34, 56).unwrap();
assert_eq!(&dt.format_with_items(fmt_items.iter()).to_string(), "2014-05-07T12:34:56+0000");
}
}