use crate::Error;
use crate::scalar::{MAX_DIAGNOSED_LENGTH, has_date_prefix};
use std::fmt::{self, Display, Write};
use std::str::FromStr;
use std::time::{Duration as StdDuration, SystemTime, UNIX_EPOCH};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant {
seconds: i64,
nanoseconds: u32,
}
const MIN_SECONDS: i64 = -62_135_596_800;
const MAX_SECONDS: i64 = 253_402_300_799;
pub(crate) const TOKEN: &str = "$soml::Instant";
impl Instant {
pub const MIN: Self = Self {
seconds: MIN_SECONDS,
nanoseconds: 0,
};
pub const MAX: Self = Self {
seconds: MAX_SECONDS,
nanoseconds: 999_999_999,
};
#[must_use]
pub const fn from_unix(seconds: i64, nanoseconds: u32) -> Option<Self> {
if nanoseconds >= 1_000_000_000 || seconds < MIN_SECONDS || seconds > MAX_SECONDS {
return None;
}
Some(Self {
seconds,
nanoseconds,
})
}
#[must_use]
pub const fn from_unix_nanoseconds(nanoseconds: i128) -> Option<Self> {
let seconds = nanoseconds.div_euclid(1_000_000_000);
if seconds < MIN_SECONDS as i128 || seconds > MAX_SECONDS as i128 {
return None;
}
Some(Self {
seconds: seconds as i64,
nanoseconds: nanoseconds.rem_euclid(1_000_000_000) as u32,
})
}
#[must_use]
pub const fn unix_nanoseconds(self) -> i128 {
self.seconds as i128 * 1_000_000_000 + self.nanoseconds as i128
}
#[must_use]
pub const fn unix_seconds(self) -> i64 {
self.seconds
}
#[must_use]
pub const fn nanoseconds(self) -> u32 {
self.nanoseconds
}
pub(crate) fn parse(text: &str) -> Result<Self, String> {
let Some(parts) = Parts::scan(text) else {
return Err(describe_bad_instant(text, "", false, None));
};
let reason =
|reason: &str| format!("Invalid instant {}: {reason}", crate::abbreviate(text, 40));
if parts.fraction.len() > 9 {
return Err(reason("a fractional second has at most nine digits"));
}
if let Some(problem) = crate::Date::calendar_error(parts.year, parts.month, parts.day) {
return Err(reason(&problem));
}
if parts.hour > 23 {
return Err(reason("the hour must be 00 to 23"));
}
if parts.minute > 59 {
return Err(reason("the minute must be 00 to 59"));
}
if parts.second > 59 {
return Err(reason(
"the second must be 00 to 59, and a leap second is not representable",
));
}
if let Some((sign, hour, minute)) = parts.offset {
if hour > 23 {
return Err(reason("the offset hour must be 00 to 23"));
}
if minute > 59 {
return Err(reason("the offset minute must be 00 to 59"));
}
if sign < 0 && hour == 0 && minute == 0 {
return Err(reason(
"-00:00 means “offset unknown” in RFC 3339, which is not representable; use Z or +00:00",
));
}
}
let offset_seconds = parts.offset.map_or(0, |(sign, hour, minute)| {
sign * (i64::from(hour) * 3600 + i64::from(minute) * 60)
});
let seconds = days_from_civil(i64::from(parts.year), parts.month, parts.day) * 86_400
+ i64::from(parts.hour) * 3600
+ i64::from(parts.minute) * 60
+ i64::from(parts.second)
- offset_seconds;
let nanoseconds = parts
.fraction
.bytes()
.fold(0, |value, digit| value * 10 + u32::from(digit - b'0'))
* 10u32.pow(9 - parts.fraction.len() as u32);
Self::from_unix(seconds, nanoseconds)
.ok_or_else(|| reason("in UTC it falls outside the years 0001 to 9999"))
}
fn components(self) -> (i64, u32, u32, u32, u32, u32) {
let days = self.seconds.div_euclid(86_400);
let second_of_day = self.seconds.rem_euclid(86_400) as u32;
let (year, month, day) = civil_from_days(days);
(
year,
month,
day,
second_of_day / 3600,
second_of_day / 60 % 60,
second_of_day % 60,
)
}
}
struct Parts<'a> {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
fraction: &'a str,
offset: Option<(i64, u32, u32)>,
}
impl<'a> Parts<'a> {
fn scan(text: &'a str) -> Option<Self> {
let bytes = text.as_bytes();
if bytes.len() < 20
|| bytes.len() > MAX_DIAGNOSED_LENGTH
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| bytes[10] != b'T'
|| bytes[13] != b':'
|| bytes[16] != b':'
{
return None;
}
let mut index = 19;
let mut fraction = "";
if bytes[index] == b'.' {
let start = index + 1;
index = crate::scalar::run_end(bytes, start, |byte| byte.is_ascii_digit());
if index == start {
return None;
}
fraction = &text[start..index];
}
let offset = match &bytes[index..] {
[b'Z'] => None,
[
sign @ (b'+' | b'-'),
hour_tens,
hour_units,
b':',
minute_tens,
minute_units,
] => {
let sign = if *sign == b'-' { -1 } else { 1 };
Some((
sign,
digits(&[*hour_tens, *hour_units])?,
digits(&[*minute_tens, *minute_units])?,
))
}
_ => return None,
};
Some(Self {
year: digits(&bytes[0..4])?,
month: digits(&bytes[5..7])?,
day: digits(&bytes[8..10])?,
hour: digits(&bytes[11..13])?,
minute: digits(&bytes[14..16])?,
second: digits(&bytes[17..19])?,
fraction,
offset,
})
}
}
fn digits(bytes: &[u8]) -> Option<u32> {
bytes.iter().try_fold(0, |value, &byte| {
byte.is_ascii_digit()
.then(|| value * 10 + u32::from(byte - b'0'))
})
}
pub(crate) fn describe_malformed_instant(
text: &str,
time: &str,
is_whole_value: bool,
offset: Option<&str>,
) -> Option<String> {
if text.len() == 10 && has_date_prefix(text.as_bytes()) && !is_time(time.as_bytes()) {
return None;
}
Parts::scan(text)
.is_none()
.then(|| describe_bad_instant(text, time, is_whole_value, offset))
}
fn is_time(text: &[u8]) -> bool {
text.len() >= 5
&& text[..2].iter().all(u8::is_ascii_digit)
&& text[2] == b':'
&& text[3..5].iter().all(u8::is_ascii_digit)
}
const 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";
fn describe_bad_instant(
text: &str,
time: &str,
is_whole_value: bool,
offset: Option<&str>,
) -> String {
let bytes = text.as_bytes();
let general = || {
format!(
"Invalid instant “{}”. {INSTANT_FORMAT}",
crate::abbreviate(text, 40)
)
};
if text.len() > MAX_DIAGNOSED_LENGTH {
return general();
}
if bytes.len() == 10 && has_date_prefix(bytes) {
return if is_time(time.as_bytes()) {
describe_space_separated_instant(text, time, is_whole_value)
} else {
format!("A date is not an instant. {INSTANT_FORMAT}")
};
}
if bytes.len() > 10 && has_date_prefix(bytes) && bytes[10] == b't' {
return "The date and time separator in an instant is an uppercase “T”".to_owned();
}
if text.ends_with('z') {
return "The UTC offset in an instant is an uppercase “Z”".to_owned();
}
if let [.., b'+' | b'-', a, b, c, d] = bytes
&& [a, b, c, d].iter().all(|byte| byte.is_ascii_digit())
{
return "An instant's offset is written with a colon, as in +07:00".to_owned();
}
if !is_local_date_time(bytes) {
return general();
}
if let Some(offset) = offset {
let reason = "An instant's offset follows its time directly, without a space";
if text.len().saturating_add(offset.len()) > MAX_DIAGNOSED_LENGTH {
return reason.to_owned();
}
let instant = format!("{text}{offset}");
return if Instant::parse(&instant).is_ok() {
format!("{reason}, as in {}", crate::abbreviate(&instant, 40))
} else {
reason.to_owned()
};
}
if is_whole_value {
format!(
"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",
crate::abbreviate(text, 40)
)
} else {
"An instant needs an offset: Z or ±HH:MM".to_owned()
}
}
fn is_local_date_time(bytes: &[u8]) -> bool {
let has_time = bytes.len() >= 19
&& has_date_prefix(bytes)
&& bytes[10] == b'T'
&& digits(&bytes[11..13]).is_some()
&& bytes[13] == b':'
&& digits(&bytes[14..16]).is_some()
&& bytes[16] == b':'
&& digits(&bytes[17..19]).is_some();
let rest = bytes.get(19..).unwrap_or_default();
has_time
&& (rest.is_empty()
|| (rest.len() > 1 && rest[0] == b'.' && rest[1..].iter().all(u8::is_ascii_digit)))
}
fn describe_space_separated_instant(date: &str, time: &str, is_whole_value: bool) -> String {
const SEPARATOR: &str =
"The date and time separator in an instant is an uppercase “T”, not a space";
if date.len().saturating_add(time.len()).saturating_add(1) > MAX_DIAGNOSED_LENGTH {
return format!("{SEPARATOR}. {INSTANT_FORMAT}");
}
let instant = format!("{date}T{time}");
if Instant::parse(&instant).is_ok() {
return format!("{SEPARATOR}, as in {}", crate::abbreviate(&instant, 40));
}
if is_whole_value
&& is_local_date_time(instant.as_bytes())
&& Instant::parse(&format!("{instant}Z")).is_ok()
{
return format!(
"{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 '{}'",
crate::abbreviate(&instant, 40),
crate::abbreviate(&format!("{date} {time}"), 40)
);
}
format!("{SEPARATOR}. {INSTANT_FORMAT}")
}
const fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year.rem_euclid(400);
let month_from_march = (month as i64 + 9) % 12;
let day_of_year = (153 * month_from_march + 2) / 5 + day as i64 - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
const fn civil_from_days(days: i64) -> (i64, u32, u32) {
let days = days + 719_468;
let era = days.div_euclid(146_097);
let day_of_era = days.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_from_march = (5 * day_of_year + 2) / 153;
let day = (day_of_year - (153 * month_from_march + 2) / 5 + 1) as u32;
let month = if month_from_march < 10 {
month_from_march + 3
} else {
month_from_march - 9
} as u32;
let year = year_of_era + era * 400 + if month <= 2 { 1 } else { 0 };
(year, month, day)
}
impl Display for Instant {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let (year, month, day, hour, minute, second) = self.components();
let mut text = *b"0000-00-00T00:00:00";
for (end, width, value) in [
(4, 4, year as u32),
(7, 2, month),
(10, 2, day),
(13, 2, hour),
(16, 2, minute),
(19, 2, second),
] {
put_digits(&mut text[end - width..end], value);
}
formatter.write_str(std::str::from_utf8(&text).expect("the digits are ASCII"))?;
write_fraction(formatter, self.nanoseconds)?;
formatter.write_char('Z')
}
}
pub(crate) fn put_digits(digits: &mut [u8], mut value: u32) {
for digit in digits.iter_mut().rev() {
*digit = b'0' + (value % 10) as u8;
value /= 10;
}
}
pub(crate) fn write_fraction(output: &mut impl Write, nanoseconds: u32) -> fmt::Result {
if nanoseconds == 0 {
return Ok(());
}
let mut nanoseconds = nanoseconds;
let mut width = 9;
while nanoseconds.is_multiple_of(10) {
nanoseconds /= 10;
width -= 1;
}
let mut text = *b".000000000";
put_digits(&mut text[1..=width], nanoseconds);
output.write_str(std::str::from_utf8(&text[..=width]).expect("the digits are ASCII"))
}
impl fmt::Debug for Instant {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "Instant({self})")
}
}
impl FromStr for Instant {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
Self::parse(text).map_err(Error::syntax)
}
}
impl TryFrom<SystemTime> for Instant {
type Error = Error;
fn try_from(time: SystemTime) -> Result<Self, Error> {
let nanoseconds = match time.duration_since(UNIX_EPOCH) {
Ok(after) => after.as_nanos() as i128,
Err(error) => -(error.duration().as_nanos() as i128),
};
Self::from_unix_nanoseconds(nanoseconds)
.ok_or_else(|| Error::data("The time is outside the years 0001 to 9999"))
}
}
impl TryFrom<Instant> for SystemTime {
type Error = Error;
fn try_from(instant: Instant) -> Result<Self, Error> {
let nanoseconds = instant.unix_nanoseconds();
let magnitude = nanoseconds.unsigned_abs();
let duration = StdDuration::new(
(magnitude / 1_000_000_000) as u64,
(magnitude % 1_000_000_000) as u32,
);
let time = if nanoseconds >= 0 {
UNIX_EPOCH.checked_add(duration)
} else {
UNIX_EPOCH.checked_sub(duration)
};
time.ok_or_else(|| {
Error::data(format!(
"The instant {instant} is outside the range of SystemTime on this platform"
))
})
}
}
serde_temporal_scalar!(Instant, "an instant");