Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
169 changes: 149 additions & 20 deletions src/items/builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use jiff::{civil, Span, ToSpan, Zoned};
use jiff::{civil, Span, Zoned};

use super::{date, epoch, error, offset, relative, time, weekday, year, Item};
use crate::extended::{DateParts, TimeParts};
Expand Down Expand Up @@ -359,25 +359,15 @@ impl DateTimeBuilder {
dt = dt.datetime().to_zoned((&offset).try_into()?)?;
}

// 4e. Apply relative adjustments.
for rel in self.relative {
dt = match rel {
relative::Relative::Years(_) | relative::Relative::Months(_) => {
// GNU way of calculating relative months and years.
// GNU changes the month/year and then checks if the target month has
// this day. If this day does not exist in the target month it overflows
// the difference.
let original_day_of_month = dt.day();
dt = dt.checked_add::<Span>(rel.try_into()?)?;
if original_day_of_month != dt.day() {
dt = dt.checked_add(
(original_day_of_month.checked_sub(dt.day()).unwrap_or(0)).days(),
)?;
}
dt
}
_ => dt.checked_add::<Span>(rel.try_into()?)?,
};
// Apply relative date adjustments first, then relative time
// adjustments. GNU groups all year/month fields before normalizing
// the day, rather than applying each relative item in input order.
let relative = relative_adjustment(&self.relative)?;
if relative.has_date_component() {
dt = apply_relative_date(dt, relative)?;
}
if relative.has_time_component() {
dt = apply_relative_time(dt, relative)?;
}

Ok(dt)
Expand Down Expand Up @@ -550,6 +540,145 @@ fn weekday_monday0(day: weekday::Day) -> u8 {
}
}

/// Relative values are accumulated by unit before they are applied. GNU
/// applies all year/month changes together, followed by days and then the
/// clock units, rather than applying the input items one at a time.
#[derive(Clone, Copy, Debug, Default)]
struct RelativeAdjustment {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

the comment here and the one at the call site say the same thing, please keep only one

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ok

years: i64,
months: i64,
days: i64,
hours: i64,
minutes: i64,
seconds: i64,
nanoseconds: i64,
}

impl RelativeAdjustment {
fn has_date_component(self) -> bool {
self.years != 0 || self.months != 0 || self.days != 0
}

fn has_time_component(self) -> bool {
self.hours != 0 || self.minutes != 0 || self.seconds != 0 || self.nanoseconds != 0
}
}

fn relative_adjustment(
relative: &[relative::Relative],
) -> Result<RelativeAdjustment, error::Error> {
let mut result = RelativeAdjustment::default();
for rel in relative {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

almost the same checked_add block 6 times, could be dedup, no?
a small helper or closure taking the field and the error string would do

match *rel {
relative::Relative::Years(value) => {
result.years = result
.years
.checked_add(i64::from(value))
.ok_or("relative year adjustment overflow")?;
}
relative::Relative::Months(value) => {
result.months = result
.months
.checked_add(i64::from(value))
.ok_or("relative month adjustment overflow")?;
}
relative::Relative::Days(value) => {
result.days = result
.days
.checked_add(i64::from(value))
.ok_or("relative day adjustment overflow")?;
}
relative::Relative::Hours(value) => {
result.hours = result
.hours
.checked_add(i64::from(value))
.ok_or("relative hour adjustment overflow")?;
}
relative::Relative::Minutes(value) => {
result.minutes = result
.minutes
.checked_add(i64::from(value))
.ok_or("relative minute adjustment overflow")?;
}
relative::Relative::Seconds(seconds, nanoseconds) => {
result.seconds = result
.seconds
.checked_add(seconds)
.ok_or("relative second adjustment overflow")?;
result.nanoseconds = result
.nanoseconds
.checked_add(i64::from(nanoseconds))
.ok_or("relative nanosecond adjustment overflow")?;
}
}
}
Ok(result)
}

fn apply_relative_date(mut dt: Zoned, relative: RelativeAdjustment) -> Result<Zoned, error::Error> {
// Change the year and month as one calendar operation. This intentionally
// preserves the original day until the target month is known, so a date
// such as January 31 overflows into March rather than clamping to February.
if relative.years != 0 || relative.months != 0 {
let (year, month) = shifted_year_month(&dt, relative)?;
let first = civil::Date::new(year, month as i8, 1)?;
let target = first.checked_add(Span::new().try_days(i64::from(dt.day() - 1))?)?;
dt = dt.with().date(target).build()?;
}
if relative.days != 0 {
dt = dt.checked_add(Span::new().try_days(relative.days)?)?;
}
Ok(dt)
}

fn shifted_year_month(dt: &Zoned, relative: RelativeAdjustment) -> Result<(i16, u8), error::Error> {
let month_index = i64::from(dt.year())
.checked_mul(12)
.and_then(|value| value.checked_add(i64::from(dt.month()) - 1))
.and_then(|value| value.checked_add(relative.years.checked_mul(12)?))
.and_then(|value| value.checked_add(relative.months))
.ok_or("relative month/year overflow")?;
let year = month_index.div_euclid(12);
let month = month_index.rem_euclid(12) + 1;
let year = i16::try_from(year).map_err(|_| "relative year overflow")?;
Ok((year, month as u8))
}

fn apply_relative_time(dt: Zoned, relative: RelativeAdjustment) -> Result<Zoned, error::Error> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could we use jiff::SignedDuration here?
SignedDuration::new(secs, nanos) already normalizes mixed signs, so most of this function and the manual sign fix would go away

let seconds = relative
.hours
.checked_mul(3_600)
.and_then(|hours| {
relative
.minutes
.checked_mul(60)
.and_then(|minutes| hours.checked_add(minutes))
})
.and_then(|seconds| seconds.checked_add(relative.seconds))
.ok_or("relative time overflow")?;
let extra_seconds = relative.nanoseconds.div_euclid(1_000_000_000);
let nanoseconds = relative.nanoseconds.rem_euclid(1_000_000_000);
let seconds = seconds
.checked_add(extra_seconds)
.ok_or("relative time overflow")?;

// Relative::Seconds stores negative fractional values in timestamp form,
// e.g. (-1, 500_000_000) for -0.5 seconds. Jiff spans require the seconds
// and nanoseconds components to have the same sign, so normalize them.
let (seconds, nanoseconds) = if seconds < 0 && nanoseconds > 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this duplicates the normalization in the TryFrom<Relative> for Span of relative.rs
which now seems unused, could you please remove it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will check

(
seconds.checked_add(1).ok_or("relative time overflow")?,
-(1_000_000_000 - nanoseconds),
)
} else {
(seconds, nanoseconds)
};
let span = Span::new()
.try_seconds(seconds)?
.try_nanoseconds(nanoseconds)?;
Ok(dt.checked_add(span)?)
}

impl TryFrom<Vec<Item>> for DateTimeBuilder {
type Error = &'static str;

Expand Down
14 changes: 8 additions & 6 deletions tests/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,29 +201,31 @@ fn test_negative_month_operations(#[case] base: &str, #[case] input: &str, #[cas
// Test chained operations (multiple relative adjustments in one parse)
// These ensure that year and month overflow logic works correctly when combined
#[rstest]
// Feb 29, 2020 + 1 year = March 1, 2021; + 1 month = April 1, 2021
// GNU groups relative years and months before normalizing: 2020-02-29 plus
// one year and one month produces 2021-03-29.
#[case::feb29_plus_year_plus_month(
"2020-02-29 00:00:00",
"1 year 1 month",
"2021-04-01 00:00:00+00:00"
"2021-03-29 00:00:00+00:00"
)]
// Jan 31, 2024 + 1 month = March 2, 2024; + 1 year = March 2, 2025
// GNU groups the month and year fields before normalizing the overflowing
// February 31 date.
#[case::jan31_plus_month_plus_year(
"2024-01-31 00:00:00",
"1 month 1 year",
"2025-03-02 00:00:00+00:00"
"2025-03-03 00:00:00+00:00"
)]
// Jan 31 + 2 months + 1 day
#[case::jan31_plus_2months_1day(
"2024-01-31 00:00:00",
"2 months 1 day",
"2024-04-01 00:00:00+00:00"
)]
// Feb 29 - 1 year + 1 month (March 1, 2019 + 1 month = April 1, 2019)
// GNU groups the relative year and month fields before normalization.
#[case::feb29_minus_year_plus_month(
"2020-02-29 00:00:00",
"1 year ago 1 month",
"2019-04-01 00:00:00+00:00"
"2019-03-29 00:00:00+00:00"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please add a test with the same unit twice, e.g. "1 month 1 month" from 2024-01-31
and one with the time unit before the date one, e.g. "4 hours 1 month"

)]
// Multiple operations with days
#[case::complex_chain(
Expand Down
Loading