|
|
@@ -0,0 +1,168 @@
|
|
|
+//! The [`ValueDate`]: the day an entry takes effect, as opposed to the instant
|
|
|
+//! it was committed.
|
|
|
+
|
|
|
+use std::fmt;
|
|
|
+
|
|
|
+use serde::{Deserialize, Serialize};
|
|
|
+
|
|
|
+/// The day an entry takes effect, held as days since 1970-01-01.
|
|
|
+///
|
|
|
+/// A calendar day rather than an instant, because a value date is a business
|
|
|
+/// fact that no timezone should be able to shift: an entry valued 20 November
|
|
|
+/// is valued 20 November wherever it is read.
|
|
|
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
|
|
+pub struct ValueDate(i64);
|
|
|
+
|
|
|
+/// Why a `(year, month, day)` is not a date.
|
|
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
+pub enum InvalidDate {
|
|
|
+ /// The month was outside 1 through 12.
|
|
|
+ Month(u32),
|
|
|
+ /// The day was outside 1 through the length of that month in that year.
|
|
|
+ Day(u32),
|
|
|
+}
|
|
|
+
|
|
|
+impl fmt::Display for InvalidDate {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ match self {
|
|
|
+ Self::Month(m) => write!(f, "month {m} is not in 1..=12"),
|
|
|
+ Self::Day(d) => write!(f, "day {d} is not a day of that month"),
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl std::error::Error for InvalidDate {}
|
|
|
+
|
|
|
+const DAYS_IN_MONTH: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
|
+
|
|
|
+fn is_leap(year: i32) -> bool {
|
|
|
+ (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
|
|
|
+}
|
|
|
+
|
|
|
+fn days_in_month(year: i32, month: u32) -> u32 {
|
|
|
+ if month == 2 && is_leap(year) {
|
|
|
+ 29
|
|
|
+ } else {
|
|
|
+ DAYS_IN_MONTH[(month - 1) as usize]
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl ValueDate {
|
|
|
+ /// Build a value date from a calendar date, rejecting one that does not
|
|
|
+ /// exist.
|
|
|
+ pub fn new(year: i32, month: u32, day: u32) -> Result<Self, InvalidDate> {
|
|
|
+ if !(1..=12).contains(&month) {
|
|
|
+ return Err(InvalidDate::Month(month));
|
|
|
+ }
|
|
|
+ if day < 1 || day > days_in_month(year, month) {
|
|
|
+ return Err(InvalidDate::Day(day));
|
|
|
+ }
|
|
|
+ Ok(Self(days_from_civil(year, month, day)))
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Days since 1970-01-01, negative before it. The storage form, and what
|
|
|
+ /// orders and compares two value dates.
|
|
|
+ pub const fn days(&self) -> i64 {
|
|
|
+ self.0
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Rebuild from the stored day count.
|
|
|
+ pub const fn from_days(days: i64) -> Self {
|
|
|
+ Self(days)
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The calendar date, as `(year, month, day)`.
|
|
|
+ pub fn civil(&self) -> (i32, u32, u32) {
|
|
|
+ civil_from_days(self.0)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl fmt::Display for ValueDate {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ let (y, m, d) = self.civil();
|
|
|
+ write!(f, "{y:04}-{m:02}-{d:02}")
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl fmt::Debug for ValueDate {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ write!(f, "ValueDate({self})")
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Days from 1970-01-01 to a calendar date, by Howard Hinnant's `days_from_civil`.
|
|
|
+/// Shifting the era to start in March puts the leap day last, so the month-length
|
|
|
+/// pattern repeats and needs no table.
|
|
|
+fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
|
|
|
+ let y = if month <= 2 { year - 1 } else { year };
|
|
|
+ let era = if y >= 0 { y } else { y - 399 } / 400;
|
|
|
+ let yoe = (y - era * 400) as i64;
|
|
|
+ let mp = if month > 2 { month - 3 } else { month + 9 } as i64;
|
|
|
+ let doy = (153 * mp + 2) / 5 + day as i64 - 1;
|
|
|
+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
|
|
+ era as i64 * 146097 + doe - 719468
|
|
|
+}
|
|
|
+
|
|
|
+/// The inverse of [`days_from_civil`].
|
|
|
+fn civil_from_days(days: i64) -> (i32, u32, u32) {
|
|
|
+ let z = days + 719468;
|
|
|
+ let era = if z >= 0 { z } else { z - 146096 } / 146097;
|
|
|
+ let doe = z - era * 146097;
|
|
|
+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
|
|
+ let y = yoe + era * 400;
|
|
|
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
|
|
+ let mp = (5 * doy + 2) / 153;
|
|
|
+ let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
|
|
+ let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
|
|
+ ((if m <= 2 { y + 1 } else { y }) as i32, m, d)
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn round_trips_through_days() {
|
|
|
+ for (y, m, d) in [
|
|
|
+ (1970, 1, 1),
|
|
|
+ (2026, 11, 20),
|
|
|
+ (2024, 2, 29),
|
|
|
+ (1999, 12, 31),
|
|
|
+ (1900, 3, 1),
|
|
|
+ (2400, 2, 29),
|
|
|
+ ] {
|
|
|
+ let date = ValueDate::new(y, m, d).unwrap();
|
|
|
+ assert_eq!(date.civil(), (y, m, d), "{y}-{m}-{d}");
|
|
|
+ assert_eq!(ValueDate::from_days(date.days()), date);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn epoch_is_day_zero_and_dates_order_by_day() {
|
|
|
+ assert_eq!(ValueDate::new(1970, 1, 1).unwrap().days(), 0);
|
|
|
+ assert_eq!(ValueDate::new(1969, 12, 31).unwrap().days(), -1);
|
|
|
+ assert!(ValueDate::new(2026, 11, 20).unwrap() < ValueDate::new(2026, 11, 21).unwrap());
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn rejects_dates_that_do_not_exist() {
|
|
|
+ assert_eq!(ValueDate::new(2026, 13, 1), Err(InvalidDate::Month(13)));
|
|
|
+ assert_eq!(ValueDate::new(2026, 0, 1), Err(InvalidDate::Month(0)));
|
|
|
+ assert_eq!(ValueDate::new(2026, 2, 29), Err(InvalidDate::Day(29)));
|
|
|
+ assert_eq!(ValueDate::new(2026, 4, 31), Err(InvalidDate::Day(31)));
|
|
|
+ assert_eq!(ValueDate::new(2026, 1, 0), Err(InvalidDate::Day(0)));
|
|
|
+ assert!(ValueDate::new(2024, 2, 29).is_ok(), "2024 is a leap year");
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn displays_as_iso() {
|
|
|
+ assert_eq!(
|
|
|
+ ValueDate::new(2026, 11, 20).unwrap().to_string(),
|
|
|
+ "2026-11-20"
|
|
|
+ );
|
|
|
+ assert_eq!(
|
|
|
+ ValueDate::new(1970, 1, 1).unwrap().to_string(),
|
|
|
+ "1970-01-01"
|
|
|
+ );
|
|
|
+ }
|
|
|
+}
|