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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct Instant {
27 seconds: i64,
28 nanoseconds: u32,
29}
30
31const MIN_SECONDS: i64 = -62_135_596_800;
33const MAX_SECONDS: i64 = 253_402_300_799;
34
35pub(crate) const TOKEN: &str = "$soml::Instant";
39
40impl Instant {
41 pub const MIN: Self = Self {
45 seconds: MIN_SECONDS,
46 nanoseconds: 0,
47 };
48
49 pub const MAX: Self = Self {
53 seconds: MAX_SECONDS,
54 nanoseconds: 999_999_999,
55 };
56
57 #[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 #[must_use]
90 pub const fn from_unix_nanoseconds(nanoseconds: i128) -> Option<Self> {
91 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 #[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 #[must_use]
114 pub const fn unix_seconds(self) -> i64 {
115 self.seconds
116 }
117
118 #[must_use]
122 pub const fn nanoseconds(self) -> u32 {
123 self.nanoseconds
124 }
125
126 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 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 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 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 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
215struct 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 fn scan(text: &'a str) -> Option<Self> {
234 let bytes = text.as_bytes();
235
236 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
295fn 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
305pub(crate) fn describe_malformed_instant(
309 text: &str,
310 time: &str,
311 is_whole_value: bool,
312 offset: Option<&str>,
313) -> Option<String> {
314 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
323fn 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 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
404fn 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
423fn 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
453const fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
457 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 era * 146_097 + day_of_era - 719_468
466}
467
468const 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
489impl Display for Instant {
493 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
494 let (year, month, day, hour, minute, second) = self.components();
495 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 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
516pub(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
526pub(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
551impl 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 fn try_from(time: SystemTime) -> Result<Self, Error> {
577 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 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 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");