Skip to main content

soml/
chrono.rs

1/*!
2Conversions between chrono's types and SOML's, and modules for `#[serde(with)]`, with the `chrono` feature.
3
4chrono's `DateTime<Utc>` reads SOML instants without this, because it asks for text. But it writes itself as a string, so a document gets a quoted `'2026-09-19T14:00:00Z'` instead of an instant. `TimeDelta` does not ask for text, so it reads a duration only through its module. `NaiveDate` needs its module in both directions, because SOML keeps a date distinct from a string. The modules here write native values:
5
6```rust
7#[derive(serde::Serialize, serde::Deserialize)]
8struct Deploy {
9	#[serde(with = "soml::chrono::date_time")]
10	at: chrono::DateTime<chrono::Utc>,
11	#[serde(with = "soml::chrono::time_delta")]
12	took: chrono::TimeDelta,
13}
14
15let deploy: Deploy = soml::from_str("at: 2026-09-19T14:00:00Z\ntook: 1m30s")?;
16assert_eq!(soml::to_string(&deploy)?, "at: 2026-09-19T14:00:00Z\ntook: 1m30s\n");
17# Ok::<(), soml::Error>(())
18```
19*/
20
21use crate::{Date, Duration, Error, Instant};
22use ::chrono::{DateTime, Datelike, TimeDelta, Utc};
23
24impl TryFrom<DateTime<Utc>> for Instant {
25	type Error = Error;
26
27	/**
28	Fails when the time is outside the years 0001 to 9999, or is a leap second.
29	*/
30	fn try_from(time: DateTime<Utc>) -> Result<Self, Error> {
31		// chrono writes a leap second as nanoseconds past one billion, which SOML cannot represent.
32		let nanoseconds = time.timestamp_subsec_nanos();
33		if nanoseconds >= 1_000_000_000 {
34			return Err(Error::data(format!(
35				"The time {time} is a leap second, which SOML cannot represent"
36			)));
37		}
38
39		// chrono, like `Instant`, counts the nanoseconds forward from the whole second, so a time before 1970 converts directly.
40		Self::from_unix(time.timestamp(), nanoseconds).ok_or_else(|| {
41			Error::data(format!("The time {time} is outside the years 0001 to 9999"))
42		})
43	}
44}
45
46impl From<Instant> for DateTime<Utc> {
47	fn from(instant: Instant) -> Self {
48		Self::from_timestamp(instant.unix_seconds(), instant.nanoseconds())
49			.expect("chrono's range holds every SOML instant")
50	}
51}
52
53impl TryFrom<TimeDelta> for Duration {
54	type Error = Error;
55
56	/**
57	Fails when the duration is longer than `i64::MAX` nanoseconds, about 292 years either way.
58	*/
59	fn try_from(delta: TimeDelta) -> Result<Self, Error> {
60		delta
61			.num_nanoseconds()
62			.map(Self::from_nanoseconds)
63			.ok_or_else(|| {
64				Error::data(format!(
65					"The duration {delta} is outside the SOML range of about 292 years"
66				))
67			})
68	}
69}
70
71impl From<Duration> for TimeDelta {
72	fn from(duration: Duration) -> Self {
73		Self::nanoseconds(duration.nanoseconds())
74	}
75}
76
77serde_with_module! {
78	/**
79	For a `chrono::DateTime<Utc>` field: `#[serde(with = "soml::chrono::date_time")]`.
80	*/
81	date_time, ::chrono::DateTime<::chrono::Utc>, crate::Instant
82}
83
84serde_with_module! {
85	/**
86	For a `chrono::TimeDelta` field: `#[serde(with = "soml::chrono::time_delta")]`.
87	*/
88	time_delta, ::chrono::TimeDelta, crate::Duration
89}
90
91impl TryFrom<::chrono::NaiveDate> for Date {
92	type Error = Error;
93
94	/**
95	Fails when the native date's year is outside 1 through 9999. Components are converted directly, without a time or timezone.
96	*/
97	fn try_from(date: ::chrono::NaiveDate) -> Result<Self, Error> {
98		u16::try_from(date.year())
99			.ok()
100			.and_then(|year| Self::new(year, date.month() as u8, date.day() as u8))
101			.ok_or_else(|| {
102				Error::data(format!("The date {date} is outside the years 0001 to 9999"))
103			})
104	}
105}
106
107impl From<Date> for ::chrono::NaiveDate {
108	fn from(date: Date) -> Self {
109		Self::from_ymd_opt(
110			i32::from(date.year()),
111			u32::from(date.month()),
112			u32::from(date.day()),
113		)
114		.expect("the native Gregorian calendar holds every SOML date")
115	}
116}
117
118serde_with_module! {
119	/**
120	For a `::chrono::NaiveDate` field: `#[serde(with = "soml::chrono::naive_date")]`. Preserves the native date type and components in both directions.
121	*/
122	naive_date, ::chrono::NaiveDate, crate::Date
123}