diff --git a/tests/derives.rs b/tests/derives.rs index 9392add4e..0165c0377 100644 --- a/tests/derives.rs +++ b/tests/derives.rs @@ -4,7 +4,7 @@ use std::hash::Hash; use time::error::{self, ConversionRange, IndeterminateOffset, TryFromParsed}; use time::ext::NumericalDuration; -use time::format_description::{self, modifier, well_known, Component, FormatItem, OwnedFormatItem}; +use time::format_description::{self, modifier, well_known, Component, BorrowedFormatItem, OwnedFormatItem}; use time::macros::{date, offset, time}; use time::parsing::Parsed; use time::{Duration, Error, Month, Time, Weekday}; @@ -64,7 +64,7 @@ fn clone() { assert_cloned_eq!(well_known::iso8601::OffsetPrecision::Hour); assert_cloned_eq!(well_known::iso8601::FormattedComponents::None); assert_cloned_eq!(component_range_error()); - assert_cloned_eq!(FormatItem::Literal(b"")); + assert_cloned_eq!(BorrowedFormatItem::Literal(b"")); assert_cloned_eq!(time::util::local_offset::Soundness::Sound); assert_cloned_eq!(modifier::Day::default()); @@ -189,13 +189,13 @@ fn debug() { modifier::OffsetSecond::default(); modifier::Padding::default(); - FormatItem::Literal(b"abcdef"); - FormatItem::Compound(&[FormatItem::Component(Component::Day(modifier::Day::default()))]); - FormatItem::Optional(&FormatItem::Compound(&[])); - FormatItem::First(&[]); - OwnedFormatItem::from(FormatItem::Literal(b"abcdef")); - OwnedFormatItem::from(FormatItem::Compound(&[FormatItem::Component(Component::Day(modifier::Day::default()))])); - OwnedFormatItem::from(FormatItem::Optional(&FormatItem::Compound(&[]))); - OwnedFormatItem::from(FormatItem::First(&[])); + BorrowedFormatItem::Literal(b"abcdef"); + BorrowedFormatItem::Compound(&[BorrowedFormatItem::Component(Component::Day(modifier::Day::default()))]); + BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&[])); + BorrowedFormatItem::First(&[]); + OwnedFormatItem::from(BorrowedFormatItem::Literal(b"abcdef")); + OwnedFormatItem::from(BorrowedFormatItem::Compound(&[BorrowedFormatItem::Component(Component::Day(modifier::Day::default()))])); + OwnedFormatItem::from(BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&[]))); + OwnedFormatItem::from(BorrowedFormatItem::First(&[])); } } diff --git a/tests/format_description.rs b/tests/format_description.rs index 38ccffaa5..bcbeed32e 100644 --- a/tests/format_description.rs +++ b/tests/format_description.rs @@ -1,29 +1,29 @@ -use time::format_description::{modifier, Component, FormatItem, OwnedFormatItem}; +use time::format_description::{modifier, BorrowedFormatItem, Component, OwnedFormatItem}; #[test] fn borrowed_format_item_component_conversions() { let component = Component::Year(modifier::Year::default()); - let item = FormatItem::from(component); - assert!(matches!(item, FormatItem::Component(inner) if inner == component)); + let item = BorrowedFormatItem::from(component); + assert!(matches!(item, BorrowedFormatItem::Component(inner) if inner == component)); assert_eq!(Component::try_from(item), Ok(component)); - assert!(Component::try_from(FormatItem::Literal(b"")).is_err()); - assert!(<&[FormatItem<'_>]>::try_from(FormatItem::Literal(b"")).is_err()); + assert!(Component::try_from(BorrowedFormatItem::Literal(b"")).is_err()); + assert!(<&[BorrowedFormatItem<'_>]>::try_from(BorrowedFormatItem::Literal(b"")).is_err()); } #[test] fn borrowed_format_item_compound_conversions() { - let compound = [FormatItem::Literal(b"")].as_slice(); - let item = FormatItem::from(compound); - assert!(matches!(item, FormatItem::Compound(inner) if inner == compound)); - assert_eq!(<&[FormatItem<'_>]>::try_from(item), Ok(compound)); + let compound = [BorrowedFormatItem::Literal(b"")].as_slice(); + let item = BorrowedFormatItem::from(compound); + assert!(matches!(item, BorrowedFormatItem::Compound(inner) if inner == compound)); + assert_eq!(<&[BorrowedFormatItem<'_>]>::try_from(item), Ok(compound)); } #[test] fn borrowed_format_item_equality() { let component = Component::Year(modifier::Year::default()); - let compound = [FormatItem::Literal(b"")].as_slice(); - let component_item = FormatItem::from(component); - let compound_item = FormatItem::from(compound); + let compound = [BorrowedFormatItem::Literal(b"")].as_slice(); + let component_item = BorrowedFormatItem::from(component); + let compound_item = BorrowedFormatItem::from(compound); assert_eq!(component, component_item); assert_eq!(component_item, component); @@ -52,7 +52,7 @@ fn owned_format_item_compound_conversions() { #[test] fn owned_format_item_equality() { let component = Component::Year(modifier::Year::default()); - let compound = OwnedFormatItem::from([FormatItem::Literal(b"")].as_slice()); + let compound = OwnedFormatItem::from([BorrowedFormatItem::Literal(b"")].as_slice()); let component_item = OwnedFormatItem::from(component); assert_eq!(component, component_item); diff --git a/tests/formatting.rs b/tests/formatting.rs index 671a3f24a..e54a9f618 100644 --- a/tests/formatting.rs +++ b/tests/formatting.rs @@ -2,7 +2,7 @@ use std::io; use time::format_description::well_known::iso8601::{DateKind, OffsetPrecision, TimePrecision}; use time::format_description::well_known::{iso8601, Iso8601, Rfc2822, Rfc3339}; -use time::format_description::{self, FormatItem, OwnedFormatItem}; +use time::format_description::{self, BorrowedFormatItem, OwnedFormatItem}; use time::macros::{date, datetime, format_description as fd, offset, time}; use time::{OffsetDateTime, Time}; @@ -562,9 +562,9 @@ fn insufficient_type_information() { assert_insufficient_type_information(Time::MIDNIGHT.format(&Rfc2822)); assert_insufficient_type_information(date!(2021 - 001).format(&Rfc2822)); assert_insufficient_type_information(datetime!(2021 - 001 0:00).format(&Rfc2822)); - assert_insufficient_type_information( - Time::MIDNIGHT.format(&FormatItem::First(&[FormatItem::Compound(fd!("[year]"))])), - ); + assert_insufficient_type_information(Time::MIDNIGHT.format(&BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(fd!("[year]")), + ]))); assert_insufficient_type_information(Time::MIDNIGHT.format(&Iso8601::DEFAULT)); assert_insufficient_type_information(date!(2021 - 001).format(&Iso8601::DEFAULT)); assert_insufficient_type_information(datetime!(2021-001 0:00).format(&Iso8601::DEFAULT)); @@ -591,14 +591,16 @@ fn failed_write() -> time::Result<()> { assert_err!(Time::MIDNIGHT, fd!("foo")); assert_err!(Time::MIDNIGHT, OwnedFormatItem::from(fd!("foo"))); - assert_err!(Time::MIDNIGHT, FormatItem::Compound(fd!("foo"))); + assert_err!(Time::MIDNIGHT, BorrowedFormatItem::Compound(fd!("foo"))); assert_err!( Time::MIDNIGHT, - FormatItem::Optional(&FormatItem::Compound(fd!("foo"))) + BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(fd!("foo"))) ); assert_err!( Time::MIDNIGHT, - OwnedFormatItem::from(FormatItem::Optional(&FormatItem::Compound(fd!("foo")))) + OwnedFormatItem::from(BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + fd!("foo") + ))) ); assert_err!(OffsetDateTime::UNIX_EPOCH, Rfc3339); assert_err!(datetime!(2021-001 0:00:00.1 UTC), Rfc3339); @@ -720,9 +722,11 @@ fn failed_write() -> time::Result<()> { #[test] fn first() -> time::Result<()> { - assert_eq!(Time::MIDNIGHT.format(&FormatItem::First(&[]))?, ""); + assert_eq!(Time::MIDNIGHT.format(&BorrowedFormatItem::First(&[]))?, ""); assert_eq!( - Time::MIDNIGHT.format(&FormatItem::First(&[FormatItem::Compound(fd!("[hour]"))]))?, + Time::MIDNIGHT.format(&BorrowedFormatItem::First(&[BorrowedFormatItem::Compound( + fd!("[hour]") + )]))?, "00" ); assert_eq!( @@ -730,8 +734,8 @@ fn first() -> time::Result<()> { "" ); assert_eq!( - Time::MIDNIGHT.format(&OwnedFormatItem::from(FormatItem::First(&[ - FormatItem::Compound(fd!("[hour]")) + Time::MIDNIGHT.format(&OwnedFormatItem::from(BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(fd!("[hour]")) ])))?, "00" ); diff --git a/tests/macros.rs b/tests/macros.rs index cc0103e6f..855fad85c 100644 --- a/tests/macros.rs +++ b/tests/macros.rs @@ -2,7 +2,7 @@ use core::num::NonZeroU16; use rstest::rstest; use time::format_description::modifier::*; -use time::format_description::{Component, FormatItem}; +use time::format_description::{BorrowedFormatItem, Component}; use time::macros::{date, format_description, time}; use time::{Date, Time}; @@ -17,13 +17,13 @@ fn nontrivial_string() { assert_eq!( format_description!("foo\ bar\n\r\t\\\"\'\0\x20\x4E\x4e\u{20}\u{4E}\u{4_e}"), - &[FormatItem::Literal(b"foobar\n\r\t\\\"'\0 NN NN")] + &[BorrowedFormatItem::Literal(b"foobar\n\r\t\\\"'\0 NN NN")] ); #[rustfmt::skip] assert_eq!( format_description!(b"foo\ bar\n\r\t\\\"\'\0\x20\x4E\x4e"), - &[FormatItem::Literal(b"foobar\n\r\t\\\"'\0 NN")] + &[BorrowedFormatItem::Literal(b"foobar\n\r\t\\\"'\0 NN")] ); } @@ -31,15 +31,15 @@ fn nontrivial_string() { fn format_description_version() { assert_eq!( format_description!(version = 1, "[["), - &[FormatItem::Literal(b"[")] + &[BorrowedFormatItem::Literal(b"[")] ); assert_eq!( format_description!(version = 1, r"\\"), - &[FormatItem::Literal(br"\\")] + &[BorrowedFormatItem::Literal(br"\\")] ); assert_eq!( format_description!(version = 2, r"\\"), - &[FormatItem::Literal(br"\")] + &[BorrowedFormatItem::Literal(br"\")] ); } @@ -47,21 +47,25 @@ fn format_description_version() { fn nested_v1() { assert_eq!( format_description!(version = 1, "[optional [[[]]"), - &[FormatItem::Optional(&FormatItem::Literal(b"["))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Literal( + b"[" + ))] ); assert_eq!( format_description!(version = 1, "[optional [ [[ ]]"), - &[FormatItem::Optional(&FormatItem::Compound(&[ - FormatItem::Literal(b" "), - FormatItem::Literal(b"["), - FormatItem::Literal(b" "), - ]))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + &[ + BorrowedFormatItem::Literal(b" "), + BorrowedFormatItem::Literal(b"["), + BorrowedFormatItem::Literal(b" "), + ] + ))] ); assert_eq!( format_description!(version = 1, "[first [a][[[]]"), - &[FormatItem::First(&[ - FormatItem::Literal(b"a"), - FormatItem::Literal(b"[") + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Literal(b"a"), + BorrowedFormatItem::Literal(b"[") ])] ); } @@ -70,28 +74,34 @@ fn nested_v1() { fn optional() { assert_eq!( format_description!(version = 2, "[optional [:[year]]]"), - &[FormatItem::Optional(&FormatItem::Compound(&[ - FormatItem::Literal(b":"), - FormatItem::Component(Component::Year(Default::default())) - ]))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + &[ + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::Year(Default::default())) + ] + ))] ); assert_eq!( format_description!(version = 2, "[optional [[year]]]"), - &[FormatItem::Optional(&FormatItem::Component( - Component::Year(Default::default()) - ))] + &[BorrowedFormatItem::Optional( + &BorrowedFormatItem::Component(Component::Year(Default::default())) + )] ); assert_eq!( format_description!(version = 2, r"[optional [\[]]"), - &[FormatItem::Optional(&FormatItem::Literal(b"["))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Literal( + b"[" + ))] ); assert_eq!( format_description!(version = 2, r"[optional [ \[ ]]"), - &[FormatItem::Optional(&FormatItem::Compound(&[ - FormatItem::Literal(b" "), - FormatItem::Literal(b"["), - FormatItem::Literal(b" "), - ]))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + &[ + BorrowedFormatItem::Literal(b" "), + BorrowedFormatItem::Literal(b"["), + BorrowedFormatItem::Literal(b" "), + ] + ))] ); } @@ -99,34 +109,39 @@ fn optional() { fn first() { assert_eq!( format_description!(version = 2, "[first [a]]"), - &[FormatItem::First(&[FormatItem::Literal(b"a")])] + &[BorrowedFormatItem::First(&[BorrowedFormatItem::Literal( + b"a" + )])] ); assert_eq!( format_description!(version = 2, "[first [a] [b]]"), - &[FormatItem::First(&[ - FormatItem::Literal(b"a"), - FormatItem::Literal(b"b"), + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Literal(b"a"), + BorrowedFormatItem::Literal(b"b"), ])] ); assert_eq!( format_description!(version = 2, "[first [a][b]]"), - &[FormatItem::First(&[ - FormatItem::Literal(b"a"), - FormatItem::Literal(b"b"), + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Literal(b"a"), + BorrowedFormatItem::Literal(b"b"), ])] ); assert_eq!( format_description!(version = 2, r"[first [a][\[]]"), - &[FormatItem::First(&[ - FormatItem::Literal(b"a"), - FormatItem::Literal(b"["), + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Literal(b"a"), + BorrowedFormatItem::Literal(b"["), ])] ); assert_eq!( format_description!(version = 2, r"[first [a][\[\[]]"), - &[FormatItem::First(&[ - FormatItem::Literal(b"a"), - FormatItem::Compound(&[FormatItem::Literal(b"["), FormatItem::Literal(b"["),]) + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Literal(b"a"), + BorrowedFormatItem::Compound(&[ + BorrowedFormatItem::Literal(b"["), + BorrowedFormatItem::Literal(b"["), + ]) ])] ); assert_eq!( @@ -134,12 +149,12 @@ fn first() { version = 2, "[first [[period case:upper]] [[period case:lower]] ]" ), - &[FormatItem::First(&[ - FormatItem::Component(Component::Period(modifier!(Period { + &[BorrowedFormatItem::First(&[ + BorrowedFormatItem::Component(Component::Period(modifier!(Period { is_uppercase: true, case_sensitive: true, }))), - FormatItem::Component(Component::Period(modifier!(Period { + BorrowedFormatItem::Component(Component::Period(modifier!(Period { is_uppercase: false, case_sensitive: true, }))), @@ -151,47 +166,59 @@ fn first() { fn backslash_escape() { assert_eq!( format_description!(version = 2, r"[optional [\]]]"), - &[FormatItem::Optional(&FormatItem::Literal(b"]"))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Literal( + b"]" + ))] ); assert_eq!( format_description!(version = 2, r"[optional [\[]]"), - &[FormatItem::Optional(&FormatItem::Literal(b"["))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Literal( + b"[" + ))] ); assert_eq!( format_description!(version = 2, r"[optional [\\]]"), - &[FormatItem::Optional(&FormatItem::Literal(br"\"))] + &[BorrowedFormatItem::Optional(&BorrowedFormatItem::Literal( + br"\" + ))] ); assert_eq!( format_description!(version = 2, r"\\"), - &[FormatItem::Literal(br"\")] + &[BorrowedFormatItem::Literal(br"\")] ); assert_eq!( format_description!(version = 2, r"\["), - &[FormatItem::Literal(br"[")] + &[BorrowedFormatItem::Literal(br"[")] ); assert_eq!( format_description!(version = 2, r"\]"), - &[FormatItem::Literal(br"]")] + &[BorrowedFormatItem::Literal(br"]")] ); assert_eq!( format_description!(version = 2, r"foo\\"), - &[FormatItem::Literal(b"foo"), FormatItem::Literal(br"\"),] + &[ + BorrowedFormatItem::Literal(b"foo"), + BorrowedFormatItem::Literal(br"\"), + ] ); assert_eq!( format_description!(version = 2, r"\\"), - &[FormatItem::Literal(br"\")] + &[BorrowedFormatItem::Literal(br"\")] ); assert_eq!( format_description!(version = 2, r"\["), - &[FormatItem::Literal(br"[")] + &[BorrowedFormatItem::Literal(br"[")] ); assert_eq!( format_description!(version = 2, r"\]"), - &[FormatItem::Literal(br"]")] + &[BorrowedFormatItem::Literal(br"]")] ); assert_eq!( format_description!(version = 2, r"foo\\"), - &[FormatItem::Literal(b"foo"), FormatItem::Literal(br"\"),] + &[ + BorrowedFormatItem::Literal(b"foo"), + BorrowedFormatItem::Literal(br"\"), + ] ); } @@ -200,13 +227,13 @@ fn format_description_coverage() { assert_eq!( format_description!("[day padding:space][day padding:zero][day padding:none]"), &[ - FormatItem::Component(Component::Day(modifier!(Day { + BorrowedFormatItem::Component(Component::Day(modifier!(Day { padding: Padding::Space, }))), - FormatItem::Component(Component::Day(modifier!(Day { + BorrowedFormatItem::Component(Component::Day(modifier!(Day { padding: Padding::Zero, }))), - FormatItem::Component(Component::Day(modifier!(Day { + BorrowedFormatItem::Component(Component::Day(modifier!(Day { padding: Padding::None, }))) ] @@ -216,13 +243,13 @@ fn format_description_coverage() { "[offset_minute padding:space][offset_minute padding:zero][offset_minute padding:none]" ), &[ - FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { + BorrowedFormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { padding: Padding::Space, }))), - FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { + BorrowedFormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { padding: Padding::Zero, }))), - FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { + BorrowedFormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { padding: Padding::None, }))) ] @@ -232,13 +259,13 @@ fn format_description_coverage() { "[offset_second padding:space][offset_second padding:zero][offset_second padding:none]" ), &[ - FormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { + BorrowedFormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { padding: Padding::Space, }))), - FormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { + BorrowedFormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { padding: Padding::Zero, }))), - FormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { + BorrowedFormatItem::Component(Component::OffsetSecond(modifier!(OffsetSecond { padding: Padding::None, }))), ] @@ -246,73 +273,82 @@ fn format_description_coverage() { assert_eq!( format_description!("[ordinal padding:space][ordinal padding:zero][ordinal padding:none]"), &[ - FormatItem::Component(Component::Ordinal(modifier!(Ordinal { + BorrowedFormatItem::Component(Component::Ordinal(modifier!(Ordinal { padding: Padding::Space, }))), - FormatItem::Component(Component::Ordinal(modifier!(Ordinal { + BorrowedFormatItem::Component(Component::Ordinal(modifier!(Ordinal { padding: Padding::Zero, }))), - FormatItem::Component(Component::Ordinal(modifier!(Ordinal { + BorrowedFormatItem::Component(Component::Ordinal(modifier!(Ordinal { padding: Padding::None, }))), ] ); assert_eq!( format_description!("[month repr:numerical]"), - &[FormatItem::Component(Component::Month(modifier!(Month { - repr: MonthRepr::Numerical, - padding: Padding::Zero, - })))] + &[BorrowedFormatItem::Component(Component::Month(modifier!( + Month { + repr: MonthRepr::Numerical, + padding: Padding::Zero, + } + )))] ); assert_eq!( format_description!("[week_number repr:iso ]"), - &[FormatItem::Component(Component::WeekNumber(modifier!( - WeekNumber { + &[BorrowedFormatItem::Component(Component::WeekNumber( + modifier!(WeekNumber { padding: Padding::Zero, repr: WeekNumberRepr::Iso, - } - )))] + }) + ))] ); assert_eq!( format_description!("[weekday repr:long one_indexed:true]"), - &[FormatItem::Component(Component::Weekday(modifier!( - Weekday { + &[BorrowedFormatItem::Component(Component::Weekday( + modifier!(Weekday { repr: WeekdayRepr::Long, one_indexed: true, - } - )))] + }) + ))] ); assert_eq!( format_description!("[year repr:full base:calendar]"), - &[FormatItem::Component(Component::Year(modifier!(Year { - repr: YearRepr::Full, - iso_week_based: false, - padding: Padding::Zero, - sign_is_mandatory: false, - })))] + &[BorrowedFormatItem::Component(Component::Year(modifier!( + Year { + repr: YearRepr::Full, + iso_week_based: false, + padding: Padding::Zero, + sign_is_mandatory: false, + } + )))] ); assert_eq!( format_description!("[[ "), - &[FormatItem::Literal(b"["), FormatItem::Literal(b" ")] + &[ + BorrowedFormatItem::Literal(b"["), + BorrowedFormatItem::Literal(b" ") + ] ); assert_eq!( format_description!("[ignore count:2]"), - &[FormatItem::Component(Component::Ignore(Ignore::count( - NonZeroU16::new(2).expect("2 is not zero") - )))] + &[BorrowedFormatItem::Component(Component::Ignore( + Ignore::count(NonZeroU16::new(2).expect("2 is not zero")) + ))] ); assert_eq!( format_description!("[unix_timestamp precision:nanosecond sign:mandatory]"), - &[FormatItem::Component(Component::UnixTimestamp(modifier!( - UnixTimestamp { + &[BorrowedFormatItem::Component(Component::UnixTimestamp( + modifier!(UnixTimestamp { precision: UnixTimestampPrecision::Nanosecond, sign_is_mandatory: true, - } - )))] + }) + ))] ); assert_eq!( format_description!("[end]"), - &[FormatItem::Component(Component::End(modifier!(End)))] + &[BorrowedFormatItem::Component(Component::End(modifier!( + End + )))] ); } diff --git a/tests/meta.rs b/tests/meta.rs index 9142c83cd..ded83b616 100644 --- a/tests/meta.rs +++ b/tests/meta.rs @@ -14,7 +14,7 @@ use quickcheck::Arbitrary; use rand::distributions::{Distribution, Standard}; use serde::{Deserialize, Serialize}; use time::format_description::well_known::iso8601; -use time::format_description::{modifier, well_known, Component, FormatItem}; +use time::format_description::{modifier, well_known, BorrowedFormatItem, Component}; use time::formatting::Formattable; use time::parsing::{Parsable, Parsed}; #[allow(deprecated)] @@ -85,7 +85,7 @@ fn alignment() { assert_alignment!(error::ParseFromDescription, 8); assert_alignment!(error::TryFromParsed, 8); assert_alignment!(Component, 2); - assert_alignment!(FormatItem<'_>, 8); + assert_alignment!(BorrowedFormatItem<'_>, 8); assert_alignment!(modifier::MonthRepr, 1); assert_alignment!(modifier::Padding, 1); assert_alignment!(modifier::SubsecondDigits, 1); @@ -164,7 +164,7 @@ fn size() { assert_size!(error::ParseFromDescription, 24, 24); assert_size!(error::TryFromParsed, 48, 48); assert_size!(Component, 6, 6); // TODO Size is 4 starting with rustc 1.71. - assert_size!(FormatItem<'_>, 24, 24); + assert_size!(BorrowedFormatItem<'_>, 24, 24); assert_size!(modifier::MonthRepr, 1, 1); assert_size!(modifier::Padding, 1, 1); assert_size!(modifier::SubsecondDigits, 1, 1); @@ -914,8 +914,8 @@ assert_impl! { @'a; Component: Clone, Debug, PartialEq, - PartialEq>, - TryFrom, Error = error::DifferentVariant>, + PartialEq>, + TryFrom, Error = error::DifferentVariant>, Copy, Eq, RefUnwindSafe, @@ -924,14 +924,14 @@ assert_impl! { @'a; Component: Unpin, UnwindSafe, } -assert_impl! { @'a; FormatItem<'_>: +assert_impl! { @'a; BorrowedFormatItem<'_>: Clone, Debug, - From<&'a [FormatItem<'a>]>, + From<&'a [BorrowedFormatItem<'a>]>, From, - PartialEq<&'a [FormatItem<'a>]>, + PartialEq<&'a [BorrowedFormatItem<'a>]>, PartialEq, - PartialEq>, + PartialEq>, Eq, Formattable, Parsable, @@ -941,9 +941,9 @@ assert_impl! { @'a; FormatItem<'_>: Unpin, UnwindSafe, } -assert_impl! { @'a; &[FormatItem<'_>]: - PartialEq>, - TryFrom, Error = error::DifferentVariant>, +assert_impl! { @'a; &[BorrowedFormatItem<'_>]: + PartialEq>, + TryFrom, Error = error::DifferentVariant>, } assert_impl! { modifier::MonthRepr: Clone, diff --git a/tests/parse_format_description.rs b/tests/parse_format_description.rs index 8628588a8..f29233c93 100644 --- a/tests/parse_format_description.rs +++ b/tests/parse_format_description.rs @@ -4,7 +4,7 @@ use rstest::rstest; use rstest_reuse::{apply, template}; use time::error::InvalidFormatDescription; use time::format_description::modifier::*; -use time::format_description::{self, Component, FormatItem, OwnedFormatItem}; +use time::format_description::{self, BorrowedFormatItem, Component, OwnedFormatItem}; /// Identical to `modifier!`, but obtains the value from `M` automagically. macro_rules! modifier_m { @@ -138,7 +138,10 @@ fn empty() { fn only_literal(#[case] format_description: &str, #[case] expected: [&[u8]; N]) { assert_eq!( format_description::parse(format_description), - Ok(expected.into_iter().map(FormatItem::Literal).collect()) + Ok(expected + .into_iter() + .map(BorrowedFormatItem::Literal) + .collect()) ); } @@ -162,7 +165,7 @@ fn only_literal(#[case] format_description: &str, #[case] expect fn simple_component(#[case] format_description: &str, #[case] component: Component) { assert_eq!( format_description::parse(format_description), - Ok(vec![FormatItem::Component(component)]) + Ok(vec![BorrowedFormatItem::Component(component)]) ); } @@ -226,9 +229,9 @@ macro_rules! parse_with_modifiers { fn day_component(padding: M) { assert_eq!( parse_with_modifiers!("day", padding), - Ok(vec![FormatItem::Component(Component::Day(modifier_m!( - Day { padding } - )))]) + Ok(vec![BorrowedFormatItem::Component(Component::Day( + modifier_m!(Day { padding }) + ))]) ); } @@ -236,9 +239,9 @@ fn day_component(padding: M) { fn minute_component(padding: M) { assert_eq!( parse_with_modifiers!("minute", padding), - Ok(vec![FormatItem::Component(Component::Minute(modifier_m!( - Minute { padding } - )))]) + Ok(vec![BorrowedFormatItem::Component(Component::Minute( + modifier_m!(Minute { padding }) + ))]) ); } @@ -246,9 +249,9 @@ fn minute_component(padding: M) { fn offset_minute_component(padding: M) { assert_eq!( parse_with_modifiers!("offset_minute", padding), - Ok(vec![FormatItem::Component(Component::OffsetMinute( - modifier_m!(OffsetMinute { padding }) - ))]) + Ok(vec![BorrowedFormatItem::Component( + Component::OffsetMinute(modifier_m!(OffsetMinute { padding })) + )]) ); } @@ -256,9 +259,9 @@ fn offset_minute_component(padding: M) { fn offset_second_component(padding: M) { assert_eq!( parse_with_modifiers!("offset_second", padding), - Ok(vec![FormatItem::Component(Component::OffsetSecond( - modifier_m!(OffsetSecond { padding }) - ))]) + Ok(vec![BorrowedFormatItem::Component( + Component::OffsetSecond(modifier_m!(OffsetSecond { padding })) + )]) ); } @@ -266,7 +269,7 @@ fn offset_second_component(padding: M) { fn ordinal_component(padding: M) { assert_eq!( parse_with_modifiers!("ordinal", padding), - Ok(vec![FormatItem::Component(Component::Ordinal( + Ok(vec![BorrowedFormatItem::Component(Component::Ordinal( modifier_m!(Ordinal { padding }) ))]) ); @@ -276,9 +279,9 @@ fn ordinal_component(padding: M) { fn second_component(padding: M) { assert_eq!( parse_with_modifiers!("second", padding), - Ok(vec![FormatItem::Component(Component::Second(modifier_m!( - Second { padding } - )))]) + Ok(vec![BorrowedFormatItem::Component(Component::Second( + modifier_m!(Second { padding }) + ))]) ); } @@ -286,12 +289,12 @@ fn second_component(padding: M) { fn hour_component(padding: M, hour_is_12_hour_clock: M) { assert_eq!( parse_with_modifiers!("hour", padding, hour_is_12_hour_clock), - Ok(vec![FormatItem::Component(Component::Hour(modifier_m!( - Hour { + Ok(vec![BorrowedFormatItem::Component(Component::Hour( + modifier_m!(Hour { padding, is_12_hour_clock: hour_is_12_hour_clock - } - )))]) + }) + ))]) ); } @@ -299,13 +302,13 @@ fn hour_component(padding: M, hour_is_12_hour_clock: M) { fn month_component(padding: M, case_sensitive: M, month_repr: M) { assert_eq!( parse_with_modifiers!("month", padding, case_sensitive, month_repr), - Ok(vec![FormatItem::Component(Component::Month(modifier_m!( - Month { + Ok(vec![BorrowedFormatItem::Component(Component::Month( + modifier_m!(Month { padding, repr: month_repr, case_sensitive - } - )))]) + }) + ))]) ); } @@ -313,12 +316,12 @@ fn month_component(padding: M, case_sensitive: M, month_repr: M, period_is_uppercase: M) { assert_eq!( parse_with_modifiers!("period", period_is_uppercase, case_sensitive), - Ok(vec![FormatItem::Component(Component::Period(modifier_m!( - Period { + Ok(vec![BorrowedFormatItem::Component(Component::Period( + modifier_m!(Period { is_uppercase: period_is_uppercase, case_sensitive - } - )))]) + }) + ))]) ); } @@ -335,7 +338,7 @@ fn weekday_component( weekday_is_one_indexed, weekday_repr ), - Ok(vec![FormatItem::Component(Component::Weekday( + Ok(vec![BorrowedFormatItem::Component(Component::Weekday( modifier_m!(Weekday { repr: weekday_repr, one_indexed: weekday_is_one_indexed, @@ -349,7 +352,7 @@ fn weekday_component( fn week_number_component(padding: M, week_number_repr: M) { assert_eq!( parse_with_modifiers!("week_number", padding, week_number_repr), - Ok(vec![FormatItem::Component(Component::WeekNumber( + Ok(vec![BorrowedFormatItem::Component(Component::WeekNumber( modifier_m!(WeekNumber { padding, repr: week_number_repr @@ -362,7 +365,7 @@ fn week_number_component(padding: M, week_number_repr: M, sign_is_mandatory: M) { assert_eq!( parse_with_modifiers!("offset_hour", padding, sign_is_mandatory), - Ok(vec![FormatItem::Component(Component::OffsetHour( + Ok(vec![BorrowedFormatItem::Component(Component::OffsetHour( modifier_m!(OffsetHour { padding, sign_is_mandatory @@ -386,14 +389,14 @@ fn year_component( year_is_iso_week_based, sign_is_mandatory ), - Ok(vec![FormatItem::Component(Component::Year(modifier_m!( - Year { + Ok(vec![BorrowedFormatItem::Component(Component::Year( + modifier_m!(Year { padding, repr: year_repr, iso_week_based: year_is_iso_week_based, sign_is_mandatory - } - )))]) + }) + ))]) ); } @@ -408,12 +411,12 @@ fn unix_timestamp_component( sign_is_mandatory, unix_timestamp_precision ), - Ok(vec![FormatItem::Component(Component::UnixTimestamp( - modifier_m!(UnixTimestamp { + Ok(vec![BorrowedFormatItem::Component( + Component::UnixTimestamp(modifier_m!(UnixTimestamp { sign_is_mandatory, precision: unix_timestamp_precision, - }) - ))]) + })) + )]) ); } @@ -421,7 +424,7 @@ fn unix_timestamp_component( fn subsecond_component(subsecond_digits: M) { assert_eq!( parse_with_modifiers!("subsecond", subsecond_digits), - Ok(vec![FormatItem::Component(Component::Subsecond( + Ok(vec![BorrowedFormatItem::Component(Component::Subsecond( modifier_m!(Subsecond { digits: subsecond_digits }) @@ -433,7 +436,7 @@ fn subsecond_component(subsecond_digits: M) { fn ignore_component(ignore_count: M) { assert_eq!( parse_with_modifiers!("ignore", ignore_count), - Ok(vec![FormatItem::Component(Component::Ignore( + Ok(vec![BorrowedFormatItem::Component(Component::Ignore( Ignore::count(ignore_count.0) ))]) ); @@ -572,21 +575,21 @@ fn backslash_escape() { ); assert_eq!( format_description::parse_borrowed::<2>(r"\\"), - Ok(vec![FormatItem::Literal(br"\")]) + Ok(vec![BorrowedFormatItem::Literal(br"\")]) ); assert_eq!( format_description::parse_borrowed::<2>(r"\["), - Ok(vec![FormatItem::Literal(br"[")]) + Ok(vec![BorrowedFormatItem::Literal(br"[")]) ); assert_eq!( format_description::parse_borrowed::<2>(r"\]"), - Ok(vec![FormatItem::Literal(br"]")]) + Ok(vec![BorrowedFormatItem::Literal(br"]")]) ); assert_eq!( format_description::parse_borrowed::<2>(r"foo\\"), Ok(vec![ - FormatItem::Literal(b"foo"), - FormatItem::Literal(br"\"), + BorrowedFormatItem::Literal(b"foo"), + BorrowedFormatItem::Literal(br"\"), ]) ); } @@ -751,44 +754,44 @@ fn rfc_3339() { sign:mandatory]:[offset_minute]" ), Ok(vec![ - FormatItem::Component(Component::Year(modifier!(Year { + BorrowedFormatItem::Component(Component::Year(modifier!(Year { padding: Padding::Zero, repr: YearRepr::Full, iso_week_based: false, sign_is_mandatory: false }))), - FormatItem::Literal(b"-"), - FormatItem::Component(Component::Month(modifier!(Month { + BorrowedFormatItem::Literal(b"-"), + BorrowedFormatItem::Component(Component::Month(modifier!(Month { padding: Padding::Zero, repr: MonthRepr::Numerical }))), - FormatItem::Literal(b"-"), - FormatItem::Component(Component::Day(modifier!(Day { + BorrowedFormatItem::Literal(b"-"), + BorrowedFormatItem::Component(Component::Day(modifier!(Day { padding: Padding::Zero }))), - FormatItem::Literal(b"T"), - FormatItem::Component(Component::Hour(modifier!(Hour { + BorrowedFormatItem::Literal(b"T"), + BorrowedFormatItem::Component(Component::Hour(modifier!(Hour { padding: Padding::Zero, is_12_hour_clock: false }))), - FormatItem::Literal(b":"), - FormatItem::Component(Component::Minute(modifier!(Minute { + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::Minute(modifier!(Minute { padding: Padding::Zero }))), - FormatItem::Literal(b":"), - FormatItem::Component(Component::Second(modifier!(Second { + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::Second(modifier!(Second { padding: Padding::Zero }))), - FormatItem::Literal(b"."), - FormatItem::Component(Component::Subsecond(modifier!(Subsecond { + BorrowedFormatItem::Literal(b"."), + BorrowedFormatItem::Component(Component::Subsecond(modifier!(Subsecond { digits: SubsecondDigits::OneOrMore }))), - FormatItem::Component(Component::OffsetHour(modifier!(OffsetHour { + BorrowedFormatItem::Component(Component::OffsetHour(modifier!(OffsetHour { padding: Padding::Zero, sign_is_mandatory: true }))), - FormatItem::Literal(b":"), - FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute { padding: Padding::Zero }))) ]) diff --git a/tests/parsed.rs b/tests/parsed.rs index e950a364a..bb63e36b1 100644 --- a/tests/parsed.rs +++ b/tests/parsed.rs @@ -1,7 +1,7 @@ use std::num::{NonZeroU16, NonZeroU8}; use time::format_description::modifier::WeekNumberRepr; -use time::format_description::{Component, FormatItem}; +use time::format_description::{BorrowedFormatItem, Component}; use time::parsing::Parsed; use time::{error, Month, Time, Weekday}; @@ -129,8 +129,8 @@ fn builder_methods() { #[test] fn single_item_parse() { - assert!(Time::parse("a", &FormatItem::Literal(b"a")).is_err()); - assert!(Time::parse("b", &FormatItem::Literal(b"a")).is_err()); + assert!(Time::parse("a", &BorrowedFormatItem::Literal(b"a")).is_err()); + assert!(Time::parse("b", &BorrowedFormatItem::Literal(b"a")).is_err()); } #[test] diff --git a/tests/parsing.rs b/tests/parsing.rs index f3ca87713..192a96498 100644 --- a/tests/parsing.rs +++ b/tests/parsing.rs @@ -2,7 +2,7 @@ use std::num::{NonZeroU16, NonZeroU8}; use time::format_description::modifier::Ignore; use time::format_description::well_known::{Iso8601, Rfc2822, Rfc3339}; -use time::format_description::{modifier, Component, FormatItem, OwnedFormatItem}; +use time::format_description::{modifier, BorrowedFormatItem, Component, OwnedFormatItem}; use time::macros::{date, datetime, offset, time}; use time::parsing::Parsed; use time::{ @@ -1455,7 +1455,9 @@ fn parse_optional() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &FormatItem::Optional(&FormatItem::Compound(&fd::parse("[year]-[month]-[day]")?)), + &BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&fd::parse( + "[year]-[month]-[day]", + )?)), )?; assert!(remaining_input.is_empty()); assert_eq!(parsed.year(), Some(2021)); @@ -1465,9 +1467,9 @@ fn parse_optional() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &OwnedFormatItem::from(FormatItem::Optional(&FormatItem::Compound(&fd::parse( - "[year]-[month]-[day]", - )?))), + &OwnedFormatItem::from(BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + &fd::parse("[year]-[month]-[day]")?, + ))), )?; assert!(remaining_input.is_empty()); assert_eq!(parsed.year(), Some(2021)); @@ -1478,7 +1480,9 @@ fn parse_optional() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01", - &FormatItem::Optional(&FormatItem::Compound(&fd::parse("[year]-[month]-[day]")?)), + &BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&fd::parse( + "[year]-[month]-[day]", + )?)), )?; assert_eq!(remaining_input, b"2021-01"); assert!(parsed.year().is_none()); @@ -1488,9 +1492,9 @@ fn parse_optional() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01", - &OwnedFormatItem::from(FormatItem::Optional(&FormatItem::Compound(&fd::parse( - "[year]-[month]-[day]", - )?))), + &OwnedFormatItem::from(BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound( + &fd::parse("[year]-[month]-[day]")?, + ))), )?; assert_eq!(remaining_input, b"2021-01"); assert!(parsed.year().is_none()); @@ -1507,7 +1511,9 @@ fn parse_first() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &FormatItem::First(&[FormatItem::Compound(&fd::parse("[year]-[month]-[day]")?)]), + &BorrowedFormatItem::First(&[BorrowedFormatItem::Compound(&fd::parse( + "[year]-[month]-[day]", + )?)]), )?; assert!(remaining_input.is_empty()); assert_eq!(parsed.year(), Some(2021)); @@ -1517,9 +1523,9 @@ fn parse_first() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &OwnedFormatItem::from(FormatItem::First(&[FormatItem::Compound(&fd::parse( - "[year]-[month]-[day]", - )?)])), + &OwnedFormatItem::from(BorrowedFormatItem::First(&[BorrowedFormatItem::Compound( + &fd::parse("[year]-[month]-[day]")?, + )])), )?; assert!(remaining_input.is_empty()); assert_eq!(parsed.year(), Some(2021)); @@ -1528,7 +1534,7 @@ fn parse_first() -> time::Result<()> { // Ensure an empty slice is a no-op success. let mut parsed = Parsed::new(); - let remaining_input = parsed.parse_item(b"2021-01-02", &FormatItem::First(&[]))?; + let remaining_input = parsed.parse_item(b"2021-01-02", &BorrowedFormatItem::First(&[]))?; assert_eq!(remaining_input, b"2021-01-02"); assert!(parsed.year().is_none()); assert!(parsed.month().is_none()); @@ -1546,10 +1552,10 @@ fn parse_first() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &FormatItem::First(&[ - FormatItem::Compound(&fd::parse("[period]")?), - FormatItem::Compound(&fd::parse("x")?), - FormatItem::Compound(&fd::parse("[year]-[month]-[day]")?), + &BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(&fd::parse("[period]")?), + BorrowedFormatItem::Compound(&fd::parse("x")?), + BorrowedFormatItem::Compound(&fd::parse("[year]-[month]-[day]")?), ]), )?; assert!(remaining_input.is_empty()); @@ -1560,10 +1566,10 @@ fn parse_first() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"2021-01-02", - &OwnedFormatItem::from(FormatItem::First(&[ - FormatItem::Compound(&fd::parse("[period]")?), - FormatItem::Compound(&fd::parse("x")?), - FormatItem::Compound(&fd::parse("[year]-[month]-[day]")?), + &OwnedFormatItem::from(BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(&fd::parse("[period]")?), + BorrowedFormatItem::Compound(&fd::parse("x")?), + BorrowedFormatItem::Compound(&fd::parse("[year]-[month]-[day]")?), ])), )?; assert!(remaining_input.is_empty()); @@ -1576,9 +1582,9 @@ fn parse_first() -> time::Result<()> { let err = parsed .parse_item( b"2021-01-02", - &FormatItem::First(&[ - FormatItem::Compound(&fd::parse("[period]")?), - FormatItem::Compound(&fd::parse("x")?), + &BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(&fd::parse("[period]")?), + BorrowedFormatItem::Compound(&fd::parse("x")?), ]), ) .expect_err("parsing should fail"); @@ -1588,9 +1594,9 @@ fn parse_first() -> time::Result<()> { let err = parsed .parse_item( b"2021-01-02", - &OwnedFormatItem::from(FormatItem::First(&[ - FormatItem::Compound(&fd::parse("[period]")?), - FormatItem::Compound(&fd::parse("x")?), + &OwnedFormatItem::from(BorrowedFormatItem::First(&[ + BorrowedFormatItem::Compound(&fd::parse("[period]")?), + BorrowedFormatItem::Compound(&fd::parse("x")?), ])), ) .expect_err("parsing should fail"); @@ -1681,7 +1687,7 @@ fn end() -> time::Result<()> { let mut parsed = Parsed::new(); let remaining_input = parsed.parse_item( b"", - &FormatItem::Component(Component::End(modifier::End::default())), + &BorrowedFormatItem::Component(Component::End(modifier::End::default())), ); assert_eq!(remaining_input, Ok(b"".as_slice())); diff --git a/tests/serde/macros.rs b/tests/serde/macros.rs index 66037b7e7..6a02344f4 100644 --- a/tests/serde/macros.rs +++ b/tests/serde/macros.rs @@ -5,7 +5,7 @@ use serde_test::{ Token, }; use time::format_description::well_known::{iso8601, Iso8601}; -use time::format_description::FormatItem; +use time::format_description::BorrowedFormatItem; use time::macros::{date, datetime, offset, time}; use time::{serde, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; @@ -34,7 +34,8 @@ serde::format_description!( "custom format: [offset_hour sign:mandatory]:[offset_minute]" ); -const TIME_FORMAT_ALT: &[FormatItem<'_>] = time::macros::format_description!("[hour]:[minute]"); +const TIME_FORMAT_ALT: &[BorrowedFormatItem<'_>] = + time::macros::format_description!("[hour]:[minute]"); serde::format_description!(time_format_alt, Time, TIME_FORMAT_ALT); #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] diff --git a/time-macros/src/format_description/public/mod.rs b/time-macros/src/format_description/public/mod.rs index ccb0b6e2a..9fd8b5ece 100644 --- a/time-macros/src/format_description/public/mod.rs +++ b/time-macros/src/format_description/public/mod.rs @@ -19,12 +19,12 @@ impl ToTokenStream for OwnedFormatItem { fn append_to(self, ts: &mut TokenStream) { match self { Self::Literal(bytes) => quote_append! { ts - ::time::format_description::FormatItem::Literal { + ::time::format_description::BorrowedFormatItem::Literal { 0: #(Literal::byte_string(bytes.as_ref())) } }, Self::Component(component) => quote_append! { ts - ::time::format_description::FormatItem::Component { 0: #S(component) } + ::time::format_description::BorrowedFormatItem::Component { 0: #S(component) } }, Self::Compound(items) => { let items = items @@ -33,11 +33,11 @@ impl ToTokenStream for OwnedFormatItem { .map(|item| quote! { #S(item), }) .collect::(); quote_append! { ts - ::time::format_description::FormatItem::Compound { 0: &[#S(items)] } + ::time::format_description::BorrowedFormatItem::Compound { 0: &[#S(items)] } } } Self::Optional(item) => quote_append! {ts - ::time::format_description::FormatItem::Optional { 0: &#S(*item) } + ::time::format_description::BorrowedFormatItem::Optional { 0: &#S(*item) } }, Self::First(items) => { let items = items @@ -46,7 +46,7 @@ impl ToTokenStream for OwnedFormatItem { .map(|item| quote! { #S(item), }) .collect::(); quote_append! { ts - ::time::format_description::FormatItem::First { 0: &[#S(items)] } + ::time::format_description::BorrowedFormatItem::First { 0: &[#S(items)] } } } } diff --git a/time-macros/src/lib.rs b/time-macros/src/lib.rs index 04f6a7583..65e24d7d3 100644 --- a/time-macros/src/lib.rs +++ b/time-macros/src/lib.rs @@ -151,7 +151,7 @@ pub fn format_description(input: TokenStream) -> TokenStream { let items = format_description::parse_with_version(version, &string, span)?; Ok(quote! {{ - const DESCRIPTION: &[::time::format_description::FormatItem<'_>] = &[#S( + const DESCRIPTION: &[::time::format_description::BorrowedFormatItem<'_>] = &[#S( items .into_iter() .map(|item| quote! { #S(item), }) @@ -212,7 +212,8 @@ pub fn serde_format_description(input: TokenStream) -> TokenStream { let items: TokenStream = items.into_iter().map(|item| quote! { #S(item), }).collect(); let items = quote! { - const ITEMS: &[::time::format_description::FormatItem<'_>] = &[#S(items)]; + const ITEMS: &[::time::format_description::BorrowedFormatItem<'_>] + = &[#S(items)]; ITEMS }; diff --git a/time/src/format_description/borrowed_format_item.rs b/time/src/format_description/borrowed_format_item.rs index 425b90287..4ef5a1756 100644 --- a/time/src/format_description/borrowed_format_item.rs +++ b/time/src/format_description/borrowed_format_item.rs @@ -5,6 +5,16 @@ use alloc::string::String; #[cfg(feature = "alloc")] use core::fmt; +/// A complete description of how to format and parse a type. +/// +/// This alias exists for backwards-compatibility. It is recommended to use `BorrowedFormatItem` +/// for clarity, as it is more explicit that the data is borrowed rather than owned. +#[deprecated( + since = "0.3.35", + note = "use `BorrowedFormatItem` instead for clarity" +)] +pub type FormatItem<'a> = BorrowedFormatItem<'a>; + use crate::error; use crate::format_description::Component; @@ -15,8 +25,8 @@ use crate::format_description::Component; pub enum BorrowedFormatItem<'a> { /// Bytes that are formatted as-is. /// - /// **Note**: If you call the `format` method that returns a `String`, these bytes will be - /// passed through `String::from_utf8_lossy`. + /// **Note**: These bytes **should** be UTF-8, but are not required to be. The value is passed + /// through `String::from_utf8_lossy` when necessary. Literal(&'a [u8]), /// A minimal representation of a single non-literal item. Component(Component), diff --git a/time/src/format_description/mod.rs b/time/src/format_description/mod.rs index befae8b56..67882afe7 100644 --- a/time/src/format_description/mod.rs +++ b/time/src/format_description/mod.rs @@ -15,7 +15,9 @@ mod owned_format_item; #[cfg(feature = "alloc")] mod parse; -pub use borrowed_format_item::BorrowedFormatItem as FormatItem; +pub use borrowed_format_item::BorrowedFormatItem; +#[allow(deprecated)] +pub use borrowed_format_item::FormatItem; #[cfg(feature = "alloc")] pub use owned_format_item::OwnedFormatItem; diff --git a/time/src/format_description/owned_format_item.rs b/time/src/format_description/owned_format_item.rs index 6f7f7c233..31ea9f90b 100644 --- a/time/src/format_description/owned_format_item.rs +++ b/time/src/format_description/owned_format_item.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use core::fmt; use crate::error; -use crate::format_description::{Component, FormatItem}; +use crate::format_description::{BorrowedFormatItem, Component}; /// A complete description of how to format and parse a type. #[non_exhaustive] @@ -14,8 +14,8 @@ use crate::format_description::{Component, FormatItem}; pub enum OwnedFormatItem { /// Bytes that are formatted as-is. /// - /// **Note**: If you call the `format` method that returns a `String`, these bytes will be - /// passed through `String::from_utf8_lossy`. + /// **Note**: These bytes **should** be UTF-8, but are not required to be. The value is passed + /// through `String::from_utf8_lossy` when necessary. Literal(Box<[u8]>), /// A minimal representation of a single non-literal item. Component(Component), @@ -46,18 +46,20 @@ impl fmt::Debug for OwnedFormatItem { } // region: conversions from FormatItem -impl From> for OwnedFormatItem { - fn from(item: FormatItem<'_>) -> Self { +impl From> for OwnedFormatItem { + fn from(item: BorrowedFormatItem<'_>) -> Self { (&item).into() } } -impl From<&FormatItem<'_>> for OwnedFormatItem { - fn from(item: &FormatItem<'_>) -> Self { +impl From<&BorrowedFormatItem<'_>> for OwnedFormatItem { + fn from(item: &BorrowedFormatItem<'_>) -> Self { match item { - FormatItem::Literal(literal) => Self::Literal(literal.to_vec().into_boxed_slice()), - FormatItem::Component(component) => Self::Component(*component), - FormatItem::Compound(compound) => Self::Compound( + BorrowedFormatItem::Literal(literal) => { + Self::Literal(literal.to_vec().into_boxed_slice()) + } + BorrowedFormatItem::Component(component) => Self::Component(*component), + BorrowedFormatItem::Compound(compound) => Self::Compound( compound .iter() .cloned() @@ -65,8 +67,8 @@ impl From<&FormatItem<'_>> for OwnedFormatItem { .collect::>() .into_boxed_slice(), ), - FormatItem::Optional(item) => Self::Optional(Box::new((*item).into())), - FormatItem::First(items) => Self::First( + BorrowedFormatItem::Optional(item) => Self::Optional(Box::new((*item).into())), + BorrowedFormatItem::First(items) => Self::First( items .iter() .cloned() @@ -78,13 +80,13 @@ impl From<&FormatItem<'_>> for OwnedFormatItem { } } -impl From>> for OwnedFormatItem { - fn from(items: Vec>) -> Self { +impl From>> for OwnedFormatItem { + fn from(items: Vec>) -> Self { items.as_slice().into() } } -impl<'a, T: AsRef<[FormatItem<'a>]> + ?Sized> From<&T> for OwnedFormatItem { +impl<'a, T: AsRef<[BorrowedFormatItem<'a>]> + ?Sized> From<&T> for OwnedFormatItem { fn from(items: &T) -> Self { Self::Compound( items diff --git a/time/src/format_description/parse/format_item.rs b/time/src/format_description/parse/format_item.rs index f33078ec4..3199b079b 100644 --- a/time/src/format_description/parse/format_item.rs +++ b/time/src/format_description/parse/format_item.rs @@ -102,7 +102,7 @@ impl Item<'_> { } } -impl<'a> TryFrom> for crate::format_description::FormatItem<'a> { +impl<'a> TryFrom> for crate::format_description::BorrowedFormatItem<'a> { type Error = Error; fn try_from(item: Item<'a>) -> Result { diff --git a/time/src/format_description/parse/mod.rs b/time/src/format_description/parse/mod.rs index 22ca52591..602ecf71f 100644 --- a/time/src/format_description/parse/mod.rs +++ b/time/src/format_description/parse/mod.rs @@ -3,6 +3,8 @@ use alloc::boxed::Box; use alloc::vec::Vec; +use crate::{error, format_description}; + /// A helper macro to make version restrictions simpler to read and write. macro_rules! version { ($range:expr) => { @@ -40,8 +42,7 @@ impl Version { /// `parse_borrowed`. pub fn parse( s: &str, -) -> Result>, crate::error::InvalidFormatDescription> -{ +) -> Result>, error::InvalidFormatDescription> { parse_borrowed::<1>(s) } @@ -52,8 +53,7 @@ pub fn parse( /// description is provided as the const parameter. **It is recommended to use version 2.** pub fn parse_borrowed( s: &str, -) -> Result>, crate::error::InvalidFormatDescription> -{ +) -> Result>, error::InvalidFormatDescription> { validate_version!(VERSION); let mut lexed = lexer::lex::(s.as_bytes()); let ast = ast::parse::<_, VERSION>(&mut lexed); @@ -75,7 +75,7 @@ pub fn parse_borrowed( /// [`OwnedFormatItem`]: crate::format_description::OwnedFormatItem pub fn parse_owned( s: &str, -) -> Result { +) -> Result { validate_version!(VERSION); let mut lexed = lexer::lex::(s.as_bytes()); let ast = ast::parse::<_, VERSION>(&mut lexed); @@ -220,10 +220,10 @@ struct Error { /// The internal error. _inner: Unused, /// The error needed for interoperability with the rest of `time`. - public: crate::error::InvalidFormatDescription, + public: error::InvalidFormatDescription, } -impl From for crate::error::InvalidFormatDescription { +impl From for error::InvalidFormatDescription { fn from(error: Error) -> Self { error.public } diff --git a/time/src/formatting/formattable.rs b/time/src/formatting/formattable.rs index 7256a8acd..7ee17a5cc 100644 --- a/time/src/formatting/formattable.rs +++ b/time/src/formatting/formattable.rs @@ -9,7 +9,7 @@ use num_conv::prelude::*; use crate::format_description::well_known::iso8601::EncodedConfig; use crate::format_description::well_known::{Iso8601, Rfc2822, Rfc3339}; -use crate::format_description::{FormatItem, OwnedFormatItem}; +use crate::format_description::{BorrowedFormatItem, OwnedFormatItem}; use crate::formatting::{ format_component, format_number_pad_zero, iso8601, write, MONTH_NAMES, WEEKDAY_NAMES, }; @@ -23,8 +23,8 @@ use crate::{error, Date, Time, UtcOffset}; /// a String from their data. See the respective methods for usage examples. #[cfg_attr(__time_03_docs, doc(notable_trait))] pub trait Formattable: sealed::Sealed {} -impl Formattable for FormatItem<'_> {} -impl Formattable for [FormatItem<'_>] {} +impl Formattable for BorrowedFormatItem<'_> {} +impl Formattable for [BorrowedFormatItem<'_>] {} impl Formattable for OwnedFormatItem {} impl Formattable for [OwnedFormatItem] {} impl Formattable for Rfc3339 {} @@ -63,7 +63,7 @@ mod sealed { } // region: custom formats -impl sealed::Sealed for FormatItem<'_> { +impl sealed::Sealed for BorrowedFormatItem<'_> { fn format_into( &self, output: &mut impl io::Write, @@ -84,7 +84,7 @@ impl sealed::Sealed for FormatItem<'_> { } } -impl sealed::Sealed for [FormatItem<'_>] { +impl sealed::Sealed for [BorrowedFormatItem<'_>] { fn format_into( &self, output: &mut impl io::Write, diff --git a/time/src/macros.rs b/time/src/macros.rs index 4f295e2ed..d78864568 100644 --- a/time/src/macros.rs +++ b/time/src/macros.rs @@ -51,8 +51,8 @@ pub use time_macros::date; pub use time_macros::datetime; /// Equivalent of performing [`format_description::parse()`] at compile time. /// -/// Using the macro instead of the function results in a static slice rather than a [`Vec`], -/// such that it can be used in `#![no_alloc]` situations. +/// Using the macro instead of the function results in a static slice rather than a +/// [`Vec`](alloc::vec::Vec), such that it can be used in `#![no_alloc]` situations. /// /// The resulting expression can be used in `const` or `static` declarations, and implements /// the sealed traits required for both formatting and parsing. diff --git a/time/src/parsing/parsable.rs b/time/src/parsing/parsable.rs index a86259316..36f663b1f 100644 --- a/time/src/parsing/parsable.rs +++ b/time/src/parsing/parsable.rs @@ -7,7 +7,7 @@ use num_conv::prelude::*; use crate::error::TryFromParsed; use crate::format_description::well_known::iso8601::EncodedConfig; use crate::format_description::well_known::{Iso8601, Rfc2822, Rfc3339}; -use crate::format_description::FormatItem; +use crate::format_description::BorrowedFormatItem; #[cfg(feature = "alloc")] use crate::format_description::OwnedFormatItem; use crate::internal_macros::bug; @@ -18,8 +18,8 @@ use crate::{error, Date, Month, OffsetDateTime, Time, UtcOffset, Weekday}; #[cfg_attr(__time_03_docs, doc(notable_trait))] #[doc(alias = "Parseable")] pub trait Parsable: sealed::Sealed {} -impl Parsable for FormatItem<'_> {} -impl Parsable for [FormatItem<'_>] {} +impl Parsable for BorrowedFormatItem<'_> {} +impl Parsable for [BorrowedFormatItem<'_>] {} #[cfg(feature = "alloc")] impl Parsable for OwnedFormatItem {} #[cfg(feature = "alloc")] @@ -93,7 +93,7 @@ mod sealed { } // region: custom formats -impl sealed::Sealed for FormatItem<'_> { +impl sealed::Sealed for BorrowedFormatItem<'_> { fn parse_into<'a>( &self, input: &'a [u8], @@ -103,7 +103,7 @@ impl sealed::Sealed for FormatItem<'_> { } } -impl sealed::Sealed for [FormatItem<'_>] { +impl sealed::Sealed for [BorrowedFormatItem<'_>] { fn parse_into<'a>( &self, input: &'a [u8], diff --git a/time/src/parsing/parsed.rs b/time/src/parsing/parsed.rs index 94fc1225d..3c6c4f511 100644 --- a/time/src/parsing/parsed.rs +++ b/time/src/parsing/parsed.rs @@ -13,7 +13,7 @@ use crate::date::{MAX_YEAR, MIN_YEAR}; use crate::error::TryFromParsed::InsufficientInformation; #[cfg(feature = "alloc")] use crate::format_description::OwnedFormatItem; -use crate::format_description::{modifier, Component, FormatItem}; +use crate::format_description::{modifier, BorrowedFormatItem, Component}; use crate::internal_macros::{bug, const_try_opt}; use crate::parsing::component::{ parse_day, parse_end, parse_hour, parse_ignore, parse_minute, parse_month, parse_offset_hour, @@ -38,7 +38,7 @@ mod sealed { } } -impl sealed::AnyFormatItem for FormatItem<'_> { +impl sealed::AnyFormatItem for BorrowedFormatItem<'_> { fn parse_item<'a>( &self, parsed: &mut Parsed, @@ -213,11 +213,11 @@ impl Parsed { } } - /// Parse a single [`FormatItem`] or [`OwnedFormatItem`], mutating the struct. The remaining - /// input is returned as the `Ok` value. + /// Parse a single [`BorrowedFormatItem`] or [`OwnedFormatItem`], mutating the struct. The + /// remaining input is returned as the `Ok` value. /// - /// If a [`FormatItem::Optional`] or [`OwnedFormatItem::Optional`] is passed, parsing will not - /// fail; the input will be returned as-is if the expected format is not present. + /// If a [`BorrowedFormatItem::Optional`] or [`OwnedFormatItem::Optional`] is passed, parsing + /// will not fail; the input will be returned as-is if the expected format is not present. pub fn parse_item<'a>( &mut self, input: &'a [u8], @@ -226,11 +226,11 @@ impl Parsed { item.parse_item(self, input) } - /// Parse a sequence of [`FormatItem`]s or [`OwnedFormatItem`]s, mutating the struct. The - /// remaining input is returned as the `Ok` value. + /// Parse a sequence of [`BorrowedFormatItem`]s or [`OwnedFormatItem`]s, mutating the struct. + /// The remaining input is returned as the `Ok` value. /// - /// This method will fail if any of the contained [`FormatItem`]s or [`OwnedFormatItem`]s fail - /// to parse. `self` will not be mutated in this instance. + /// This method will fail if any of the contained [`BorrowedFormatItem`]s or + /// [`OwnedFormatItem`]s fail to parse. `self` will not be mutated in this instance. pub fn parse_items<'a>( &mut self, mut input: &'a [u8], diff --git a/time/src/serde/mod.rs b/time/src/serde/mod.rs index 1468e2191..fadc44306 100644 --- a/time/src/serde/mod.rs +++ b/time/src/serde/mod.rs @@ -119,9 +119,9 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; doc = "use ::serde::Deserialize;" )] /// use time::serde; -/// use time::format_description::FormatItem; +/// use time::format_description::BorrowedFormatItem; /// -/// const DATE_TIME_FORMAT: &[FormatItem<'_>] = time::macros::format_description!( +/// const DATE_TIME_FORMAT: &[BorrowedFormatItem<'_>] = time::macros::format_description!( /// "hour=[hour], minute=[minute]" /// ); /// @@ -208,18 +208,18 @@ pub use time_macros::serde_format_description as format_description; use self::visitor::Visitor; #[cfg(feature = "parsing")] -use crate::format_description::{modifier, Component, FormatItem}; +use crate::format_description::{modifier, BorrowedFormatItem, Component}; use crate::{Date, Duration, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; // region: Date /// The format used when serializing and deserializing a human-readable `Date`. #[cfg(feature = "parsing")] -const DATE_FORMAT: &[FormatItem<'_>] = &[ - FormatItem::Component(Component::Year(modifier::Year::default())), - FormatItem::Literal(b"-"), - FormatItem::Component(Component::Month(modifier::Month::default())), - FormatItem::Literal(b"-"), - FormatItem::Component(Component::Day(modifier::Day::default())), +const DATE_FORMAT: &[BorrowedFormatItem<'_>] = &[ + BorrowedFormatItem::Component(Component::Year(modifier::Year::default())), + BorrowedFormatItem::Literal(b"-"), + BorrowedFormatItem::Component(Component::Month(modifier::Month::default())), + BorrowedFormatItem::Literal(b"-"), + BorrowedFormatItem::Component(Component::Day(modifier::Day::default())), ]; impl Serialize for Date { @@ -277,12 +277,12 @@ impl<'a> Deserialize<'a> for Duration { // region: OffsetDateTime /// The format used when serializing and deserializing a human-readable `OffsetDateTime`. #[cfg(feature = "parsing")] -const OFFSET_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ - FormatItem::Compound(DATE_FORMAT), - FormatItem::Literal(b" "), - FormatItem::Compound(TIME_FORMAT), - FormatItem::Literal(b" "), - FormatItem::Compound(UTC_OFFSET_FORMAT), +const OFFSET_DATE_TIME_FORMAT: &[BorrowedFormatItem<'_>] = &[ + BorrowedFormatItem::Compound(DATE_FORMAT), + BorrowedFormatItem::Literal(b" "), + BorrowedFormatItem::Compound(TIME_FORMAT), + BorrowedFormatItem::Literal(b" "), + BorrowedFormatItem::Compound(UTC_OFFSET_FORMAT), ]; impl Serialize for OffsetDateTime { @@ -324,10 +324,10 @@ impl<'a> Deserialize<'a> for OffsetDateTime { // region: PrimitiveDateTime /// The format used when serializing and deserializing a human-readable `PrimitiveDateTime`. #[cfg(feature = "parsing")] -const PRIMITIVE_DATE_TIME_FORMAT: &[FormatItem<'_>] = &[ - FormatItem::Compound(DATE_FORMAT), - FormatItem::Literal(b" "), - FormatItem::Compound(TIME_FORMAT), +const PRIMITIVE_DATE_TIME_FORMAT: &[BorrowedFormatItem<'_>] = &[ + BorrowedFormatItem::Compound(DATE_FORMAT), + BorrowedFormatItem::Literal(b" "), + BorrowedFormatItem::Compound(TIME_FORMAT), ]; impl Serialize for PrimitiveDateTime { @@ -366,14 +366,14 @@ impl<'a> Deserialize<'a> for PrimitiveDateTime { // region: Time /// The format used when serializing and deserializing a human-readable `Time`. #[cfg(feature = "parsing")] -const TIME_FORMAT: &[FormatItem<'_>] = &[ - FormatItem::Component(Component::Hour(::default())), - FormatItem::Literal(b":"), - FormatItem::Component(Component::Minute(::default())), - FormatItem::Literal(b":"), - FormatItem::Component(Component::Second(::default())), - FormatItem::Literal(b"."), - FormatItem::Component(Component::Subsecond(::default())), +const TIME_FORMAT: &[BorrowedFormatItem<'_>] = &[ + BorrowedFormatItem::Component(Component::Hour(modifier::Hour::default())), + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::Minute(modifier::Minute::default())), + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::Second(modifier::Second::default())), + BorrowedFormatItem::Literal(b"."), + BorrowedFormatItem::Component(Component::Subsecond(modifier::Subsecond::default())), ]; impl Serialize for Time { @@ -404,18 +404,20 @@ impl<'a> Deserialize<'a> for Time { // region: UtcOffset /// The format used when serializing and deserializing a human-readable `UtcOffset`. #[cfg(feature = "parsing")] -const UTC_OFFSET_FORMAT: &[FormatItem<'_>] = &[ - FormatItem::Component(Component::OffsetHour({ +const UTC_OFFSET_FORMAT: &[BorrowedFormatItem<'_>] = &[ + BorrowedFormatItem::Component(Component::OffsetHour({ let mut m = modifier::OffsetHour::default(); m.sign_is_mandatory = true; m })), - FormatItem::Optional(&FormatItem::Compound(&[ - FormatItem::Literal(b":"), - FormatItem::Component(Component::OffsetMinute(modifier::OffsetMinute::default())), - FormatItem::Optional(&FormatItem::Compound(&[ - FormatItem::Literal(b":"), - FormatItem::Component(Component::OffsetSecond(modifier::OffsetSecond::default())), + BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&[ + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::OffsetMinute(modifier::OffsetMinute::default())), + BorrowedFormatItem::Optional(&BorrowedFormatItem::Compound(&[ + BorrowedFormatItem::Literal(b":"), + BorrowedFormatItem::Component(Component::OffsetSecond( + modifier::OffsetSecond::default(), + )), ])), ])), ];