[ledger] Core: haléře, dates, the event log and apply(), merchant keys and rules, one-to-one matching, import planning
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
//! Civil dates as days since 1970-01-01 (proleptic Gregorian), and timestamps the app hands in.
|
||||
//! There is no clock here: "today" is always a parameter.
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Date(i32);
|
||||
|
||||
/// Milliseconds since the Unix epoch, as given by the app.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Timestamp(pub i64);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("not a date (expected YYYY-MM-DD)")]
|
||||
pub struct DateError;
|
||||
|
||||
const MIN_YEAR: i32 = 1900;
|
||||
const MAX_YEAR: i32 = 2200;
|
||||
|
||||
pub fn is_leap(y: i32) -> bool {
|
||||
(y % 4 == 0 && y % 100 != 0) || y % 400 == 0
|
||||
}
|
||||
|
||||
pub fn days_in_month(y: i32, m: u32) -> u32 {
|
||||
match m {
|
||||
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
2 if is_leap(y) => 29,
|
||||
2 => 28,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
impl Date {
|
||||
/// `None` for an impossible date or a year outside 1900–2200.
|
||||
pub fn from_ymd(y: i32, m: u32, d: u32) -> Option<Date> {
|
||||
if !(MIN_YEAR..=MAX_YEAR).contains(&y) || !(1..=12).contains(&m) || d == 0 || d > days_in_month(y, m) {
|
||||
return None;
|
||||
}
|
||||
// Howard Hinnant's days_from_civil.
|
||||
let y = if m <= 2 { y - 1 } else { y };
|
||||
let era = y.div_euclid(400);
|
||||
let yoe = y - era * 400;
|
||||
let mp = (m as i32 + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + d as i32 - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
Some(Date(era * 146_097 + doe - 719_468))
|
||||
}
|
||||
|
||||
pub fn from_days(days: i32) -> Date {
|
||||
Date(days)
|
||||
}
|
||||
|
||||
pub fn days(self) -> i32 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn ymd(self) -> (i32, u32, u32) {
|
||||
let z = self.0 + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 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 }, m, d)
|
||||
}
|
||||
|
||||
pub fn add_days(self, n: i32) -> Date {
|
||||
Date(self.0 + n)
|
||||
}
|
||||
|
||||
/// Days from `self` to `other` (positive when `other` is later).
|
||||
pub fn days_until(self, other: Date) -> i32 {
|
||||
other.0 - self.0
|
||||
}
|
||||
|
||||
/// The same day `n` months later, clamped to the month's last day (31 Jan + 1 = 28/29 Feb).
|
||||
pub fn add_months(self, n: i32) -> Date {
|
||||
let (y, m, d) = self.ymd();
|
||||
let idx = y * 12 + (m as i32 - 1) + n;
|
||||
let (ny, nm) = (idx.div_euclid(12), (idx.rem_euclid(12) + 1) as u32);
|
||||
let nd = d.min(days_in_month(ny, nm));
|
||||
Date::from_ymd(ny, nm, nd).unwrap_or(self)
|
||||
}
|
||||
|
||||
pub fn add_years(self, n: i32) -> Date {
|
||||
self.add_months(n * 12)
|
||||
}
|
||||
|
||||
pub fn month_start(self) -> Date {
|
||||
let (y, m, _) = self.ymd();
|
||||
Date::from_ymd(y, m, 1).unwrap_or(self)
|
||||
}
|
||||
|
||||
pub fn month_end(self) -> Date {
|
||||
let (y, m, _) = self.ymd();
|
||||
Date::from_ymd(y, m, days_in_month(y, m)).unwrap_or(self)
|
||||
}
|
||||
|
||||
/// `(year, month)` — the key of a monthly budget period.
|
||||
pub fn month(self) -> (i32, u32) {
|
||||
let (y, m, _) = self.ymd();
|
||||
(y, m)
|
||||
}
|
||||
|
||||
/// The civil date of a timestamp in UTC. The app passes local "today" as a `Date`; this is for the log.
|
||||
pub fn from_timestamp_utc(t: Timestamp) -> Date {
|
||||
Date(t.0.div_euclid(86_400_000) as i32)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Date {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let (y, m, d) = self.ymd();
|
||||
write!(f, "{y:04}-{m:02}-{d:02}")
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Date {
|
||||
type Err = DateError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Date, DateError> {
|
||||
let b = s.as_bytes();
|
||||
if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
|
||||
return Err(DateError);
|
||||
}
|
||||
let num = |r: std::ops::Range<usize>| -> Result<u32, DateError> {
|
||||
let part = &s[r];
|
||||
if !part.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return Err(DateError);
|
||||
}
|
||||
part.parse().map_err(|_| DateError)
|
||||
};
|
||||
Date::from_ymd(num(0..4)? as i32, num(5..7)?, num(8..10)?).ok_or(DateError)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Date {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.collect_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Date {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Date, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
s.parse().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_day_for_three_centuries() {
|
||||
let start = Date::from_ymd(1900, 1, 1).unwrap();
|
||||
let end = Date::from_ymd(2200, 12, 31).unwrap();
|
||||
let mut day = start;
|
||||
while day <= end {
|
||||
let (y, m, d) = day.ymd();
|
||||
assert_eq!(Date::from_ymd(y, m, d), Some(day));
|
||||
assert_eq!(day.to_string().parse::<Date>(), Ok(day));
|
||||
day = day.add_days(1);
|
||||
}
|
||||
assert_eq!(Date::from_ymd(1970, 1, 1).unwrap().days(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn months_clamp() {
|
||||
let d = |s: &str| s.parse::<Date>().unwrap();
|
||||
assert_eq!(d("2026-01-31").add_months(1), d("2026-02-28"));
|
||||
assert_eq!(d("2028-01-31").add_months(1), d("2028-02-29"));
|
||||
assert_eq!(d("2026-12-15").add_months(1), d("2027-01-15"));
|
||||
assert_eq!(d("2026-03-31").add_months(-1), d("2026-02-28"));
|
||||
assert_eq!(d("2028-02-29").add_years(1), d("2029-02-28"));
|
||||
assert_eq!(d("2026-11-03").month_end(), d("2026-11-30"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_is_not_a_date() {
|
||||
for bad in ["2026-02-29", "2026-13-01", "2026-00-10", "26-01-01", "2026-1-01", "2026-01-01T", "+026-01-01", "1899-12-31"] {
|
||||
assert!(bad.parse::<Date>().is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user