ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The WIDE duration grammar — the second grammar [`parse`](super::parse) consults, and the
//! normalization table it is built on.
//!
//! **This table is `ingraph`'s, character for character from the first constant below.** The two
//! crates cannot share one copy — `ingraph-codegen` is what `ingraph`'s derive expands through and
//! an edge back would be a cycle in the build order that matters — so the copy is PINNED instead:
//! `ingraph-derive`'s `duration_parity` suite reads both files and refuses a byte of drift, and
//! reads the same corpus through both entries. The ruling that put a duration parser here is
//! explicit that the two sides speak ONE grammar; a second copy with its own opinions is exactly
//! what it forbids.
//!
//! The note the original carries, verbatim in substance: [`jiff::SignedDuration`] declines `d`,
//! `w`, `month` and `y`, because none of them has a fixed length without a reference date. Those
//! units are answered here by a table this framework OWNS and states, and the sub-day rows are here
//! too because the wide grammar reads a WHOLE STRING — `1s 1h` and `1d 1hrs` both arrive, the first
//! because jiff requires descending order and the second because jiff stops at the day.

use core::time::Duration;

/// A day, exactly — 24 hours is what `1d` means here, not what a calendar day always is.
const SECONDS_PER_DAY: u64 = 86_400;
/// A week, exactly seven days.
const SECONDS_PER_WEEK: u64 = 7 * SECONDS_PER_DAY;
/// A month as a FIXED AVERAGE of 30.44 days — **a convenience, not calendar arithmetic**.
const SECONDS_PER_MONTH: u64 = 2_630_016;
/// A year as a FIXED AVERAGE of 365.25 days — **a convenience, not calendar arithmetic**.
const SECONDS_PER_YEAR: u64 = 31_557_600;

/// One unit of the wide grammar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Unit {
  Nanosecond,
  Microsecond,
  Millisecond,
  Second,
  Minute,
  Hour,
  Day,
  Week,
  Month,
  Year,
}

impl Unit {
  /// **THE NORMALIZATION TABLE** — every spelling this grammar admits, and nothing else.
  ///
  /// Case is not normalised on the way in, which is what makes `M` a MONTH and `m` a minute. That
  /// is the sharpest edge in the grammar and it is deliberate: normalising the case would make one
  /// of the two unreachable, and both are spellings callers already send.
  ///
  /// The list is exhaustive rather than illustrative. A spelling absent from it is an error even
  /// when jiff would have read it — see the module note on why the two vocabularies differ.
  fn from_spelling(spelling: &str) -> Option<Self> {
    Some(match spelling {
      "ns" | "nsec" | "nanos" => Self::Nanosecond,
      "us" | "µs" | "usec" => Self::Microsecond,
      "ms" | "msec" | "millis" => Self::Millisecond,
      "s" | "sec" | "secs" | "second" | "seconds" => Self::Second,
      "m" | "min" | "mins" | "minute" | "minutes" => Self::Minute,
      "h" | "hr" | "hrs" | "hour" | "hours" => Self::Hour,
      "d" | "day" | "days" => Self::Day,
      "w" | "wk" | "wks" | "week" | "weeks" => Self::Week,
      "M" | "month" | "months" => Self::Month,
      "y" | "yr" | "yrs" | "year" | "years" => Self::Year,
      _ => return None,
    })
  }

  /// `count` whole units, as (seconds, nanoseconds).
  ///
  /// CHECKED: a count that does not fit refuses rather than wrapping, and the caller turns that
  /// into jiff's own refusal.
  fn whole(self, count: u64) -> Option<(u64, u64)> {
    Some(match self {
      Self::Nanosecond => (0, count),
      Self::Microsecond => (0, count.checked_mul(1_000)?),
      Self::Millisecond => (0, count.checked_mul(1_000_000)?),
      Self::Second => (count, 0),
      Self::Minute => (count.checked_mul(60)?, 0),
      Self::Hour => (count.checked_mul(3_600)?, 0),
      Self::Day => (count.checked_mul(SECONDS_PER_DAY)?, 0),
      Self::Week => (count.checked_mul(SECONDS_PER_WEEK)?, 0),
      Self::Month => (count.checked_mul(SECONDS_PER_MONTH)?, 0),
      Self::Year => (count.checked_mul(SECONDS_PER_YEAR)?, 0),
    })
  }

  /// `numerator/denominator` of one unit, as (seconds, nanoseconds).
  ///
  /// EXACT DIVISION ONLY, so `0.25d` is six hours and `0.3month` is an error rather than a rounded
  /// month. Refusing beats rounding here because the value a filter compares against would
  /// otherwise depend on how many digits the caller happened to write.
  ///
  /// A fractional NANOSECOND has nowhere to go and is refused for that reason.
  fn fraction(self, numerator: u64, denominator: u64) -> Option<(u64, u64)> {
    /// The quotient when it is exact, and nothing when it is not.
    fn exact(value: u64, denominator: u64) -> Option<u64> {
      value
        .is_multiple_of(denominator)
        .then(|| value / denominator)
    }

    Some(match self {
      Self::Nanosecond => return None,
      Self::Microsecond => (0, exact(numerator.checked_mul(1_000)?, denominator)?),
      Self::Millisecond => (0, exact(numerator.checked_mul(1_000_000)?, denominator)?),
      Self::Second => (
        0,
        exact(numerator.checked_mul(1_000_000_000)?, denominator)?,
      ),
      Self::Minute => (
        0,
        exact(numerator.checked_mul(60_000_000_000)?, denominator)?,
      ),
      Self::Hour => (exact(numerator.checked_mul(3_600)?, denominator)?, 0),
      Self::Day => (
        exact(numerator.checked_mul(SECONDS_PER_DAY)?, denominator)?,
        0,
      ),
      Self::Week => (
        exact(numerator.checked_mul(SECONDS_PER_WEEK)?, denominator)?,
        0,
      ),
      Self::Month => (
        exact(numerator.checked_mul(SECONDS_PER_MONTH)?, denominator)?,
        0,
      ),
      Self::Year => (
        exact(numerator.checked_mul(SECONDS_PER_YEAR)?, denominator)?,
        0,
      ),
    })
  }
}

/// Read `text` in the wide grammar — `None` when no spelling of it admits the string.
///
/// The refusal carries no message on purpose. The caller already holds jiff's, which names the unit
/// it refused and where, and that is the one a client sees; a second message here would only have
/// to be chosen between.
pub(super) fn parse(text: &str) -> Option<Duration> {
  // A bare `0` is the one string with no unit that means something, and jiff does not take it. It
  // is a special case in the grammar rather than an oversight in the table: `00` is refused, and so
  // is every other unitless number.
  if text == "0" {
    return Some(Duration::ZERO);
  }
  Scan {
    rest: text.chars(),
    text,
  }
  .run()
}

/// Where a number has to begin, this is what was found there.
enum Start {
  /// The first digit of a count; the rest of its digits follow.
  Digit(u64),
  /// The text ran out, which ends the parse rather than failing it.
  End,
}

/// A cursor over the text, carrying the offsets a unit spelling is sliced out by.
struct Scan<'a> {
  rest: core::str::Chars<'a>,
  text: &'a str,
}

impl Scan<'_> {
  /// The byte offset of the next character to be read.
  fn offset(&self) -> usize {
    self.text.len() - self.rest.as_str().len()
  }

  /// Skip whitespace to the first digit of the next count.
  fn start(&mut self) -> Option<Start> {
    for c in self.rest.by_ref() {
      match c {
        '0'..='9' => return Some(Start::Digit(u64::from(c.to_digit(10)?))),
        c if c.is_whitespace() => {}
        // A sign belongs to jiff's grammar and never reaches this one, which is why `-1d` is an
        // error where `-30m` is a value.
        _ => return None,
      }
    }
    Some(Start::End)
  }

  /// One `count`, `unit` component after another, summed.
  ///
  /// Whitespace is skipped wherever it falls — inside the number, between the number and its unit,
  /// between components — so `1 d`, `1d` and `1  d ` are one value written three ways.
  fn run(mut self) -> Option<Duration> {
    let Start::Digit(mut count) = self.start()? else {
      // Empty, or nothing but whitespace.
      return None;
    };
    let mut total = Duration::ZERO;

    'component: loop {
      let mut fraction = None;
      let mut offset = self.offset();

      // The count's remaining digits, up to whatever ends them.
      while let Some(c) = self.rest.next() {
        match c {
          '0'..='9' => {
            let digit = u64::from(c.to_digit(10)?);
            count = count.checked_mul(10)?.checked_add(digit)?;
          }
          '.' => {
            fraction = Some(self.fraction(&mut offset)?);
            break;
          }
          c if c.is_whitespace() => {}
          'a'..='z' | 'A'..='Z' | 'µ' => break,
          _ => return None,
        }
        offset = self.offset();
      }

      // The unit spelling, which ends at whitespace, at a digit, or at the end of the text. A digit
      // ends this component and OPENS the next one without a separator, so `1d2h` needs none.
      let start = offset;
      let mut offset = self.offset();
      while let Some(c) = self.rest.next() {
        match c {
          '0'..='9' => {
            Self::add(&mut total, self.text.get(start..offset)?, count, fraction)?;
            count = u64::from(c.to_digit(10)?);
            continue 'component;
          }
          c if c.is_whitespace() => break,
          'a'..='z' | 'A'..='Z' | 'µ' => {}
          _ => return None,
        }
        offset = self.offset();
      }

      Self::add(&mut total, self.text.get(start..offset)?, count, fraction)?;
      match self.start()? {
        Start::Digit(next) => count = next,
        Start::End => return Some(total),
      }
    }
  }

  /// The digits after a decimal separator, as `(numerator, denominator)`.
  ///
  /// Leading zeros grow the denominator alone, so `0.05h` is five hundredths and not five tenths.
  /// `offset` is advanced to where the unit spelling begins, which is what the caller slices from.
  fn fraction(&mut self, offset: &mut usize) -> Option<(u64, u64)> {
    let mut numerator = 0u64;
    let mut denominator = 1u64;
    let mut leading_zeros = true;

    while let Some(c) = self.rest.next() {
      match c {
        '0' => {
          denominator = denominator.checked_mul(10)?;
          if !leading_zeros {
            numerator = numerator.checked_mul(10)?;
          }
        }
        '1'..='9' => {
          leading_zeros = false;
          denominator = denominator.checked_mul(10)?;
          let digit = u64::from(c.to_digit(10)?);
          numerator = numerator.checked_mul(10)?.checked_add(digit)?;
        }
        c if c.is_whitespace() => {}
        'a'..='z' | 'A'..='Z' | 'µ' => break,
        _ => return None,
      }
      *offset = self.offset();
    }

    // A separator with no digits behind it — `1.` — is not a number.
    (denominator != 1).then_some((numerator, denominator))
  }

  /// Resolve `spelling` in the table and fold that much time into `total`.
  fn add(
    total: &mut Duration,
    spelling: &str,
    count: u64,
    fraction: Option<(u64, u64)>,
  ) -> Option<()> {
    let unit = Unit::from_spelling(spelling)?;

    let (secs, nanos) = unit.whole(count)?;
    *total = accumulate(*total, secs, nanos)?;

    if let Some((numerator, denominator)) = fraction {
      let (secs, nanos) = unit.fraction(numerator, denominator)?;
      *total = accumulate(*total, secs, nanos)?;
    }

    Some(())
  }
}

/// Add `(secs, nanos)` to a running total, carrying whole seconds out of the nanoseconds.
///
/// The carry is taken at a full second rather than PAST one, which is the one place this grammar
/// deliberately differs from the parser it replaced: carrying only past a second leaves exactly
/// `1_000_000_000` nanoseconds for `Duration::new` to normalise, and `Duration::new` PANICS instead
/// when the second it carries is one the total cannot hold. Every value either way is identical;
/// what changes is that the unreachable-looking corner refuses like the rest of the grammar rather
/// than aborting the process.
fn accumulate(total: Duration, secs: u64, nanos: u64) -> Option<Duration> {
  let mut secs = secs;
  let mut nanos = u64::from(total.subsec_nanos()).checked_add(nanos)?;
  if nanos >= 1_000_000_000 {
    secs = secs.checked_add(nanos / 1_000_000_000)?;
    nanos %= 1_000_000_000;
  }
  let secs = total.as_secs().checked_add(secs)?;
  Some(Duration::new(secs, u32::try_from(nanos).ok()?))
}