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

Update ixdtf to handle unbound fraction length #6036

Merged
merged 14 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 15 additions & 22 deletions components/time/src/ixdtf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub enum ParseError {
InconsistentTimeUtcOffsets,
/// There was an invalid Offset.
InvalidOffsetError,
/// Parsed fractional digits had excessive precision beyond nanosecond.
ExcessivePrecision,
/// The set of time zone fields was not expected for the given type.
/// For example, if a named time zone was present with offset-only parsing,
/// or an offset was present with named-time-zone-only parsing.
Expand Down Expand Up @@ -275,12 +277,7 @@ impl<'a> Intermediate<'a> {
};
let time_zone_id = mapper.iana_bytes_to_bcp47(iana_identifier);
let date = Date::<Iso>::try_new_iso(self.date.year, self.date.month, self.date.day)?;
let time = Time::try_new(
self.time.hour,
self.time.minute,
self.time.second,
self.time.nanosecond,
)?;
let time = Time::try_from_time_record(&self.time)?;
let offset = match time_zone_id.as_str() {
"utc" | "gmt" => Some(UtcOffset::zero()),
_ => None,
Expand Down Expand Up @@ -316,12 +313,7 @@ impl<'a> Intermediate<'a> {
},
};
let date = Date::<Iso>::try_new_iso(self.date.year, self.date.month, self.date.day)?;
let time = Time::try_new(
self.time.hour,
self.time.minute,
self.time.second,
self.time.nanosecond,
)?;
let time = Time::try_from_time_record(&self.time)?;
Ok(time_zone_id.with_offset(offset).at_time((date, time)))
}

Expand All @@ -338,12 +330,7 @@ impl<'a> Intermediate<'a> {
};
let time_zone_id = mapper.iana_bytes_to_bcp47(iana_identifier);
let date = Date::try_new_iso(self.date.year, self.date.month, self.date.day)?;
let time = Time::try_new(
self.time.hour,
self.time.minute,
self.time.second,
self.time.nanosecond,
)?;
let time = Time::try_from_time_record(&self.time)?;
let offset = UtcOffset::try_from_utc_offset_record(offset)?;
Ok(time_zone_id
.with_offset(Some(offset))
Expand Down Expand Up @@ -723,13 +710,19 @@ impl Time {

fn try_from_ixdtf_record(ixdtf_record: &IxdtfParseRecord) -> Result<Self, ParseError> {
let time_record = ixdtf_record.time.ok_or(ParseError::MissingFields)?;
let time = Self::try_new(
Self::try_from_time_record(&time_record)
}

fn try_from_time_record(time_record: &TimeRecord) -> Result<Self, ParseError> {
let Some(nanosecond) = time_record.fraction.to_nanoseconds() else {
return Err(ParseError::ExcessivePrecision);
};
Ok(Self::try_new(
time_record.hour,
time_record.minute,
time_record.second,
time_record.nanosecond,
)?;
Ok(time)
nanosecond,
)?)
}
}

Expand Down
12 changes: 6 additions & 6 deletions utils/ixdtf/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions utils/ixdtf/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ pub enum ParseError {
DateDurationPartOrder,
#[displaydoc("Invalid time duration part order.")]
TimeDurationPartOrder,
#[displaydoc("Duration part fraction exceeded a representable range.")]
DurationFractionalDigitsExceededRange,
#[displaydoc("Invalid time duration designator.")]
TimeDurationDesignator,
}
Expand Down
12 changes: 6 additions & 6 deletions utils/ixdtf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
//!
//! ```
//! use ixdtf::parsers::{
//! records::{Sign, TimeZoneRecord},
//! records::{Sign, TimeZoneRecord, Fraction},
//! IxdtfParser,
//! };
//!
Expand All @@ -42,7 +42,7 @@
//! assert_eq!(offset.hour, 5);
//! assert_eq!(offset.minute, 0);
//! assert_eq!(offset.second, 0);
//! assert_eq!(offset.nanosecond, 0);
//! assert_eq!(offset.fraction, Fraction { digits: 0, value: 0});
//! assert!(!tz_annotation.critical);
//! assert_eq!(
//! tz_annotation.tz,
Expand Down Expand Up @@ -74,7 +74,7 @@
//!
//! ```rust
//! use ixdtf::parsers::{
//! records::{Sign, TimeZoneRecord},
//! records::{Sign, TimeZoneRecord, Fraction},
//! IxdtfParser,
//! };
//!
Expand All @@ -96,7 +96,7 @@
//! assert_eq!(offset.hour, 0);
//! assert_eq!(offset.minute, 0);
//! assert_eq!(offset.second, 0);
//! assert_eq!(offset.nanosecond, 0);
//! assert_eq!(offset.fraction, Fraction { digits: 0, value: 0});
//! assert!(!tz_annotation.critical);
//! assert_eq!(
//! tz_annotation.tz,
Expand Down Expand Up @@ -135,7 +135,7 @@
//!
//! ```rust
//! use ixdtf::parsers::{
//! records::{Sign, TimeZoneRecord},
//! records::{Sign, TimeZoneRecord, Fraction},
//! IxdtfParser,
//! };
//!
Expand All @@ -152,7 +152,7 @@
//! assert_eq!(offset.hour, 0);
//! assert_eq!(offset.minute, 0);
//! assert_eq!(offset.second, 0);
//! assert_eq!(offset.nanosecond, 0);
//! assert_eq!(offset.fraction, Fraction { digits: 0, value: 0});
//! assert!(tz_annotation.critical);
//! assert_eq!(
//! tz_annotation.tz,
Expand Down
29 changes: 24 additions & 5 deletions utils/ixdtf/src/parsers/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
is_month_designator, is_second_designator, is_sign, is_time_designator,
is_week_designator, is_year_designator,
},
records::{DateDurationRecord, DurationParseRecord, TimeDurationRecord},
records::{DateDurationRecord, DurationParseRecord, Fraction, TimeDurationRecord},
time::parse_fraction,
Cursor,
},
Expand Down Expand Up @@ -134,7 +134,7 @@ pub(crate) fn parse_time_duration(cursor: &mut Cursor) -> ParserResult<Option<Ti
TimeDurationDesignator,
);

let mut time: (u64, u64, u64, Option<u32>) = (0, 0, 0, None);
let mut time: (u64, u64, u64, Option<Fraction>) = (0, 0, 0, None);
let mut previous_unit = TimeUnit::None;
while cursor.check_or(false, |c| c.is_ascii_digit()) {
let mut value: u64 = 0;
Expand Down Expand Up @@ -194,20 +194,39 @@ pub(crate) fn parse_time_duration(cursor: &mut Cursor) -> ParserResult<Option<Ti
// Safety: Max fraction * 3600 is within u64 -> see test maximum_duration_fraction
TimeUnit::Hour => Ok(Some(TimeDurationRecord::Hours {
hours: time.0,
fraction: time.3.map(|f| 3600 * u64::from(f)).unwrap_or(0),
fraction: time
.3
.map(|f| adjust_fraction_for_unit(f, 3600))
.transpose()?
.unwrap_or_default(),
})),
// Safety: Max fraction * 60 is within u64 -> see test maximum_duration_fraction
TimeUnit::Minute => Ok(Some(TimeDurationRecord::Minutes {
hours: time.0,
minutes: time.1,
fraction: time.3.map(|f| 60 * u64::from(f)).unwrap_or(0),
fraction: time
.3
.map(|f| adjust_fraction_for_unit(f, 60))
.transpose()?
.unwrap_or_default(),
})),
TimeUnit::Second => Ok(Some(TimeDurationRecord::Seconds {
hours: time.0,
minutes: time.1,
seconds: time.2,
fraction: time.3.unwrap_or(0),
fraction: time.3.unwrap_or_default(),
})),
TimeUnit::None => Err(ParseError::abrupt_end("TimeDurationDesignator")),
}
}

fn adjust_fraction_for_unit(fraction: Fraction, unit: u64) -> ParserResult<Fraction> {
let value = fraction
.value
.checked_mul(unit)
.ok_or(ParseError::DurationFractionalDigitsExceededRange)?;
Ok(Fraction {
digits: fraction.digits,
value,
})
}
22 changes: 11 additions & 11 deletions utils/ixdtf/src/parsers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ impl<'a> IxdtfParser<'a> {
/// # Example
///
/// ```rust
/// use ixdtf::parsers::{IsoDurationParser, records::{Sign, DurationParseRecord, TimeDurationRecord}};
/// use ixdtf::parsers::{IsoDurationParser, records::{Sign, DurationParseRecord, Fraction, TimeDurationRecord}};
///
/// let duration_str = "P1Y2M1DT2H10M30S";
///
Expand All @@ -245,13 +245,13 @@ impl<'a> IxdtfParser<'a> {
/// let date_duration = result.date.unwrap();
///
/// let (hours, minutes, seconds, fraction) = match result.time {
/// // Hours variant is defined as { hours: u32, fraction: u64 }
/// // Hours variant is defined as { hours: u32, fraction: Fraction }
/// Some(TimeDurationRecord::Hours{ hours, fraction }) => (hours, 0, 0, fraction),
/// // Minutes variant is defined as { hours: u32, minutes: u32, fraction: u64 }
/// // Minutes variant is defined as { hours: u32, minutes: u32, fraction: Fraction }
/// Some(TimeDurationRecord::Minutes{ hours, minutes, fraction }) => (hours, minutes, 0, fraction),
/// // Seconds variant is defined as { hours: u32, minutes: u32, seconds: u32, fraction: u32 }
/// Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction as u64),
/// None => (0,0,0,0),
/// // Seconds variant is defined as { hours: u32, minutes: u32, seconds: u32, fraction: Fraction }
/// Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction),
/// None => (0,0,0, Fraction::default()),
/// };
///
/// assert_eq!(result.sign, Sign::Positive);
Expand All @@ -262,7 +262,7 @@ impl<'a> IxdtfParser<'a> {
/// assert_eq!(hours, 2);
/// assert_eq!(minutes, 10);
/// assert_eq!(seconds, 30);
/// assert_eq!(fraction, 0);
/// assert_eq!(fraction, Fraction { digits: 0, value: 0 });
/// ```
#[cfg(feature = "duration")]
#[derive(Debug)]
Expand Down Expand Up @@ -313,7 +313,7 @@ impl<'a> IsoDurationParser<'a> {
/// ## Parsing a time duration
///
/// ```rust
/// # use ixdtf::parsers::{IsoDurationParser, records::{DurationParseRecord, TimeDurationRecord }};
/// # use ixdtf::parsers::{IsoDurationParser, records::{DurationParseRecord, Fraction, TimeDurationRecord }};
/// let time_duration = "PT2H10M30S";
///
/// let result = IsoDurationParser::from_str(time_duration).parse().unwrap();
Expand All @@ -324,14 +324,14 @@ impl<'a> IsoDurationParser<'a> {
/// // Minutes variant is defined as { hours: u32, minutes: u32, fraction: u64 }
/// Some(TimeDurationRecord::Minutes{ hours, minutes, fraction }) => (hours, minutes, 0, fraction),
/// // Seconds variant is defined as { hours: u32, minutes: u32, seconds: u32, fraction: u32 }
/// Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction as u64),
/// None => (0,0,0,0),
/// Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction),
/// None => (0,0,0,Fraction::default()),
/// };
/// assert!(result.date.is_none());
/// assert_eq!(hours, 2);
/// assert_eq!(minutes, 10);
/// assert_eq!(seconds, 30);
/// assert_eq!(fraction, 0);
/// assert_eq!(fraction, Fraction { digits: 0, value: 0 });
/// ```
pub fn parse(&mut self) -> ParserResult<DurationParseRecord> {
duration::parse_duration(&mut self.cursor)
Expand Down
Loading
Loading