Skip to main content

soml/
instant.rs

1use crate::Error;
2use crate::scalar::{MAX_DIAGNOSED_LENGTH, has_date_prefix};
3use std::fmt::{self, Display, Write};
4use std::str::FromStr;
5use std::time::{Duration as StdDuration, SystemTime, UNIX_EPOCH};
6
7/**
8A SOML instant: a point in time with nanosecond precision, from `0001-01-01T00:00:00Z` to `9999-12-31T23:59:59.999999999Z`.
9
10This is a UTC timestamp, not a monotonic clock like `std::time::Instant`, so it is meant to be used qualified, as `soml::Instant`.
11
12The offset a document writes an instant with is not part of the value, so `2026-09-19T21:00:00+07:00` and `2026-09-19T14:00:00Z` are the same instant. `Display` writes the canonical form, which is always UTC.
13
14```rust
15let instant: soml::Instant = "2026-09-19T21:00:00.5+07:00".parse()?;
16
17assert_eq!(instant.to_string(), "2026-09-19T14:00:00.5Z");
18assert_eq!(instant.unix_seconds(), 1_789_826_400);
19assert_eq!(instant.nanoseconds(), 500_000_000);
20# Ok::<(), soml::Error>(())
21```
22
23With serde, it reads only from a SOML instant, not from a string, and it is written as a SOML instant. Other formats, such as JSON, see its canonical text.
24*/
25#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct Instant {
27	seconds: i64,
28	nanoseconds: u32,
29}
30
31// The Unix seconds of 0001-01-01T00:00:00Z and of 9999-12-31T23:59:59Z.
32const MIN_SECONDS: i64 = -62_135_596_800;
33const MAX_SECONDS: i64 = 253_402_300_799;
34
35/**
36The name that tells the SOML serializer and deserializer that a newtype struct is an instant. Other formats treat a newtype struct as its content, so they see the canonical text.
37*/
38pub(crate) const TOKEN: &str = "$soml::Instant";
39
40impl Instant {
41	/**
42	The earliest instant, `0001-01-01T00:00:00Z`.
43	*/
44	pub const MIN: Self = Self {
45		seconds: MIN_SECONDS,
46		nanoseconds: 0,
47	};
48
49	/**
50	The latest instant, `9999-12-31T23:59:59.999999999Z`.
51	*/
52	pub const MAX: Self = Self {
53		seconds: MAX_SECONDS,
54		nanoseconds: 999_999_999,
55	};
56
57	/**
58	Creates an instant from whole seconds since 1970-01-01T00:00:00Z, and nanoseconds after them.
59
60	Returns `None` when `nanoseconds` is one billion or more, or when the instant is outside the years 0001 to 9999.
61
62	```rust
63	let instant = soml::Instant::from_unix(0, 0).unwrap();
64	assert_eq!(instant.to_string(), "1970-01-01T00:00:00Z");
65
66	assert!(soml::Instant::from_unix(-62_135_596_801, 0).is_none());
67	```
68	*/
69	#[must_use]
70	pub const fn from_unix(seconds: i64, nanoseconds: u32) -> Option<Self> {
71		if nanoseconds >= 1_000_000_000 || seconds < MIN_SECONDS || seconds > MAX_SECONDS {
72			return None;
73		}
74
75		Some(Self {
76			seconds,
77			nanoseconds,
78		})
79	}
80
81	/**
82	Creates an instant from nanoseconds since 1970-01-01T00:00:00Z. Returns `None` when the instant is outside the years 0001 to 9999.
83
84	```rust
85	let instant = soml::Instant::from_unix_nanoseconds(1_500_000_000).unwrap();
86	assert_eq!(instant.to_string(), "1970-01-01T00:00:01.5Z");
87	```
88	*/
89	#[must_use]
90	pub const fn from_unix_nanoseconds(nanoseconds: i128) -> Option<Self> {
91		// Euclidean division keeps the nanoseconds from 0 to 999,999,999 for an instant before 1970, as `from_unix` requires, so the cast is lossless.
92		let seconds = nanoseconds.div_euclid(1_000_000_000);
93		if seconds < MIN_SECONDS as i128 || seconds > MAX_SECONDS as i128 {
94			return None;
95		}
96		Some(Self {
97			seconds: seconds as i64,
98			nanoseconds: nanoseconds.rem_euclid(1_000_000_000) as u32,
99		})
100	}
101
102	/**
103	Nanoseconds since 1970-01-01T00:00:00Z. Negative for an instant before 1970.
104	*/
105	#[must_use]
106	pub const fn unix_nanoseconds(self) -> i128 {
107		self.seconds as i128 * 1_000_000_000 + self.nanoseconds as i128
108	}
109
110	/**
111	Whole seconds since 1970-01-01T00:00:00Z. Negative for an instant before 1970, which is then made later by `nanoseconds()`.
112	*/
113	#[must_use]
114	pub const fn unix_seconds(self) -> i64 {
115		self.seconds
116	}
117
118	/**
119	The nanoseconds after `unix_seconds()`, from 0 to 999,999,999.
120	*/
121	#[must_use]
122	pub const fn nanoseconds(self) -> u32 {
123		self.nanoseconds
124	}
125
126	/**
127	Reads an instant in SOML syntax, with the reason it is invalid as the error.
128	*/
129	pub(crate) fn parse(text: &str) -> Result<Self, String> {
130		let Some(parts) = Parts::scan(text) else {
131			return Err(describe_bad_instant(text, "", false, None));
132		};
133
134		let reason =
135			|reason: &str| format!("Invalid instant {}: {reason}", crate::abbreviate(text, 40));
136
137		if parts.fraction.len() > 9 {
138			return Err(reason("a fractional second has at most nine digits"));
139		}
140
141		// The year has four digits, so it cannot be more than 9999.
142		if let Some(problem) = crate::Date::calendar_error(parts.year, parts.month, parts.day) {
143			return Err(reason(&problem));
144		}
145
146		if parts.hour > 23 {
147			return Err(reason("the hour must be 00 to 23"));
148		}
149
150		if parts.minute > 59 {
151			return Err(reason("the minute must be 00 to 59"));
152		}
153
154		if parts.second > 59 {
155			return Err(reason(
156				"the second must be 00 to 59, and a leap second is not representable",
157			));
158		}
159
160		if let Some((sign, hour, minute)) = parts.offset {
161			if hour > 23 {
162				return Err(reason("the offset hour must be 00 to 23"));
163			}
164
165			if minute > 59 {
166				return Err(reason("the offset minute must be 00 to 59"));
167			}
168
169			if sign < 0 && hour == 0 && minute == 0 {
170				return Err(reason(
171					"-00:00 means “offset unknown” in RFC 3339, which is not representable; use Z or +00:00",
172				));
173			}
174		}
175
176		// Note: Not using map_or_default because map_or(0, ...) makes the zero UTC offset explicit.
177		let offset_seconds = parts.offset.map_or(0, |(sign, hour, minute)| {
178			sign * (i64::from(hour) * 3600 + i64::from(minute) * 60)
179		});
180		let seconds = days_from_civil(i64::from(parts.year), parts.month, parts.day) * 86_400
181			+ i64::from(parts.hour) * 3600
182			+ i64::from(parts.minute) * 60
183			+ i64::from(parts.second)
184			- offset_seconds;
185
186		// The length check above keeps the scale and value in range.
187		let nanoseconds = parts
188			.fraction
189			.bytes()
190			.fold(0, |value, digit| value * 10 + u32::from(digit - b'0'))
191			* 10u32.pow(9 - parts.fraction.len() as u32);
192
193		Self::from_unix(seconds, nanoseconds)
194			.ok_or_else(|| reason("in UTC it falls outside the years 0001 to 9999"))
195	}
196
197	/**
198	The date and time in UTC: year, month, day, hour, minute, and second.
199	*/
200	fn components(self) -> (i64, u32, u32, u32, u32, u32) {
201		let days = self.seconds.div_euclid(86_400);
202		let second_of_day = self.seconds.rem_euclid(86_400) as u32;
203		let (year, month, day) = civil_from_days(days);
204		(
205			year,
206			month,
207			day,
208			second_of_day / 3600,
209			second_of_day / 60 % 60,
210			second_of_day % 60,
211		)
212	}
213}
214
215/**
216The parts of an instant's text, before any range check. The text must match `YYYY-MM-DDTHH:MM:SS[.fraction](Z|±HH:MM)` exactly.
217*/
218struct Parts<'a> {
219	year: u32,
220	month: u32,
221	day: u32,
222	hour: u32,
223	minute: u32,
224	second: u32,
225	fraction: &'a str,
226	offset: Option<(i64, u32, u32)>,
227}
228
229impl<'a> Parts<'a> {
230	/**
231	The parts, or `None` when the text does not have the form of an instant. A huge text, which only a huge fraction can make, is not read as one, as in the JS reference, so its error is the general one.
232	*/
233	fn scan(text: &'a str) -> Option<Self> {
234		let bytes = text.as_bytes();
235
236		// The shortest instant, `YYYY-MM-DDTHH:MM:SSZ`, has 20 bytes, so the indexes up to 19 below are in bounds.
237		if bytes.len() < 20
238			|| bytes.len() > MAX_DIAGNOSED_LENGTH
239			|| bytes[4] != b'-'
240			|| bytes[7] != b'-'
241			|| bytes[10] != b'T'
242			|| bytes[13] != b':'
243			|| bytes[16] != b':'
244		{
245			return None;
246		}
247
248		let mut index = 19;
249		let mut fraction = "";
250
251		if bytes[index] == b'.' {
252			let start = index + 1;
253			index = crate::scalar::run_end(bytes, start, |byte| byte.is_ascii_digit());
254
255			if index == start {
256				return None;
257			}
258
259			fraction = &text[start..index];
260		}
261
262		let offset = match &bytes[index..] {
263			[b'Z'] => None,
264			[
265				sign @ (b'+' | b'-'),
266				hour_tens,
267				hour_units,
268				b':',
269				minute_tens,
270				minute_units,
271			] => {
272				let sign = if *sign == b'-' { -1 } else { 1 };
273				Some((
274					sign,
275					digits(&[*hour_tens, *hour_units])?,
276					digits(&[*minute_tens, *minute_units])?,
277				))
278			}
279			_ => return None,
280		};
281
282		Some(Self {
283			year: digits(&bytes[0..4])?,
284			month: digits(&bytes[5..7])?,
285			day: digits(&bytes[8..10])?,
286			hour: digits(&bytes[11..13])?,
287			minute: digits(&bytes[14..16])?,
288			second: digits(&bytes[17..19])?,
289			fraction,
290			offset,
291		})
292	}
293}
294
295/**
296The value of a run of ASCII digits, or `None` if any byte is not a digit.
297*/
298fn digits(bytes: &[u8]) -> Option<u32> {
299	bytes.iter().try_fold(0, |value, &byte| {
300		byte.is_ascii_digit()
301			.then(|| value * 10 + u32::from(byte - b'0'))
302	})
303}
304
305/**
306The reason `text` does not have the form of an instant, or `None` when it has that form, whatever its values, or when `text` is a date with no time after it, which is a valid value. `time` is the token after a space that follows `text` in a document, or an empty string, `is_whole_value` is whether nothing that may be part of the instant follows `text` there, and `offset` is an offset after a space that follows `text` there, or `None`.
307*/
308pub(crate) fn describe_malformed_instant(
309	text: &str,
310	time: &str,
311	is_whole_value: bool,
312	offset: Option<&str>,
313) -> Option<String> {
314	// A date alone is valid, so only a date with a time after it is a mistaken instant.
315	if text.len() == 10 && has_date_prefix(text.as_bytes()) && !is_time(time.as_bytes()) {
316		return None;
317	}
318	Parts::scan(text)
319		.is_none()
320		.then(|| describe_bad_instant(text, time, is_whole_value, offset))
321}
322
323/**
324Whether `text` starts with an hour and a minute, `HH:MM`.
325*/
326fn is_time(text: &[u8]) -> bool {
327	text.len() >= 5
328		&& text[..2].iter().all(u8::is_ascii_digit)
329		&& text[2] == b':'
330		&& text[3..5].iter().all(u8::is_ascii_digit)
331}
332
333const INSTANT_FORMAT: &str = "An instant is written as 2026-09-19T14:00:00Z, with an optional fraction of up to nine digits and an offset of Z or ±HH:MM";
334
335fn describe_bad_instant(
336	text: &str,
337	time: &str,
338	is_whole_value: bool,
339	offset: Option<&str>,
340) -> String {
341	let bytes = text.as_bytes();
342	let general = || {
343		format!(
344			"Invalid instant “{}”. {INSTANT_FORMAT}",
345			crate::abbreviate(text, 40)
346		)
347	};
348
349	if text.len() > MAX_DIAGNOSED_LENGTH {
350		return general();
351	}
352
353	if bytes.len() == 10 && has_date_prefix(bytes) {
354		return if is_time(time.as_bytes()) {
355			describe_space_separated_instant(text, time, is_whole_value)
356		} else {
357			format!("A date is not an instant. {INSTANT_FORMAT}")
358		};
359	}
360
361	if bytes.len() > 10 && has_date_prefix(bytes) && bytes[10] == b't' {
362		return "The date and time separator in an instant is an uppercase “T”".to_owned();
363	}
364
365	if text.ends_with('z') {
366		return "The UTC offset in an instant is an uppercase “Z”".to_owned();
367	}
368
369	if let [.., b'+' | b'-', a, b, c, d] = bytes
370		&& [a, b, c, d].iter().all(|byte| byte.is_ascii_digit())
371	{
372		return "An instant's offset is written with a colon, as in +07:00".to_owned();
373	}
374
375	if !is_local_date_time(bytes) {
376		return general();
377	}
378
379	if let Some(offset) = offset {
380		// The instant has the offset it was meant in, so it is not a local time to write as a string.
381		let reason = "An instant's offset follows its time directly, without a space";
382		if text.len().saturating_add(offset.len()) > MAX_DIAGNOSED_LENGTH {
383			return reason.to_owned();
384		}
385		let instant = format!("{text}{offset}");
386
387		return if Instant::parse(&instant).is_ok() {
388			format!("{reason}, as in {}", crate::abbreviate(&instant, 40))
389		} else {
390			reason.to_owned()
391		};
392	}
393
394	if is_whole_value {
395		format!(
396			"An instant needs an offset: Z or ±HH:MM. A date and time without an offset is a local time, which is not an instant, so write it as a string, as in '{}', or add the offset it was meant in",
397			crate::abbreviate(text, 40)
398		)
399	} else {
400		"An instant needs an offset: Z or ±HH:MM".to_owned()
401	}
402}
403
404/**
405Whether `text` is a date and a time with an optional fraction, but no offset.
406*/
407fn is_local_date_time(bytes: &[u8]) -> bool {
408	let has_time = bytes.len() >= 19
409		&& has_date_prefix(bytes)
410		&& bytes[10] == b'T'
411		&& digits(&bytes[11..13]).is_some()
412		&& bytes[13] == b':'
413		&& digits(&bytes[14..16]).is_some()
414		&& bytes[16] == b':'
415		&& digits(&bytes[17..19]).is_some();
416	let rest = bytes.get(19..).unwrap_or_default();
417
418	has_time
419		&& (rest.is_empty()
420			|| (rest.len() > 1 && rest[0] == b'.' && rest[1..].iter().all(u8::is_ascii_digit)))
421}
422
423/**
424A date and a time with a space between them, where an instant has a “T”. Following the example must not turn a local time into UTC silently, so a time without an offset is described as what it is. An instant is only shown when it is valid, so a date that does not exist, a time out of range, or an instant outside the years 0001 to 9999 in UTC gets the general format instead.
425*/
426fn describe_space_separated_instant(date: &str, time: &str, is_whole_value: bool) -> String {
427	const SEPARATOR: &str =
428		"The date and time separator in an instant is an uppercase “T”, not a space";
429	if date.len().saturating_add(time.len()).saturating_add(1) > MAX_DIAGNOSED_LENGTH {
430		return format!("{SEPARATOR}. {INSTANT_FORMAT}");
431	}
432
433	let instant = format!("{date}T{time}");
434
435	if Instant::parse(&instant).is_ok() {
436		return format!("{SEPARATOR}, as in {}", crate::abbreviate(&instant, 40));
437	}
438
439	if is_whole_value
440		&& is_local_date_time(instant.as_bytes())
441		&& Instant::parse(&format!("{instant}Z")).is_ok()
442	{
443		return format!(
444			"{SEPARATOR}, and an instant needs the offset it was meant in, as in {}Z for UTC. A date and time without an offset is a local time, which is not an instant, so write it as a string, as in '{}'",
445			crate::abbreviate(&instant, 40),
446			crate::abbreviate(&format!("{date} {time}"), 40)
447		);
448	}
449
450	format!("{SEPARATOR}. {INSTANT_FORMAT}")
451}
452
453/**
454Days since 1970-01-01 in the proleptic Gregorian calendar. Howard Hinnant's `days_from_civil`.
455*/
456const fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
457	// The year starts on March 1 here, so that a leap day is the last day of its year.
458	let year = if month <= 2 { year - 1 } else { year };
459	let era = year.div_euclid(400);
460	let year_of_era = year.rem_euclid(400);
461	let month_from_march = (month as i64 + 9) % 12;
462	let day_of_year = (153 * month_from_march + 2) / 5 + day as i64 - 1;
463	let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
464	// 719,468 is the number of days from 0000-03-01 to 1970-01-01.
465	era * 146_097 + day_of_era - 719_468
466}
467
468/**
469The year, month, and day of a count of days since 1970-01-01. Howard Hinnant's `civil_from_days`.
470*/
471const fn civil_from_days(days: i64) -> (i64, u32, u32) {
472	let days = days + 719_468;
473	let era = days.div_euclid(146_097);
474	let day_of_era = days.rem_euclid(146_097);
475	let year_of_era =
476		(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
477	let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
478	let month_from_march = (5 * day_of_year + 2) / 153;
479	let day = (day_of_year - (153 * month_from_march + 2) / 5 + 1) as u32;
480	let month = if month_from_march < 10 {
481		month_from_march + 3
482	} else {
483		month_from_march - 9
484	} as u32;
485	let year = year_of_era + era * 400 + if month <= 2 { 1 } else { 0 };
486	(year, month, day)
487}
488
489/**
490Writes the canonical form: UTC with `Z`, and a fraction without trailing zeros, left out when it is zero.
491*/
492impl Display for Instant {
493	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
494		let (year, month, day, hour, minute, second) = self.components();
495		// The digits are put in place, because `write!` is several times slower, and a large document can have thousands of instants. Each field has a fixed width, and the year is from 1 to 9999.
496		let mut text = *b"0000-00-00T00:00:00";
497
498		for (end, width, value) in [
499			(4, 4, year as u32),
500			(7, 2, month),
501			(10, 2, day),
502			(13, 2, hour),
503			(16, 2, minute),
504			(19, 2, second),
505		] {
506			put_digits(&mut text[end - width..end], value);
507		}
508
509		// Note: Not using typed ASCII views because they are unstable on the minimum Rust version.
510		formatter.write_str(std::str::from_utf8(&text).expect("the digits are ASCII"))?;
511		write_fraction(formatter, self.nanoseconds)?;
512		formatter.write_char('Z')
513	}
514}
515
516/**
517Writes `value` in decimal into all of `digits`, with leading zeros.
518*/
519pub(crate) fn put_digits(digits: &mut [u8], mut value: u32) {
520	for digit in digits.iter_mut().rev() {
521		*digit = b'0' + (value % 10) as u8;
522		value /= 10;
523	}
524}
525
526/**
527Writes `.` and the nanoseconds as a fraction of a second without trailing zeros, or nothing when they are zero. Instants and durations share this form.
528*/
529pub(crate) fn write_fraction(output: &mut impl Write, nanoseconds: u32) -> fmt::Result {
530	if nanoseconds == 0 {
531		return Ok(());
532	}
533
534	let mut nanoseconds = nanoseconds;
535	let mut width = 9;
536	while nanoseconds.is_multiple_of(10) {
537		nanoseconds /= 10;
538		width -= 1;
539	}
540	let mut text = *b".000000000";
541	put_digits(&mut text[1..=width], nanoseconds);
542	output.write_str(std::str::from_utf8(&text[..=width]).expect("the digits are ASCII"))
543}
544
545impl fmt::Debug for Instant {
546	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
547		write!(formatter, "Instant({self})")
548	}
549}
550
551/**
552Reads an instant in SOML syntax, with any offset.
553
554```rust
555let instant: soml::Instant = "2026-09-19T14:00:00Z".parse()?;
556assert_eq!(instant.unix_seconds(), 1_789_826_400);
557
558assert!("2026-09-19".parse::<soml::Instant>().is_err());
559# Ok::<(), soml::Error>(())
560```
561*/
562impl FromStr for Instant {
563	type Err = Error;
564
565	fn from_str(text: &str) -> Result<Self, Error> {
566		Self::parse(text).map_err(Error::syntax)
567	}
568}
569
570impl TryFrom<SystemTime> for Instant {
571	type Error = Error;
572
573	/**
574	Fails when the time is outside the years 0001 to 9999.
575	*/
576	fn try_from(time: SystemTime) -> Result<Self, Error> {
577		// Every SystemTime duration has u64 seconds, so its nanoseconds fit an i128. Signed nanoseconds also handle the borrowed second before the epoch directly.
578		let nanoseconds = match time.duration_since(UNIX_EPOCH) {
579			Ok(after) => after.as_nanos() as i128,
580			Err(error) => -(error.duration().as_nanos() as i128),
581		};
582		Self::from_unix_nanoseconds(nanoseconds)
583			.ok_or_else(|| Error::data("The time is outside the years 0001 to 9999"))
584	}
585}
586
587impl TryFrom<Instant> for SystemTime {
588	type Error = Error;
589
590	/**
591	Fails when the platform's `SystemTime` cannot hold the instant. On Windows, for example, it cannot go before the year 1601.
592	*/
593	fn try_from(instant: Instant) -> Result<Self, Error> {
594		let nanoseconds = instant.unix_nanoseconds();
595		let magnitude = nanoseconds.unsigned_abs();
596		let duration = StdDuration::new(
597			(magnitude / 1_000_000_000) as u64,
598			(magnitude % 1_000_000_000) as u32,
599		);
600		let time = if nanoseconds >= 0 {
601			UNIX_EPOCH.checked_add(duration)
602		} else {
603			// The nanoseconds count forward from the whole second, so the signed total gives the exact distance before the epoch.
604			UNIX_EPOCH.checked_sub(duration)
605		};
606
607		time.ok_or_else(|| {
608			Error::data(format!(
609				"The instant {instant} is outside the range of SystemTime on this platform"
610			))
611		})
612	}
613}
614
615serde_temporal_scalar!(Instant, "an instant");