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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

New formatting API #1196

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
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
18 changes: 18 additions & 0 deletions bench/benches/chrono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,22 @@ fn bench_parse_strftime_localized(c: &mut Criterion) {
});
}

fn bench_format_to_string(c: &mut Criterion) {
let dt = Local::now();
c.bench_function("bench_format_to_string", |b| {
b.iter(|| black_box(dt).format_to_string("%Y-%m-%dT%H:%M:%S%.f%:z"))
});
}

fn bench_format_with(c: &mut Criterion) {
let dt = Local::now();
let fmt_items: Vec<_> = StrftimeItems::new("%Y-%m-%dT%H:%M:%S%.f%:z").collect();
let formatter = DateTime::formatter(&fmt_items).unwrap();
c.bench_function("bench_format_with", |b| {
b.iter(|| format!("{}", black_box(dt).format_with(&formatter)))
});
}

fn bench_format(c: &mut Criterion) {
let dt = Local::now();
c.bench_function("bench_format", |b| {
Expand Down Expand Up @@ -235,6 +251,8 @@ criterion_group!(
bench_get_local_time,
bench_parse_strftime,
bench_format,
bench_format_to_string,
bench_format_with,
bench_format_with_items,
bench_format_manual,
bench_naivedate_add_signed,
Expand Down
18 changes: 7 additions & 11 deletions src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! ISO 8601 calendar date with time zone.
#![allow(deprecated)]

#[cfg(feature = "alloc")]
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::ops::{Add, AddAssign, Sub, SubAssign};
Expand All @@ -13,9 +12,8 @@ use core::{fmt, hash};
#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize, Serialize};

#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[cfg(feature = "unstable-locales")]
use crate::format::Locale;
#[cfg(feature = "alloc")]
use crate::format::{DelayedFormat, Item, StrftimeItems};
use crate::naive::{IsoWeek, NaiveDate, NaiveTime};
use crate::offset::{TimeZone, Utc};
Expand Down Expand Up @@ -331,10 +329,9 @@ where
Tz::Offset: fmt::Display,
{
/// Formats the date with the specified formatting items.
#[cfg(feature = "alloc")]
#[inline]
#[must_use]
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I, Tz::Offset>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
Expand All @@ -345,22 +342,21 @@ where
/// Formats the date with the specified format string.
/// See the [`crate::format::strftime`] module
/// on the supported escape sequences.
#[cfg(feature = "alloc")]
#[inline]
#[must_use]
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>, Tz::Offset> {
self.format_with_items(StrftimeItems::new(fmt))
}

/// Formats the date with the specified formatting items and locale.
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[cfg(feature = "unstable-locales")]
#[inline]
#[must_use]
pub fn format_localized_with_items<'a, I, B>(
&self,
items: I,
locale: Locale,
) -> DelayedFormat<I>
) -> DelayedFormat<I, Tz::Offset>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
Expand All @@ -377,14 +373,14 @@ where
/// Formats the date with the specified format string and locale.
/// See the [`crate::format::strftime`] module
/// on the supported escape sequences.
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[cfg(feature = "unstable-locales")]
#[inline]
#[must_use]
pub fn format_localized<'a>(
&self,
fmt: &'a str,
locale: Locale,
) -> DelayedFormat<StrftimeItems<'a>> {
) -> DelayedFormat<StrftimeItems<'a>, Tz::Offset> {
self.format_localized_with_items(StrftimeItems::new_with_locale(fmt, locale), locale)
}
}
Expand Down
153 changes: 109 additions & 44 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ use core::{fmt, hash, str};
#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[cfg(feature = "unstable-locales")]
use crate::format::Locale;
#[cfg(feature = "alloc")]
use crate::format::BAD_FORMAT;
use crate::format::{
parse, parse_and_remainder, parse_rfc3339, Fixed, Item, ParseError, ParseResult, Parsed,
StrftimeItems, TOO_LONG,
parse, parse_and_remainder, parse_rfc3339, DelayedFormat, Fixed, FormattingSpec, Item,
ParseError, ParseResult, Parsed, StrftimeItems, TOO_LONG,
};
#[cfg(feature = "alloc")]
use crate::format::{write_rfc2822, write_rfc3339, DelayedFormat, SecondsFormat};
use crate::format::{write_rfc2822, write_rfc3339, SecondsFormat};
use crate::naive::{Days, IsoWeek, NaiveDate, NaiveDateTime, NaiveTime};
#[cfg(feature = "clock")]
use crate::offset::Local;
Expand Down Expand Up @@ -1097,11 +1099,95 @@ impl<Tz: TimeZone> DateTime<Tz>
where
Tz::Offset: fmt::Display,
{
/// Formats the combined date and time with the specified formatting items.
/// Format using a [`FormattingSpec`] created with [`DateTime::formatter`].
pub fn format_with<'a, I, J, B, Tz2>(
&self,
formatter: &FormattingSpec<DateTime<Tz2>, I>,
) -> DelayedFormat<J, Tz::Offset>
where
I: IntoIterator<Item = B, IntoIter = J> + Clone,
J: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
Tz2: TimeZone,
{
let naive = self.naive_local();
formatter.formatter(Some(naive.date()), Some(naive.time()), Some(self.offset().clone()))
}

/// Format the date and time with the specified format string to a `String`.
///
/// See the [`format::strftime` module](crate::format::strftime) for the supported formatting
/// specifiers.
///
/// # Errors
///
/// Returns an error if the format string is invalid.
///
/// # Example
///
/// ```
/// use chrono::{TimeZone, Utc};
///
/// let dt = Utc.with_ymd_and_hms(2015, 9, 5, 23, 56, 4).unwrap();
/// assert_eq!(
/// dt.format_to_string("%Y-%m-%d %H:%M:%S %Z"),
/// Ok("2015-09-05 23:56:04 UTC".to_owned())
/// );
/// assert_eq!(
/// dt.format_to_string("%Y-%m-%d %H:%M:%S %:z"),
/// Ok("2015-09-05 23:56:04 +00:00".to_owned())
/// );
/// assert_eq!(
/// dt.format_to_string("around %l %p on %b %-d"),
/// Ok("around 11 PM on Sep 5".to_owned())
/// );
/// ```
#[cfg(feature = "alloc")]
pub fn format_to_string(&self, fmt_str: &str) -> Result<String, ParseError> {
let naive = self.naive_local();
let formatter = DelayedFormat::new_with_offset(
Some(naive.date()),
Some(naive.time()),
self.offset(),
StrftimeItems::new(fmt_str),
);
let mut result = String::new();
write!(&mut result, "{}", &formatter).map_err(|_| BAD_FORMAT)?;
Ok(result)
}

/// Formats the combined date and time with the specified format string and
/// locale to a `String`.
///
/// See the [`format::strftime` module](crate::format::strftime) for the supported formatting
/// specifiers.
///
/// # Errors
///
/// Returns an error if the format string is invalid.
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
pub fn format_to_string_localized(
&self,
fmt_str: &str,
locale: Locale,
) -> Result<String, ParseError> {
let naive = self.naive_local();
let formatter = DelayedFormat::new_with_offset_and_locale(
Some(naive.date()),
Some(naive.time()),
self.offset(),
StrftimeItems::new_with_locale(fmt_str, locale),
locale,
);
let mut result = String::new();
write!(&mut result, "{}", &formatter).map_err(|_| BAD_FORMAT)?;
Ok(result)
}

/// Formats the combined date and time with the specified formatting items.
#[inline]
#[must_use]
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I, Tz::Offset>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
Expand All @@ -1122,50 +1208,29 @@ where
/// let formatted = format!("{}", date_time.format("%d/%m/%Y %H:%M"));
/// assert_eq!(formatted, "02/04/2017 12:50");
/// ```
#[cfg(feature = "alloc")]
#[inline]
#[must_use]
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>, Tz::Offset> {
self.format_with_items(StrftimeItems::new(fmt))
}
}

/// Formats the combined date and time with the specified formatting items and locale.
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[inline]
#[must_use]
pub fn format_localized_with_items<'a, I, B>(
&self,
items: I,
locale: Locale,
) -> DelayedFormat<I>
where
I: Iterator<Item = B> + Clone,
B: Borrow<Item<'a>>,
{
let local = self.overflowing_naive_local();
DelayedFormat::new_with_offset_and_locale(
Some(local.date()),
Some(local.time()),
&self.offset,
items,
locale,
)
}

/// Formats the combined date and time per the specified format string and
/// locale.
///
/// See the [`crate::format::strftime`] module on the supported escape
/// sequences.
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
#[inline]
#[must_use]
pub fn format_localized<'a>(
&self,
fmt: &'a str,
impl DateTime<Utc> {
/// Create a new [`FormattingSpec`] that can be used to format multiple `DateTime`'s.
pub const fn formatter<'a>(
items: &'a [Item<'a>],
) -> Result<FormattingSpec<Self, &'a [Item<'a>]>, ParseError> {
FormattingSpec::<Self, _>::from_slice(items)
}

/// Create a new [`FormattingSpec`] that can be used to format multiple `DateTime`'s,
/// localized for `locale`.
#[cfg(feature = "unstable-locales")]
pub const fn formatter_localized<'a>(
items: &'a [Item<'a>],
locale: Locale,
) -> DelayedFormat<StrftimeItems<'a>> {
self.format_localized_with_items(StrftimeItems::new_with_locale(fmt, locale), locale)
) -> Result<FormattingSpec<Self, &'a [Item<'a>]>, ParseError> {
FormattingSpec::<Self, _>::from_slice_localized(items, locale)
}
}

Expand Down
30 changes: 14 additions & 16 deletions src/datetime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use crate::naive::{NaiveDate, NaiveTime};
use crate::offset::{FixedOffset, TimeZone, Utc};
#[cfg(feature = "clock")]
use crate::offset::{Local, Offset};
#[cfg(feature = "unstable-locales")]
use crate::ParseError;
use crate::{Datelike, Days, MappedLocalTime, Months, NaiveDateTime, TimeDelta, Timelike, Weekday};

#[derive(Clone)]
Expand Down Expand Up @@ -139,7 +141,6 @@ fn test_datetime_from_timestamp_millis() {
for (timestamp_millis, _formatted) in valid_map.iter().copied() {
let datetime = DateTime::from_timestamp_millis(timestamp_millis).unwrap();
assert_eq!(timestamp_millis, datetime.timestamp_millis());
#[cfg(feature = "alloc")]
assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
}

Expand Down Expand Up @@ -174,7 +175,6 @@ fn test_datetime_from_timestamp_micros() {
for (timestamp_micros, _formatted) in valid_map.iter().copied() {
let datetime = DateTime::from_timestamp_micros(timestamp_micros).unwrap();
assert_eq!(timestamp_micros, datetime.timestamp_micros());
#[cfg(feature = "alloc")]
assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
}

Expand Down Expand Up @@ -214,7 +214,6 @@ fn test_datetime_from_timestamp_nanos() {
for (timestamp_nanos, _formatted) in valid_map.iter().copied() {
let datetime = DateTime::from_timestamp_nanos(timestamp_nanos);
assert_eq!(timestamp_nanos, datetime.timestamp_nanos_opt().unwrap());
#[cfg(feature = "alloc")]
assert_eq!(datetime.format("%F %T%.9f").to_string(), _formatted);
}

Expand Down Expand Up @@ -1313,7 +1312,7 @@ fn test_to_string_round_trip_with_local() {
fn test_datetime_format_with_local() {
// if we are not around the year boundary, local and UTC date should have the same year
let dt = Local::now().with_month(5).unwrap();
assert_eq!(dt.format("%Y").to_string(), dt.with_timezone(&Utc).format("%Y").to_string());
assert_eq!(dt.format_to_string("%Y"), dt.with_timezone(&Utc).format_to_string("%Y"));
}

#[test]
Expand Down Expand Up @@ -1539,7 +1538,6 @@ fn test_min_max_getters() {
// assert_eq!(beyond_min.to_rfc2822(), "");
#[cfg(feature = "alloc")]
assert_eq!(beyond_min.to_rfc3339(), "-262144-12-31T22:00:00-02:00");
#[cfg(feature = "alloc")]
assert_eq!(
beyond_min.format("%Y-%m-%dT%H:%M:%S%:z").to_string(),
"-262144-12-31T22:00:00-02:00"
Expand All @@ -1564,7 +1562,6 @@ fn test_min_max_getters() {
// assert_eq!(beyond_max.to_rfc2822(), "");
#[cfg(feature = "alloc")]
assert_eq!(beyond_max.to_rfc3339(), "+262143-01-01T01:59:59.999999999+02:00");
#[cfg(feature = "alloc")]
assert_eq!(
beyond_max.format("%Y-%m-%dT%H:%M:%S%.9f%:z").to_string(),
"+262143-01-01T01:59:59.999999999+02:00"
Expand Down Expand Up @@ -1817,21 +1814,22 @@ fn test_test_deprecated_from_offset() {
}

#[test]
#[cfg(all(feature = "unstable-locales", feature = "alloc"))]
fn locale_decimal_point() {
#[cfg(feature = "unstable-locales")]
fn locale_decimal_point() -> Result<(), ParseError> {
use crate::Locale::{ar_SY, nl_NL};
let dt =
Utc.with_ymd_and_hms(2018, 9, 5, 18, 58, 0).unwrap().with_nanosecond(123456780).unwrap();

assert_eq!(dt.format_localized("%T%.f", nl_NL).to_string(), "18:58:00,123456780");
assert_eq!(dt.format_localized("%T%.3f", nl_NL).to_string(), "18:58:00,123");
assert_eq!(dt.format_localized("%T%.6f", nl_NL).to_string(), "18:58:00,123456");
assert_eq!(dt.format_localized("%T%.9f", nl_NL).to_string(), "18:58:00,123456780");
assert_eq!(dt.format_to_string_localized("%T%.f", nl_NL)?, "18:58:00,123456780");
assert_eq!(dt.format_to_string_localized("%T%.3f", nl_NL)?, "18:58:00,123");
assert_eq!(dt.format_to_string_localized("%T%.6f", nl_NL)?, "18:58:00,123456");
assert_eq!(dt.format_to_string_localized("%T%.9f", nl_NL)?, "18:58:00,123456780");

assert_eq!(dt.format_localized("%T%.f", ar_SY).to_string(), "18:58:00.123456780");
assert_eq!(dt.format_localized("%T%.3f", ar_SY).to_string(), "18:58:00.123");
assert_eq!(dt.format_localized("%T%.6f", ar_SY).to_string(), "18:58:00.123456");
assert_eq!(dt.format_localized("%T%.9f", ar_SY).to_string(), "18:58:00.123456780");
assert_eq!(dt.format_to_string_localized("%T%.f", ar_SY)?, "18:58:00.123456780");
assert_eq!(dt.format_to_string_localized("%T%.3f", ar_SY)?, "18:58:00.123");
assert_eq!(dt.format_to_string_localized("%T%.6f", ar_SY)?, "18:58:00.123456");
assert_eq!(dt.format_to_string_localized("%T%.9f", ar_SY)?, "18:58:00.123456780");
Ok(())
}

/// This is an extended test for <https://github.com/chronotope/chrono/issues/1289>.
Expand Down