use core::fmt;
#[cfg(feature = "async-graphql")]
use smol_bytes::{Utf8Bytes, Utf8BytesMut};
#[cfg(all(test, feature = "async-graphql"))]
mod tests;
#[cfg(feature = "async-graphql")]
const NANOS_PER_SECOND: i128 = 1_000_000_000;
#[cfg(feature = "async-graphql")]
const FRACTION_DIGITS: usize = 9;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseClockError {
Shape,
Hours,
Minutes,
Seconds,
Fraction,
Overflow,
}
impl fmt::Display for ParseClockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let reason = match self {
Self::Shape => "a clock is spelled H:MM:SS or H:MM:SS.fff",
Self::Hours => "the hours are one or more digits",
Self::Minutes => "the minutes are exactly two digits, below sixty",
Self::Seconds => "the seconds are exactly two digits, below sixty",
Self::Fraction => "the fraction is one to nine digits",
Self::Overflow => "the position is further from zero than 292 years of nanoseconds",
};
f.write_str(reason)
}
}
impl core::error::Error for ParseClockError {}
#[cfg(feature = "async-graphql")]
pub fn nanos(text: &str) -> Result<i64, ParseClockError> {
let (negative, body) = match text.strip_prefix('-') {
Some(body) => (true, body),
None => (false, text),
};
let (hours, rest) = body.split_once(':').ok_or(ParseClockError::Shape)?;
let (minutes, rest) = rest.split_once(':').ok_or(ParseClockError::Shape)?;
let (seconds, fraction) = match rest.split_once('.') {
Some((seconds, fraction)) => (seconds, Some(fraction)),
None => (rest, None),
};
let hours: i128 = digits(hours, 1..=usize::MAX).ok_or(ParseClockError::Hours)?;
let minutes: i128 = digits(minutes, 2..=2)
.filter(|minutes| *minutes < 60)
.ok_or(ParseClockError::Minutes)?;
let seconds: i128 = digits(seconds, 2..=2)
.filter(|seconds| *seconds < 60)
.ok_or(ParseClockError::Seconds)?;
let nanos = match fraction {
Some(fraction) => {
if fraction.is_empty() || fraction.len() > FRACTION_DIGITS {
return Err(ParseClockError::Fraction);
}
let scale = 10i128.pow((FRACTION_DIGITS - fraction.len()) as u32);
digits(fraction, 1..=FRACTION_DIGITS).ok_or(ParseClockError::Fraction)? * scale
}
None => 0,
};
let total = ((hours * 60 + minutes) * 60 + seconds) * NANOS_PER_SECOND + nanos;
let total = if negative { -total } else { total };
i64::try_from(total).map_err(|_| ParseClockError::Overflow)
}
#[cfg(feature = "async-graphql")]
fn digits(text: &str, width: core::ops::RangeInclusive<usize>) -> Option<i128> {
if !width.contains(&text.len()) || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
text.bytes().try_fold(0i128, |sum, byte| {
sum
.checked_mul(10)
.and_then(|sum| sum.checked_add(i128::from(byte - b'0')))
})
}
#[cfg(feature = "async-graphql")]
#[must_use]
pub fn render(nanos: i64) -> Utf8Bytes {
let negative = nanos < 0;
let magnitude = u128::from(nanos.unsigned_abs());
let fraction = magnitude % (NANOS_PER_SECOND as u128);
let whole = magnitude / (NANOS_PER_SECOND as u128);
let mut clock = Utf8BytesMut::with_capacity(24);
if negative {
clock.push('-');
}
push_number(&mut clock, whole / 3600, 1);
clock.push(':');
push_number(&mut clock, (whole / 60) % 60, 2);
clock.push(':');
push_number(&mut clock, whole % 60, 2);
clock.push('.');
push_number(&mut clock, fraction, FRACTION_DIGITS);
clock.freeze_shared()
}
#[cfg(feature = "async-graphql")]
fn push_number(out: &mut Utf8BytesMut, value: u128, width: usize) {
let mut digits = [0u8; 39];
let mut written = 0;
let mut rest = value;
while {
digits[written] = b'0' + (rest % 10) as u8;
written += 1;
rest /= 10;
rest > 0
} {}
for _ in written..width {
out.push('0');
}
for index in (0..written).rev() {
out.push(char::from(digits[index]));
}
}