use crate::Error;
use core::fmt::NumBuffer;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::time::Duration as StdDuration;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Duration {
nanoseconds: i64,
}
pub(crate) const TOKEN: &str = "$soml::Duration";
const UNITS: [&str; 6] = ["h", "m", "s", "ms", "us", "ns"];
impl Duration {
pub const MIN: Self = Self::from_nanoseconds(i64::MIN);
pub const MAX: Self = Self::from_nanoseconds(i64::MAX);
pub const ZERO: Self = Self::from_nanoseconds(0);
#[must_use]
pub const fn from_nanoseconds(nanoseconds: i64) -> Self {
Self { nanoseconds }
}
#[must_use]
pub const fn nanoseconds(self) -> i64 {
self.nanoseconds
}
#[must_use]
pub const fn is_negative(self) -> bool {
self.nanoseconds < 0
}
pub(crate) fn parse(text: &str) -> Result<Self, String> {
let fail = |reason: &str| {
Err(format!(
"Invalid duration {}: {reason}",
crate::abbreviate(text, 40)
))
};
let bytes = text.as_bytes();
let is_negative = bytes.first() == Some(&b'-');
let mut index = usize::from(is_negative);
if index == bytes.len() {
return fail("a duration needs at least one part, as in 30s");
}
let mut previous_rank = None;
let mut total: u64 = 0;
let mut fraction: &[u8] = &[];
let mut unit_length: u64 = 0;
while index < bytes.len() {
let digits_end = crate::scalar::skip_integer_part(bytes, index);
let next = bytes.get(digits_end).copied();
if digits_end == index {
if bytes[index] == b'-' && bytes.get(index + 1).is_some_and(u8::is_ascii_digit) {
return fail("only the whole duration takes a sign, as in -1h30m");
}
if bytes[index] == b'+' {
return fail("a “+” sign is not allowed");
}
return fail(&format!(
"expected a number at “{}”",
crate::abbreviate(&text[index..], 10)
));
}
if bytes[index] == b'0'
&& next.is_some_and(|byte| byte.is_ascii_digit() || byte == b'_')
{
return fail("leading zeros are not allowed");
}
if next == Some(b'_') {
return fail("an underscore must be between two digits");
}
fraction = &[];
let mut unit_start = digits_end;
if next == Some(b'.') {
unit_start = crate::scalar::skip_digits(bytes, digits_end + 1, u8::is_ascii_digit);
if unit_start == digits_end + 1 {
return fail("a “.” must be followed by a digit");
}
if bytes.get(unit_start) == Some(&b'_') {
return fail("an underscore must be between two digits");
}
fraction = &bytes[digits_end + 1..unit_start];
}
let limit = bytes.len().min(unit_start + 11);
let unit_end = crate::scalar::run_end(&bytes[..limit], unit_start, |byte| {
byte.is_ascii_alphabetic()
});
let unit = &text[unit_start..unit_end];
let (rank, length) = match unit {
"h" => (0, 3_600_000_000_000),
"m" => (1, 60_000_000_000),
"s" => (2, 1_000_000_000),
"ms" => (3, 1_000_000),
"us" => (4, 1000),
"ns" => (5, 1),
_ => return fail(&describe_bad_unit(unit, text)),
};
if previous_rank.is_some_and(|previous| rank <= previous) {
return fail(
"the units are in the order h, m, s, ms, us, ns, and each appears at most once",
);
}
if next == Some(b'.') && bytes.get(unit_end).is_some_and(u8::is_ascii_digit) {
return fail("only the last part may have a fraction");
}
unit_length = length;
total = total.saturating_add(
integer_digits(&bytes[index..digits_end]).saturating_mul(unit_length),
);
index = unit_end;
previous_rank = Some(rank);
}
let fraction = &fraction[..fraction
.iter()
.rposition(|&byte| byte != b'0' && byte != b'_')
.map_or(0, |last| last + 1)];
let fraction_digits = fraction
.iter()
.filter(|&&byte| byte != b'_')
.take(14)
.count();
if fraction_digits > 13 {
return fail("it is not a whole number of nanoseconds");
}
if !fraction.is_empty() {
let scale = 10u128.pow(fraction_digits as u32);
let fraction_nanoseconds =
u128::from(integer_digits(fraction)) * u128::from(unit_length);
if !fraction_nanoseconds.is_multiple_of(scale) {
return fail("it is not a whole number of nanoseconds");
}
total = total.saturating_add((fraction_nanoseconds / scale) as u64);
}
if is_negative && total == 0 {
return fail("“-” is not allowed before zero, because zero has one spelling: 0s");
}
let nanoseconds = if is_negative {
0i64.checked_sub_unsigned(total)
} else {
i64::try_from(total).ok()
};
let Some(nanoseconds) = nanoseconds else {
return fail(
"it is outside the 64-bit range of nanoseconds, about 292 years either way",
);
};
Ok(Self::from_nanoseconds(nanoseconds))
}
}
fn integer_digits(digits: &[u8]) -> u64 {
digits
.iter()
.filter(|&&byte| byte != b'_')
.try_fold(0u64, |value, &byte| {
let (value, carry) = value.carrying_mul(10, u64::from(byte - b'0'));
(carry == 0).then_some(value)
})
.unwrap_or(u64::MAX)
}
pub(crate) fn is_year_unit(unit: &[u8]) -> bool {
["y", "yr", "yrs", "year", "years"]
.iter()
.any(|name| name.as_bytes().eq_ignore_ascii_case(unit))
}
fn describe_bad_unit<'a>(unit: &'a str, text: &str) -> std::borrow::Cow<'a, str> {
match unit {
"" => "every number needs a unit: h, m, s, ms, us, or ns".into(),
"d" | "day" | "days" => "there is no day unit, because a day is not a fixed length. Write 24h for a fixed 24 hours".into(),
"w" | "week" | "weeks" => "there is no week unit, because a day is not a fixed length. Write 168h for a fixed 168 hours".into(),
_ if is_year_unit(unit.as_bytes()) => "there is no year unit, because a year is not a fixed length. Write 8760h for a fixed 365 days".into(),
"M" => {
let is_size = text.len() <= crate::scalar::MAX_DIAGNOSED_LENGTH && text.ends_with('M') && text[..text.len() - 1].bytes().all(|byte| byte.is_ascii_digit() || byte == b'_');
let size_hint = if is_size {
format!(". A size, such as 512M, is a string: '{}'", crate::abbreviate(text, 40))
} else {
String::new()
};
format!("there is no month unit, because a month is not a fixed length{size_hint}").into()
}
_ if let Some(name) = UNITS.iter().find(|name| name.eq_ignore_ascii_case(unit)) => format!("the units are lowercase: {name}").into(),
_ => format!("“{}” is not a unit. The units are h, m, s, ms, us, and ns, and a string must be quoted", crate::abbreviate(unit, 10)).into(),
}
}
impl Display for Duration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
const SECOND: u64 = 1_000_000_000;
let magnitude = self.nanoseconds.unsigned_abs();
if magnitude == 0 {
return formatter.write_str("0s");
}
if self.nanoseconds < 0 {
formatter.write_str("-")?;
}
let whole_seconds = magnitude / SECOND;
let hours = whole_seconds / 3600;
let minutes = whole_seconds / 60 % 60;
let seconds = whole_seconds % 60;
let nanoseconds = (magnitude % SECOND) as u32;
let mut digits = NumBuffer::new();
if hours > 0 {
formatter.write_str(hours.format_into(&mut digits))?;
formatter.write_str("h")?;
}
if minutes > 0 {
formatter.write_str(minutes.format_into(&mut digits))?;
formatter.write_str("m")?;
}
if seconds > 0 || nanoseconds > 0 {
formatter.write_str(seconds.format_into(&mut digits))?;
crate::instant::write_fraction(formatter, nanoseconds)?;
formatter.write_str("s")?;
}
Ok(())
}
}
impl fmt::Debug for Duration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "Duration({self})")
}
}
impl FromStr for Duration {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
Self::parse(text).map_err(Error::syntax)
}
}
impl TryFrom<StdDuration> for Duration {
type Error = Error;
fn try_from(duration: StdDuration) -> Result<Self, Error> {
i64::try_from(duration.as_nanos())
.map(Self::from_nanoseconds)
.map_err(|_| {
Error::data(format!(
"The duration {duration:?} is outside the SOML range of about 292 years"
))
})
}
}
impl TryFrom<Duration> for StdDuration {
type Error = Error;
fn try_from(duration: Duration) -> Result<Self, Error> {
u64::try_from(duration.nanoseconds)
.map(Self::from_nanos)
.map_err(|_| {
Error::data(format!(
"The duration {duration} is negative, which a std::time::Duration cannot be"
))
})
}
}
serde_temporal_scalar!(Duration, "a duration");