Skip to content

Commit

Permalink
Make with_year return Some if it is a no-op
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Feb 25, 2024
1 parent 72e7df3 commit f23dcba
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1099,12 +1099,15 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// # Errors
///
/// Returns `None` if:
/// - The resulting date does not exist.
/// - When the `NaiveDateTime` would be out of range.
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
/// - The resulting UTC datetime would be out of range.
/// - The resulting local datetime would be out of range (unless the year remains the same).
fn with_year(&self, year: i32) -> Option<DateTime<Tz>> {
map_local(self, |datetime| datetime.with_year(year))
map_local(self, |dt| match dt.year() == year {
true => Some(dt),
false => dt.with_year(year),
})
}

/// Makes a new `DateTime` with the month number (starting from 1) changed.
Expand Down
2 changes: 2 additions & 0 deletions src/datetime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,7 @@ fn test_min_max_setters() {
let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);

assert_eq!(beyond_min.with_year(2020).unwrap().year(), 2020);
assert_eq!(beyond_min.with_year(beyond_min.year()), Some(beyond_min));
assert_eq!(beyond_min.with_month(beyond_min.month()), Some(beyond_min));
assert_eq!(beyond_min.with_month(3), None);
assert_eq!(beyond_min.with_month0(beyond_min.month0()), Some(beyond_min));
Expand All @@ -1441,6 +1442,7 @@ fn test_min_max_setters() {
assert_eq!(beyond_min.with_nanosecond(0), Some(beyond_min));

assert_eq!(beyond_max.with_year(2020).unwrap().year(), 2020);
assert_eq!(beyond_max.with_year(beyond_max.year()), Some(beyond_max));
assert_eq!(beyond_max.with_month(beyond_max.month()), Some(beyond_max));
assert_eq!(beyond_max.with_month(3), None);
assert_eq!(beyond_max.with_month0(beyond_max.month0()), Some(beyond_max));
Expand Down

0 comments on commit f23dcba

Please sign in to comment.