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
//! A confidence in the closed unit interval: [`Confidence`], the widths it measures in, and the
//! `f32` one this crate has always called [`Score`](crate::Score).

use core::{cmp::Ordering, hash::Hasher};

#[cfg(test)]
mod tests;

/// A confidence or ratio in the closed unit interval `[0.0, 1.0]`, measured in `S`.
///
/// The constructor is the only way in, and it refuses everything outside the interval and every
/// value the carrier admits that is not a number. That refusal is what buys the total order below:
/// with `NaN` excluded, `partial_cmp` never returns `None`, so `Ord` is a fact about the type rather
/// than a convention its users have to keep.
///
/// # The WIDTH is a parameter and the INVARIANT is not
///
/// Every carrier promises the same interval and the same order. What a carrier chooses is how many
/// bits the promise is kept in — `f32` for a detector's own output, `f64` where a fusion has already
/// spent the narrower width, [`half::f16`] where a quantised model emits one, and
/// [`rust_decimal::Decimal`] where the value is a base-ten quantity that no binary float IS. The
/// vocabulary is closed and the reason is [`ConfidenceCarrier`]'s: each member's refusal is a
/// MEASURED argument about that width, not a shape a bound could check.
///
/// [`Score`](crate::Score) is `Confidence<f32>` under the name this crate spent on it before the
/// width was a parameter, and it is an alias rather than a wrapper — the two are one type, so a call
/// site that spells either spells both.
///
/// # Examples
///
/// ```
/// use ingraph::{Confidence, Score};
///
/// assert_eq!(Score::new(0.82).unwrap().get(), 0.82);
/// assert!(Score::new(1.5).is_none());
///
/// // The same interval, one width up.
/// assert_eq!(Confidence::<f64>::ONE.get(), 1.0);
/// ```
///
/// A width outside the vocabulary is refused where it is named, and the note says what the
/// vocabulary is:
///
/// ```compile_fail,E0277
/// fn main() {
///   let _ = ingraph::Confidence::<i32>::ZERO;
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Confidence<S: ConfidenceCarrier>(S);

impl<S: ConfidenceCarrier> Confidence<S> {
  /// The bottom of the interval.
  pub const ZERO: Self = Self(S::ZERO);
  /// The top of the interval.
  pub const ONE: Self = Self(S::ONE);

  /// Construct a confidence, or refuse a value that is not one.
  ///
  /// What is refused and what is normalised on the way through are the CARRIER's, stated once per
  /// width at [`ConfidenceCarrier::admit`] — the interval is the same everywhere and the values that
  /// are not numbers are not.
  #[inline]
  pub fn new(value: S) -> Option<Self> {
    S::admit(value).map(Self)
  }

  /// The wrapped value, always in `[0.0, 1.0]` and never one of the values [`new`](Self::new)
  /// refused.
  #[inline]
  pub const fn get(&self) -> S {
    self.0
  }
}

/// A confidence measured in `f32`, under the name this crate spent on it before the width was a
/// parameter.
///
/// An ALIAS and not a wrapper: `Score` and `Confidence<f32>` are one type, so every row this crate
/// wrote for the first is a row the second has, every call site that spells either spells both, and
/// the `Score` a schema publishes is the `Score` it published before.
///
/// It survives the generalisation rather than being carried by it. A confidence is what the word
/// means in every declaration this framework has seen — a sound-event detection, a face detection, a
/// speaker cluster, a zero-shot tag — and `f32` is the width all four of them measure in.
pub type Score = Confidence<f32>;

// `PartialEq` is derived and `Eq` is not, because the derive would be the wrong statement in one of
// the two cases: a carrier's equality is already the right one here, and its REFLEXIVITY is a
// property of this type rather than of the carrier — `x == x` fails for `NaN` alone, and a
// `Confidence` is never one.
impl<S: ConfidenceCarrier> Eq for Confidence<S> {}

impl<S: ConfidenceCarrier> Ord for Confidence<S> {
  /// Total because [`Confidence::new`] refuses every value the carrier's `partial_cmp` returns
  /// [`None`] for — which for the three IEEE widths is `NaN` and for the decimal is nothing at all.
  #[inline]
  fn cmp(&self, other: &Self) -> Ordering {
    S::admitted_cmp(&self.0, &other.0)
  }
}

impl<S: ConfidenceCarrier> PartialOrd for Confidence<S> {
  #[inline]
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<S: ConfidenceCarrier> core::hash::Hash for Confidence<S> {
  /// The carrier's hash for values it has ADMITTED, which is where the `Hash`/`Eq` contract is kept
  /// — see [`ConfidenceCarrier::hash_admitted`] for what each width has to do to keep it.
  #[inline]
  fn hash<H: Hasher>(&self, state: &mut H) {
    S::hash_admitted(&self.0, state);
  }
}

/// The widths a [`Confidence`] measures in.
///
/// # It is SEALED, and the seal is not caution
///
/// A member is admitted by a MEASUREMENT of that width: which of its values are not numbers, which
/// two of its values compare equal and carry different bits, and whether its own `Hash` already
/// answers for the second. Those are facts about a carrier that this crate checks and pins with a
/// test apiece; a bound cannot check them, so an implementation written outside this crate would be
/// an unchecked promise standing where a checked one is. Extend the set by asking the framework.
///
/// # What each member owes
///
/// [`ZERO`](Self::ZERO) and [`ONE`](Self::ONE) are the interval's ends AT THIS WIDTH, and they are
/// consts rather than a conversion because the endpoints are exactly representable in every carrier
/// here and a conversion would put a rounding question where there is none.
///
/// [`admit`](Self::admit) is the whole of the refusal, and everything below it is stated relative to
/// what it let through: [`admitted_cmp`](Self::admitted_cmp) may be total only because `admit`
/// refused the values that make an order partial, and [`hash_admitted`](Self::hash_admitted) may
/// hash bits only because `admit` left no two equal values with different ones.
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not a width a confidence is measured in",
  label = "not a confidence carrier",
  note = "a confidence measures in `f32` or `f64`, or — under the cargo feature of the same name — \
          in `half::f16` (`half`) or `rust_decimal::Decimal` (`rust_decimal`)",
  note = "the vocabulary is SEALED: a width is admitted by MEASURING which of its values are not \
          numbers and which two of them compare equal while carrying different bits, which an \
          implementation outside this crate cannot establish. Extend the set by asking the \
          framework, not by implementing this trait"
)]
pub trait ConfidenceCarrier: Copy + PartialOrd + core::fmt::Debug + sealed::Sealed {
  /// The bottom of the interval, at this width.
  const ZERO: Self;
  /// The top of the interval, at this width.
  const ONE: Self;

  /// Refuse a value that is not a confidence, and normalise any representation that would otherwise
  /// break the `Hash`/`Eq` contract [`hash_admitted`](Self::hash_admitted) has to keep.
  ///
  /// The interval is the one thing every implementation checks identically. The rest is the width's
  /// own, and each impl below says which of the two clauses it spends and why.
  fn admit(value: Self) -> Option<Self>;

  /// Compare two values [`admit`](Self::admit) let through, TOTALLY.
  ///
  /// It may be total only because of what `admit` refused, which is why it is stated here rather
  /// than asked for as an [`Ord`] bound: `f32`, `f64` and `f16` have no `Ord` to ask for, and the
  /// order this returns is one their admitted values have and their full domains do not.
  fn admitted_cmp(&self, other: &Self) -> Ordering;

  /// Hash a value [`admit`](Self::admit) let through, consistently with `==` over the same values.
  ///
  /// Stated here for the same reason as [`admitted_cmp`](Self::admitted_cmp), and with a sharper
  /// obligation: the three IEEE widths have no `Hash` at all, and the one carrier that does have to
  /// be checked rather than assumed — two values that are `==` and hash differently is the exact
  /// defect this row exists to close.
  fn hash_admitted<H: Hasher>(&self, state: &mut H);
}

/// The seal. Public inside a private module, so the bound is nameable from this crate's own rows and
/// unnameable — hence unimplementable — from outside it.
mod sealed {
  pub trait Sealed {}
}

/// The two IEEE binary widths Rust ships, whose refusal is one argument written at two widths.
///
/// `NaN` and the infinities are refused, and `-0.0` is admitted and NORMALISED to `+0.0`: it
/// satisfies the range check, compares equal to `+0.0`, and carries different bits — so admitting it
/// unchanged would make two equal values hash differently.
///
/// `+ 0.0` is what does the normalising, and it maps `-0.0` to `+0.0` and is the identity everywhere
/// else in the interval.
macro_rules! ieee_carriers {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl sealed::Sealed for $ty {}

      impl ConfidenceCarrier for $ty {
        const ZERO: Self = 0.0;
        const ONE: Self = 1.0;

        #[inline]
        fn admit(value: Self) -> Option<Self> {
          if value.is_nan() || !(0.0..=1.0).contains(&value) {
            return None;
          }
          Some(value + 0.0)
        }

        #[inline]
        fn admitted_cmp(&self, other: &Self) -> Ordering {
          self.partial_cmp(other).expect("a confidence is never NaN")
        }

        #[inline]
        fn hash_admitted<H: Hasher>(&self, state: &mut H) {
          core::hash::Hash::hash(&self.to_bits(), state);
        }
      }
    )+
  };
}

ieee_carriers!(f32, f64);

/// IEEE binary16, and the ONE width here whose refusal is written against the carrier's own
/// comparisons rather than against Rust's literals.
///
/// The clauses are `f32`'s unchanged — `NaN` and the infinities out, `-0.0` normalised — and what
/// changes is how each is spelled. The range is checked against [`ZERO`](ConfidenceCarrier::ZERO)
/// and [`ONE`](ConfidenceCarrier::ONE) because `0.0` and `1.0` are `f64` literals and this width is
/// not one; the normalisation is an EQUALITY rather than an addition because `half`'s arithmetic
/// round-trips through `f32`, and a round trip is a second rounding standing where the whole point
/// is that nothing moves.
///
/// The equality IS the normalisation's argument, and it is the same one `f32` spends: `-0.0 == 0.0`
/// is true, so the branch catches exactly the value whose bits differ from the one it compares equal
/// to, and is the identity everywhere else.
#[cfg(feature = "half")]
impl sealed::Sealed for half::f16 {}

#[cfg(feature = "half")]
impl ConfidenceCarrier for half::f16 {
  const ZERO: Self = half::f16::ZERO;
  const ONE: Self = half::f16::ONE;

  #[inline]
  fn admit(value: Self) -> Option<Self> {
    if value.is_nan() || !(Self::ZERO..=Self::ONE).contains(&value) {
      return None;
    }
    Some(if value == Self::ZERO {
      Self::ZERO
    } else {
      value
    })
  }

  #[inline]
  fn admitted_cmp(&self, other: &Self) -> Ordering {
    self.partial_cmp(other).expect("a confidence is never NaN")
  }

  #[inline]
  fn hash_admitted<H: Hasher>(&self, state: &mut H) {
    core::hash::Hash::hash(&self.to_bits(), state);
  }
}

/// The BASE-TEN width, and the one carrier that spends NEITHER of the float clauses.
///
/// **There is no `NaN` arm and no infinity arm**, and the absence is the type's rather than an
/// omission: [`rust_decimal::Decimal`] has no such values to refuse, which is why this row's `admit`
/// is the interval check alone and why its order is a delegation — `Decimal` is [`Ord`] already, so
/// the totality this trait buys the floats is a fact it arrived with.
///
/// **There is no `-0.0` normalisation either, and here the reason is a MEASUREMENT.** A decimal has
/// a negative zero AND a scale, so `-0` and `0` and `0.00` and `0` are two pairs that compare equal
/// while carrying different bits — a strictly worse position than the floats', where there is only
/// the one pair. `Decimal`'s own `Hash` closes both: it hashes `normalize()`, which strips trailing
/// zeros and converts `-0` to `0`. So the delegation below is the whole of the obligation, and the
/// two pairs are pinned by tests rather than left to the dependency's word.
#[cfg(feature = "rust_decimal")]
impl sealed::Sealed for rust_decimal::Decimal {}

#[cfg(feature = "rust_decimal")]
impl ConfidenceCarrier for rust_decimal::Decimal {
  const ZERO: Self = rust_decimal::Decimal::ZERO;
  const ONE: Self = rust_decimal::Decimal::ONE;

  #[inline]
  fn admit(value: Self) -> Option<Self> {
    (Self::ZERO..=Self::ONE).contains(&value).then_some(value)
  }

  #[inline]
  fn admitted_cmp(&self, other: &Self) -> Ordering {
    Ord::cmp(self, other)
  }

  #[inline]
  fn hash_admitted<H: Hasher>(&self, state: &mut H) {
    core::hash::Hash::hash(self, state);
  }
}