footing 0.1.6

Feature-gated foundations for Rust backend services
Documentation
//! Serde-compatible human-readable durations.

use std::{error::Error, fmt, time::Duration};

use serde::{Deserializer, Serializer, de};

use crate::result::{ClassifyError, ErrorKind};

const NANOS_PER_NANO: u128 = 1;
const NANOS_PER_MICRO: u128 = 1_000;
const NANOS_PER_MILLI: u128 = 1_000_000;
const NANOS_PER_SECOND: u128 = 1_000_000_000;
const NANOS_PER_MINUTE: u128 = 60 * NANOS_PER_SECOND;
const NANOS_PER_HOUR: u128 = 60 * NANOS_PER_MINUTE;
const NANOS_PER_DAY: u128 = 24 * NANOS_PER_HOUR;
const NANOS_PER_WEEK: u128 = 7 * NANOS_PER_DAY;

/// Serializes the value.
pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&format(*duration))
}

/// Deserializes and validates the value.
pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_str(DurationVisitor)
}

/// Utilities for option.
pub mod option {
    use super::*;

    /// Serializes the value.
    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match duration {
            Some(duration) => serializer.serialize_some(&format(*duration)),
            None => serializer.serialize_none(),
        }
    }

    /// Deserializes and validates the value.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OptionDurationVisitor;

        impl<'de> de::Visitor<'de> for OptionDurationVisitor {
            type Value = Option<Duration>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("null or a duration string")
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(None)
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(None)
            }

            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize(deserializer).map(Some)
            }
        }

        deserializer.deserialize_option(OptionDurationVisitor)
    }
}

#[must_use]
/// Formats the value.
pub fn format(duration: Duration) -> String {
    let total_nanos =
        u128::from(duration.as_secs()) * NANOS_PER_SECOND + u128::from(duration.subsec_nanos());
    for (unit, unit_nanos) in [
        ("w", NANOS_PER_WEEK),
        ("d", NANOS_PER_DAY),
        ("h", NANOS_PER_HOUR),
        ("m", NANOS_PER_MINUTE),
        ("s", NANOS_PER_SECOND),
        ("ms", NANOS_PER_MILLI),
        ("us", NANOS_PER_MICRO),
        ("ns", NANOS_PER_NANO),
    ] {
        if total_nanos >= unit_nanos && total_nanos.is_multiple_of(unit_nanos) {
            return format!("{}{unit}", total_nanos / unit_nanos);
        }
    }

    format!("{}ns", duration.as_nanos())
}

/// Parses the value.
pub fn parse(value: &str) -> Result<Duration, ParseDurationError> {
    let value = value.trim();
    if value.is_empty() {
        return Err(ParseDurationError::Empty);
    }

    let mut index = 0;
    let mut total_nanos = 0_u128;
    let mut saw_component = false;

    while index < value.len() {
        skip_ascii_whitespace(value, &mut index);
        if index >= value.len() {
            break;
        }

        let number_start = index;
        while value.as_bytes().get(index).is_some_and(u8::is_ascii_digit) {
            index += 1;
        }
        if number_start == index {
            return Err(ParseDurationError::MissingNumber { offset: index });
        }

        let amount = value
            .get(number_start..index)
            .ok_or(ParseDurationError::InvalidUnit)?
            .parse::<u128>()
            .map_err(|_| ParseDurationError::NumberTooLarge)?;
        let unit = value.get(index..).ok_or(ParseDurationError::InvalidUnit)?;
        let (unit_nanos, unit_len) = duration_unit(unit)?;
        index += unit_len;
        saw_component = true;

        let component = amount
            .checked_mul(unit_nanos)
            .ok_or(ParseDurationError::Overflow)?;
        total_nanos = total_nanos
            .checked_add(component)
            .ok_or(ParseDurationError::Overflow)?;
        if total_nanos / NANOS_PER_SECOND > u128::from(u64::MAX) {
            return Err(ParseDurationError::Overflow);
        }
    }

    if !saw_component {
        return Err(ParseDurationError::Empty);
    }

    Ok(Duration::new(
        (total_nanos / NANOS_PER_SECOND) as u64,
        (total_nanos % NANOS_PER_SECOND) as u32,
    ))
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Errors that can occur while handling parse duration.
pub enum ParseDurationError {
    /// Indicates empty.
    Empty,
    /// The required number is missing.
    MissingNumber {
        #[doc = "The offset value."]
        offset: usize,
    },
    /// The number exceeds the supported size.
    NumberTooLarge,
    /// The unit is invalid.
    InvalidUnit,
    /// Indicates overflow.
    Overflow,
}

impl fmt::Display for ParseDurationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("duration must not be empty"),
            Self::MissingNumber { offset } => {
                write!(
                    formatter,
                    "duration component must start with digits at byte {offset}"
                )
            }
            Self::NumberTooLarge => formatter.write_str("duration number is too large"),
            Self::InvalidUnit => {
                formatter.write_str("duration unit must be one of ns, us, ms, s, m, h, d or w")
            }
            Self::Overflow => formatter.write_str("duration is too large"),
        }
    }
}

impl Error for ParseDurationError {}

impl ClassifyError for ParseDurationError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Empty => "duration_empty",
            Self::MissingNumber { .. } => "duration_missing_number",
            Self::NumberTooLarge => "duration_number_too_large",
            Self::InvalidUnit => "duration_invalid_unit",
            Self::Overflow => "duration_overflow",
        })
    }
}

struct DurationVisitor;

impl de::Visitor<'_> for DurationVisitor {
    type Value = Duration;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a duration string such as 500ms, 30s, 5m, 2h, 7d or 1h30m")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        parse(value).map_err(E::custom)
    }
}

fn duration_unit(value: &str) -> Result<(u128, usize), ParseDurationError> {
    let unit_len = value
        .find(|character: char| character.is_ascii_digit() || character.is_ascii_whitespace())
        .unwrap_or(value.len());
    let nanos = match &value[..unit_len] {
        "ns" => NANOS_PER_NANO,
        "us" | "µs" => NANOS_PER_MICRO,
        "ms" => NANOS_PER_MILLI,
        "s" => NANOS_PER_SECOND,
        "m" => NANOS_PER_MINUTE,
        "h" => NANOS_PER_HOUR,
        "d" => NANOS_PER_DAY,
        "w" => NANOS_PER_WEEK,
        _ => return Err(ParseDurationError::InvalidUnit),
    };

    Ok((nanos, unit_len))
}

fn skip_ascii_whitespace(value: &str, index: &mut usize) {
    while value
        .as_bytes()
        .get(*index)
        .is_some_and(u8::is_ascii_whitespace)
    {
        *index += 1;
    }
}