Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Use chrono instead of hand-rolled UTC conversion (#1479)

Dylan M. Taylor3b985e3813c1
diff --git a/AGENTS.md b/AGENTS.md
index 65693656c..0be7fa87b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,6 +26,7 @@ People trust DesignCraft with their layouts; a crash loses their work. **This ou
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. The UI crate is swappable.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
+- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math). A crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: type tool caret navigation`).
diff --git a/Cargo.lock b/Cargo.lock
index ffca2b064..1180cf0b1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -683,6 +683,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -936,6 +945,7 @@ name = "designcraft"
version = "0.11.0"
dependencies = [
"arboard",
+ "chrono",
"designcraft-engine",
"designcraft-ui-egui",
"eframe",
@@ -1005,6 +1015,7 @@ dependencies = [
name = "designcraft-doc"
version = "0.11.0"
dependencies = [
+ "chrono",
"designcraft-color",
"designcraft-geom",
"proptest",
@@ -1056,6 +1067,7 @@ dependencies = [
name = "designcraft-epub"
version = "0.11.0"
dependencies = [
+ "chrono",
"designcraft-color",
"designcraft-doc",
"zip",
@@ -1146,6 +1158,7 @@ dependencies = [
name = "designcraft-pdf"
version = "0.11.0"
dependencies = [
+ "chrono",
"craft-pdf",
"designcraft-color",
"designcraft-compose",
@@ -1168,6 +1181,7 @@ dependencies = [
name = "designcraft-pptx"
version = "0.11.0"
dependencies = [
+ "chrono",
"designcraft-color",
"designcraft-compose",
"designcraft-doc",
diff --git a/Cargo.toml b/Cargo.toml
index a19abf1a9..0e728e87f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,8 @@ thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
+# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
+chrono = { version = "0.4.45", default-features = false, features = ["std"] }
proptest = "1"
rayon = "1"
unicode-bidi = "0.3"
diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml
index 7dc83bc55..81a267aa9 100644
--- a/apps/designcraft/Cargo.toml
+++ b/apps/designcraft/Cargo.toml
@@ -18,6 +18,7 @@ egui = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+chrono = { workspace = true }
[build-dependencies]
# Icon + VERSIONINFO for designcraft.exe; build.rs only uses it when the target is Windows.
diff --git a/apps/designcraft/src/logging.rs b/apps/designcraft/src/logging.rs
index d3e0dbea7..5fe70a749 100644
--- a/apps/designcraft/src/logging.rs
+++ b/apps/designcraft/src/logging.rs
@@ -90,27 +90,36 @@ fn matches(name: &str, target: &str) -> bool {
}
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
+/// A clock far past chrono's year range still converts (the calendar repeats every 400 years), so
+/// logging never panics and never silently resets to the epoch for a convertible instant.
pub fn timestamp(t: SystemTime) -> String {
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
- let secs = since.as_secs();
- let (days, rem) = (secs / 86_400, secs % 86_400);
- let (y, m, d) = civil_from_days(days);
- format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
+ // Pre-1970 is clamped to the epoch by `unwrap_or_default` above. `as_secs` is `u64`; a value
+ // past `i64::MAX` seconds saturates rather than falling back to the epoch.
+ let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX);
+ let (y, t) = utc_parts(secs, since.subsec_nanos());
+ // `{:04}` rather than `%Y`, which writes a `+` before years past 9999.
+ format!("{y:04}-{}", t.format("%m-%dT%H:%M:%S%.3fZ"))
}
-/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
-/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch).
-fn civil_from_days(days: u64) -> (u64, u64, u64) {
- let z = days + 719_468;
- let era = z / 146_097;
- let doe = z % 146_097;
- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
- let mp = (5 * doy + 2) / 153;
- let d = doy - (153 * mp + 2) / 5 + 1;
- let m = if mp < 10 { mp + 3 } else { mp - 9 };
- let y = yoe + era * 400 + u64::from(m <= 2);
- (y, m, d)
+/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into
+/// chrono's range by whole 400-year cycles). The calendar repeats every 400 years (146_097 days),
+/// so month, day and time of day come from chrono and only the year is carried, which keeps every
+/// `i64` exact. Replaces the old hand-rolled `civil_from_days`; chrono is the only calendar logic.
+fn utc_parts(secs: i64, nanos: u32) -> (i64, chrono::NaiveDateTime) {
+ use chrono::Datelike;
+ let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
+ let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
+ // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
+ let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
+ let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999)));
+ match (date, time) {
+ (Some(d), Some(t)) => {
+ let y = i128::from(d.year()) + i128::from(cycles) * 400;
+ (i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.and_time(t))
+ }
+ _ => (1970, chrono::NaiveDateTime::default()), // unreachable
+ }
}
fn numbered(dir: &Path, n: usize) -> PathBuf {
@@ -317,6 +326,20 @@ mod tests {
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_704_067_199_999)), "2023-12-31T23:59:59.999Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
+ // Past chrono's year range still converts via the 400-year cycle (the old code did too,
+ // through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
+ // SystemTime can't hold this instant, so it is only checked where it exists.
+ // `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
+ if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
+ assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
+ }
+ // Years past 9999 keep the plain zero-padded year (no `+`).
+ assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
+ // 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
+ // Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
+ if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
+ assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
+ }
}
#[test]
diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml
index ed7430db7..1d3da4062 100644
--- a/crates/doc/Cargo.toml
+++ b/crates/doc/Cargo.toml
@@ -14,6 +14,7 @@ designcraft-color = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+chrono = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
diff --git a/crates/doc/src/vars.rs b/crates/doc/src/vars.rs
index 1ea4f8ced..0a3f5ea46 100644
--- a/crates/doc/src/vars.rs
+++ b/crates/doc/src/vars.rs
@@ -126,28 +126,46 @@ pub fn now() -> i64 {
}
}
-/// (year, month 1–12, day 1–31) from days since 1970-01-01 (H. Hinnant's public-domain algorithm).
+/// (year, month 1–12, day 1–31) from days since 1970-01-01.
+///
+/// `NaiveDate` only covers about ±262143 years, but the system clock can run past it, so this
+/// stays exact for every `days`. The Gregorian calendar repeats every 400 years (146_097 days):
+/// chrono converts the day within its cycle and whole cycles go back into the year (an i128 so no
+/// `days` overflows), which matches the proleptic Gregorian answer the old hand-rolled code gave.
+/// 1970-01-01 is `num_days_from_ce` 719_163.
fn civil(days: i64) -> (i64, u32, u32) {
- let z = days + 719_468;
- let era = z.div_euclid(146_097);
- let doe = z.rem_euclid(146_097);
- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
- 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;
- (yoe + era * 400 + i64::from(m <= 2), m, d)
+ use chrono::Datelike;
+ let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
+ match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
+ Some(d) => {
+ let y = i128::from(d.year()) + i128::from(cycles) * 400;
+ (i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.month(), d.day())
+ }
+ // Unreachable: `rest + 719_163` is always a valid CE day.
+ None => (1970, 1, 1),
+ }
}
-/// Days since 1970-01-01 of a civil date (inverse of [`civil`]).
+/// Days since 1970-01-01 of a civil date (inverse of [`civil`]), exact for any year.
+///
+/// The Gregorian calendar repeats every 400 years (146_097 days): chrono converts the year within
+/// its cycle and whole cycles are added back as days (an i128 so the extremes can't overflow),
+/// which matches the proleptic Gregorian count the old hand-rolled code gave. 1970-01-01 is
+/// `num_days_from_ce` 719_163.
+///
+/// A day past the end of its month carries into the next one, as before chrono (`2019-02-30`
+/// is 2019-03-02: `parse_iso_date` accepts any day 1..=31): chrono places the 1st of the month
+/// and the rest of the days are added on. Only a month outside 1..=12 reads as 0.
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
- let y = if m <= 2 { y - 1 } else { y };
- let era = y.div_euclid(400);
- let yoe = y.rem_euclid(400);
- let mp = i64::from(if m > 2 { m - 3 } else { m + 9 });
- let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
- era * 146_097 + doe - 719_468
+ let (cycles, year) = (i128::from(y.div_euclid(400)), y.rem_euclid(400));
+ i32::try_from(year)
+ .ok()
+ .and_then(|year| chrono::NaiveDate::from_ymd_opt(year, m, 1))
+ .and_then(|first| {
+ let days = i128::from(chrono::Datelike::num_days_from_ce(&first)) - 719_163 + cycles * 146_097 + i128::from(d) - 1;
+ i64::try_from(days).ok()
+ })
+ .unwrap_or(0)
}
/// Unix seconds of an ISO 8601 timestamp such as `2019-12-16T09:48:02+01:00` (seconds, the
@@ -294,6 +312,30 @@ mod tests {
assert_eq!(format_date(951_782_400, "yyyy-MM-dd"), "2000-02-29");
}
+ #[test]
+ fn dates_beyond_chrono_range() {
+ // Past `NaiveDate`'s ±262143 the 400-year cycles carry the year; the clock can reach this,
+ // so keep the proleptic Gregorian date the old formula gave rather than the epoch, on both
+ // sides of the epoch. Values from the pre-chrono formula, through the public `format_date`.
+ assert_eq!(format_date(10_000_000_000_000, "yyyy-MM-dd HH:mm"), "318857-05-20 17:46");
+ assert_eq!(format_date(-8_334_659_289_600, "yyyy-MM-dd"), "-262145-03-01");
+ // `days_from_civil` is exact and inverts `civil` past the range, both sides.
+ for (y, m, d, days) in
+ [(262_144i64, 1u32, 1u32, 95_026_602i64), (300_000, 6, 15, 108_853_388), (-262_145, 3, 1, -96_465_964), (-300_000, 2, 29, -110_292_219)]
+ {
+ assert_eq!(days_from_civil(y, m, d), days, "{y}-{m}-{d}");
+ assert_eq!(civil(days), (y, m, d), "{days}");
+ }
+ // The extremes must not overflow or panic (i128 intermediates).
+ let _ = (civil(i64::MAX), civil(i64::MIN), days_from_civil(i64::MAX, 12, 31), days_from_civil(i64::MIN, 1, 1));
+ // A day past the end of its month carries over, as before chrono, instead of reading as 1970.
+ assert_eq!(days_from_civil(2019, 2, 30), days_from_civil(2019, 3, 2));
+ assert_eq!(days_from_civil(2024, 2, 30), days_from_civil(2024, 3, 1));
+ assert_eq!(days_from_civil(2019, 4, 31), days_from_civil(2019, 5, 1));
+ assert_eq!(parse_iso_date("2019-02-30"), Some(1_551_484_800));
+ assert_eq!(parse_iso_date("2019-02-30T09:48:02Z"), parse_iso_date("2019-03-02T09:48:02Z"));
+ }
+
#[test]
fn iso_dates() {
assert_eq!(parse_iso_date("2026-10-01T14:05:00Z"), Some(1_790_863_500));
diff --git a/crates/epub/Cargo.toml b/crates/epub/Cargo.toml
index 0cbe1673c..2836b0a92 100644
--- a/crates/epub/Cargo.toml
+++ b/crates/epub/Cargo.toml
@@ -12,3 +12,4 @@ workspace = true
designcraft-doc = { workspace = true }
designcraft-color = { workspace = true }
zip = { workspace = true }
+chrono = { workspace = true }
diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs
index 84bf56f1e..bd4571501 100644
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@ -123,19 +123,32 @@ fn font_file(k: usize, f: &EmbeddedFont) -> (String, &'static str) {
}
/// An ISO 8601 UTC timestamp (`2026-10-13T09:30:00Z`) for Unix seconds `t`.
+/// A time outside chrono's year range still converts: the calendar repeats every 400 years, so the
+/// instant is moved into range by whole cycles and only the year is carried (matches the old
+/// `civil_from_days`), rather than resetting to the epoch.
fn iso8601(t: i64) -> String {
- let (days, secs) = (t.div_euclid(86_400), t.rem_euclid(86_400));
- // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
- let z = days + 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 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
- let mp = (5 * doy + 2) / 153;
- let day = doy - (153 * mp + 2) / 5 + 1;
- let month = if mp < 10 { mp + 3 } else { mp - 9 };
- let year = yoe + era * 400 + i64::from(month <= 2);
- format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs % 3600 / 60, secs % 60)
+ let (y, dt) = utc_parts(t, 0);
+ // `{:04}` rather than `%Y`, which writes a `+` before years past 9999.
+ format!("{y:04}-{}", dt.format("%m-%dT%H:%M:%SZ"))
+}
+
+/// Unix seconds (+ nanos) → (proleptic Gregorian year, the instant moved into chrono's range by
+/// whole 400-year cycles). Month, day and time of day come from chrono; only the year is carried,
+/// which keeps every `i64` exact. chrono is the only calendar logic.
+fn utc_parts(secs: i64, nanos: u32) -> (i64, chrono::NaiveDateTime) {
+ use chrono::Datelike;
+ let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
+ let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
+ // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
+ let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
+ let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999)));
+ match (date, time) {
+ (Some(d), Some(t)) => {
+ let y = i128::from(d.year()) + i128::from(cycles) * 400;
+ (i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.and_time(t))
+ }
+ _ => (1970, chrono::NaiveDateTime::default()), // unreachable
+ }
}
/// The package's `dcterms:modified`: the given time, else the document's last save or creation.
@@ -1582,6 +1595,14 @@ mod tests {
(951_782_400, "2000-02-29T00:00:00Z"),
(1_791_891_000, "2026-10-13T11:30:00Z"),
(-86_400, "1969-12-31T00:00:00Z"),
+ // Years past 9999 keep the plain zero-padded year (no `+`).
+ (253_402_300_800, "10000-01-01T00:00:00Z"),
+ // Beyond chrono's range the old `civil_from_days` still converted; pin that output
+ // (never the epoch) in both directions and at the `i64` extremes.
+ (10_000_000_000_000, "318857-05-20T17:46:40Z"),
+ (-10_000_000_000_000, "-314918-08-13T06:13:20Z"),
+ (i64::MAX, "292277026596-12-04T15:30:07Z"),
+ (i64::MIN, "-292277022657-01-27T08:29:52Z"),
] {
assert_eq!(iso8601(t), want);
}
diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml
index 6f40462b7..09da578ee 100644
--- a/crates/pdf/Cargo.toml
+++ b/crates/pdf/Cargo.toml
@@ -20,6 +20,7 @@ designcraft-images = { workspace = true }
image = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
+chrono = { workspace = true }
# The placed-PDF version check names hayro's PdfVersion (krilla::pdf::Pdf::version returns it).
hayro-syntax = "0.7.2"
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index 4e7627e9e..df44acbf2 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -436,20 +436,25 @@ fn date_time(t: i64) -> krilla::metadata::DateTime {
.utc_offset_minute(0)
}
-/// Unix seconds (UTC) → (year, month, day, hour, minute, second), proleptic Gregorian.
+/// Unix seconds (UTC) → (year, month, day, hour, minute, second), proleptic Gregorian. A time
+/// outside chrono's year range still converts (the calendar repeats every 400 years, so the
+/// instant is moved into range by whole cycles and only the year is carried, matching the old
+/// `civil`), rather than resetting to the epoch. `date_time` applies the PDF `0..=9999` year clamp.
pub(crate) fn civil(t: i64) -> (i64, u8, u8, u8, u8, u8) {
- let days = t.div_euclid(86_400);
- let secs = t.rem_euclid(86_400);
- let z = days + 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 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
- let mp = (5 * doy + 2) / 153;
- let day = doy - (153 * mp + 2) / 5 + 1;
- let month = if mp < 10 { mp + 3 } else { mp - 9 };
- let year = yoe + era * 400 + i64::from(month <= 2);
- (year, month as u8, day as u8, (secs / 3600) as u8, (secs / 60 % 60) as u8, (secs % 60) as u8)
+ use chrono::{Datelike, Timelike};
+ let (days, sod) = (t.div_euclid(86_400), t.rem_euclid(86_400));
+ let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
+ // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
+ let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
+ let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, 0));
+ match (date, time) {
+ (Some(d), Some(t)) => {
+ let y = i128::from(d.year()) + i128::from(cycles) * 400;
+ let y = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX });
+ (y, d.month() as u8, d.day() as u8, t.hour() as u8, t.minute() as u8, t.second() as u8)
+ }
+ _ => (1970, 1, 1, 0, 0, 0), // unreachable
+ }
}
/// A successful conversion and its name-independent diagnostic. Replayed once for each asset.
@@ -2117,4 +2122,19 @@ mod eps_tests {
assert_eq!(images, vec![("DeviceCMYK".to_string(), pixels.clone())], "{standard:?}");
}
}
+
+ #[test]
+ fn civil_dates_match_the_old_cycle_conversion_including_beyond_chrono() {
+ use super::civil;
+ assert_eq!(civil(0), (1970, 1, 1, 0, 0, 0));
+ assert_eq!(civil(951_782_400), (2000, 2, 29, 0, 0, 0));
+ assert_eq!(civil(1_791_504_000 + 3_723), (2026, 10, 9, 1, 2, 3));
+ // Beyond chrono's year range the old `civil` still converted; pin that output, never the
+ // epoch. `date_time` is what clamps the year to the PDF `0..=9999` range afterwards.
+ assert_eq!(civil(253_402_300_800), (10000, 1, 1, 0, 0, 0));
+ assert_eq!(civil(10_000_000_000_000), (318857, 5, 20, 17, 46, 40));
+ assert_eq!(civil(-10_000_000_000_000), (-314918, 8, 13, 6, 13, 20));
+ assert_eq!(civil(i64::MAX), (292277026596, 12, 4, 15, 30, 7));
+ assert_eq!(civil(i64::MIN), (-292277022657, 1, 27, 8, 29, 52));
+ }
}
diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml
index c6e1c876f..afc90c69c 100644
--- a/crates/pptx/Cargo.toml
+++ b/crates/pptx/Cargo.toml
@@ -19,6 +19,7 @@ skrifa = { workspace = true }
image = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
+chrono = { workspace = true }
[dev-dependencies]
designcraft-fonts = { workspace = true, features = ["testing"] }
diff --git a/crates/pptx/src/package.rs b/crates/pptx/src/package.rs
index ed5ad553b..13939aecc 100644
--- a/crates/pptx/src/package.rs
+++ b/crates/pptx/src/package.rs
@@ -290,20 +290,25 @@ fn core(p: &Package) -> String {
s
}
-/// Unix seconds → UTC civil date and time (proleptic Gregorian).
+/// Unix seconds → UTC civil date and time (proleptic Gregorian), year clamped to the W3CDTF
+/// `0..=9999` range. A time outside chrono's year range still converts (the calendar repeats every
+/// 400 years, so the instant is moved into range by whole cycles and only the year is carried,
+/// matching the old `civil`), then the year is clamped — never a silent reset to the epoch.
fn civil(t: i64) -> (i64, u32, u32, u32, u32, u32) {
- let days = t.div_euclid(86_400);
- let secs = t.rem_euclid(86_400);
- let z = days + 719_468;
- let era = z.div_euclid(146_097);
- let doe = z.rem_euclid(146_097);
- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
- 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;
- let y = yoe + era * 400 + i64::from(m <= 2);
- (y.clamp(0, 9999), m, d, (secs / 3600) as u32, (secs / 60 % 60) as u32, (secs % 60) as u32)
+ use chrono::{Datelike, Timelike};
+ let (days, sod) = (t.div_euclid(86_400), t.rem_euclid(86_400));
+ let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097));
+ // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400.
+ let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt);
+ let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, 0));
+ match (date, time) {
+ (Some(d), Some(t)) => {
+ let y = i128::from(d.year()) + i128::from(cycles) * 400;
+ let y = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX });
+ (y.clamp(0, 9999), d.month(), d.day(), t.hour(), t.minute(), t.second())
+ }
+ _ => (1970, 1, 1, 0, 0, 0), // unreachable
+ }
}
/// A neutral theme: text sets its own fonts and colours, so these only matter for new objects.
@@ -331,5 +336,13 @@ mod tests {
assert_eq!(civil(0), (1970, 1, 1, 0, 0, 0));
assert_eq!(civil(951_782_400), (2000, 2, 29, 0, 0, 0));
assert_eq!(civil(1_791_504_000 + 3_723), (2026, 10, 9, 1, 2, 3));
+ // Beyond chrono's year range the old `civil` still converted and clamped only the year to
+ // the W3CDTF `0..=9999` range; pin that (month/day/time keep the real instant), never the
+ // epoch, in both directions and at the `i64` extremes.
+ assert_eq!(civil(253_402_300_800), (9999, 1, 1, 0, 0, 0));
+ assert_eq!(civil(10_000_000_000_000), (9999, 5, 20, 17, 46, 40));
+ assert_eq!(civil(-10_000_000_000_000), (0, 8, 13, 6, 13, 20));
+ assert_eq!(civil(i64::MAX), (9999, 12, 4, 15, 30, 7));
+ assert_eq!(civil(i64::MIN), (0, 1, 27, 8, 29, 52));
}
}