ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! The CLOCK grammar — `H:MM:SS.fff` — read into nanoseconds, and the one thing `mediatime` writes
//! and cannot read back.
//!
//! `mediatime::Timestamp`'s `Display` renders a clock under `{}` and its `FromStr` accepts only the
//! exact `{:#}` form, and the reason is written on that impl: *the clock is lossy and has no
//! inverse*. It is truncated toward zero at millisecond resolution and it names no timebase, so the
//! string cannot say which instant it was printed from. That is a fact about the RENDERING, and this
//! module does not contradict it — nothing here recovers a `pts` or a timebase.
//!
//! What a clock DOES name exactly is a position on the timeline, in nanoseconds. That is enough to
//! be a BOUND and not enough to be an IDENTITY, which is the whole of why the filters below take one
//! in `gt`/`gte`/`lt`/`lte` and refuse it in `eq`/`ne`/`in`/`notIn`. A bound moved by a fraction of a
//! nanosecond selects the same rows; an identity moved by one selects none.
//!
//! # The grammar, and what each refusal teaches
//!
//! ```text
//!   [-] H+ : MM : SS [ . f{1,9} ]
//!
//!   0:00:00.137     the form mediatime writes
//!   00:01:30.5      a client's own padding and a shorter fraction
//!   123:45:06.789   hours are unbounded; this is a normal rendering
//!   -0:00:01.5      the sign is the whole clock's
//! ```
//!
//! Hours are one or more digits and carry no ceiling — a clock is elapsed time, not a wall time, so
//! `123:45:06` is a real position rather than an overflow. Minutes and seconds are EXACTLY two
//! digits and below sixty, which is what makes the three parts unambiguous: a `1:2:3` that meant one
//! hour, two minutes and three seconds would also read as a badly padded `1:02:03`, and the two
//! spellings would be one string with two meanings if both were admitted.
//!
//! The fraction is one to nine digits, and NINE is the resolution the value lands in: a tenth digit
//! is refused rather than truncated, because a client that wrote one meant it and silently dropping
//! it is a bound that is not the bound they asked for.
//!
//! There is no case folding here and none is missing — the alphabet is digits, a colon, a dot and a
//! sign, none of which has a case. Where `Timebase`'s roster door folds ASCII case because it reads
//! NAMES, this door reads numbers.

//! # What rides the WIRE feature here, and what does not
//!
//! [`nanos`] and [`render`] are the two doors, and both are `async-graphql`'s: a clock is a STRING
//! form, and the only thing in this crate that reads or writes one is an operand scalar. So the
//! grammar compiles where there is a face to spend it on and nowhere else.
//!
//! [`ParseClockError`] is NOT gated with them, and the split is the one the family's ungated
//! operand re-exports already make: a refusal vocabulary is a name a caller MATCHES ON, and an API
//! that changes shape with a wire feature is one a caller has to write two versions of. The enum
//! costs nothing to compile and says the same thing in every build.

use core::fmt;

#[cfg(feature = "async-graphql")]
use smol_bytes::{Utf8Bytes, Utf8BytesMut};

#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// Nanoseconds in one second, as the `i128` the whole sum is accumulated in.
#[cfg(feature = "async-graphql")]
const NANOS_PER_SECOND: i128 = 1_000_000_000;

/// The most fractional digits a clock may carry — the resolution the value lands in.
#[cfg(feature = "async-graphql")]
const FRACTION_DIGITS: usize = 9;

/// A string does not name a clock position.
///
/// One variant per way the grammar can fail, rather than one opaque error, for the reason
/// [`ParseTimebaseError`](super::ParseTimebaseError) has its five: the operand arrives from a
/// client, and which rule it broke is the only part of the answer that says what to send instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseClockError {
  /// The three colon-separated parts are not there — `H:MM:SS` is the shape.
  Shape,
  /// The hours are missing or are not digits.
  Hours,
  /// The minutes are not exactly two digits below sixty.
  Minutes,
  /// The seconds are not exactly two digits below sixty.
  Seconds,
  /// The fraction is empty, is not digits, or is longer than nine of them.
  Fraction,
  /// The position does not fit `i64` nanoseconds, which span about ±292 years.
  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")]
/// A clock position, in nanoseconds.
///
/// Total over the grammar and exact within it: the sum is accumulated in `i128`, where no legal
/// clock can overflow — nine digits of fraction plus sixty seconds plus sixty minutes is bounded,
/// and the hours are the only unbounded part, so the single range check is the one back into `i64`.
///
/// # Errors
///
/// [`ParseClockError`], naming the part or the rule that refused.
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),
  };

  // Parsed as `i128` rather than as `i64`, so a client's hundred-digit hour is a value this function
  // refuses on the RANGE check below rather than one `i64::from_str` refuses on its own — which
  // would report the shape as wrong when it is the magnitude.
  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)?;

  // The fraction is read as a COUNT OF NANOSECONDS by padding it to nine digits rather than by
  // dividing: `.5` is 500 000 000 ns, and reading it as five and scaling would put the decimal point
  // in a place the digits do not have.
  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")]
/// One run of ASCII digits, as `i128`, or [`None`] where the run is empty, holds anything else, or
/// is outside `width`.
///
/// ASCII rather than [`char::is_numeric`], which admits every decimal digit in Unicode — Devanagari,
/// fullwidth, and a dozen more. A clock's `06` and its fullwidth twin are two strings a client could
/// send, and admitting both would make one position have two spellings for no gain.
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")]
/// A nanosecond position rendered back as a clock, at NANOSECOND resolution.
///
/// The inverse of [`nanos`] over this module's own grammar, which `mediatime`'s renderer is not: it
/// truncates at milliseconds, so its output is a clock this door reads and a value it cannot recover.
/// Rendering nine digits here is what makes the round trip exact — and the difference is worth
/// carrying, because a wire face publishing a bound a client cannot send back is a face that lies
/// about its own vocabulary.
///
/// Built directly into a [`Utf8Bytes`]: the widest rendering a `i64` nanosecond count can produce is
/// `-2562047:47:16.854775807`, twenty-four bytes, so all but the most extreme instants stay inside
/// the inline representation and none of them allocates more than once.
#[must_use]
pub fn render(nanos: i64) -> Utf8Bytes {
  let negative = nanos < 0;
  // `unsigned_abs` rather than a negation, which `i64::MIN` has no room for.
  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")]
/// One number, zero-padded to at least `width` digits, written into the buffer without an
/// intermediate `String` — the carrier law, spent at the only place this module builds text.
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]));
  }
}