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
//! [`NormCoord`]: a coordinate in the closed unit interval, and the one instantiation of this
//! family's parameter that the crate NAMES.

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

use crate::{
  ColumnKind, CursorValue, DefaultMarker, DefaultVecMarker, ScalarFilterMarker, column::column_eq,
};

#[cfg(test)]
mod tests;

/// **A NORMALIZED COORDINATE** — one axis of a position in the unit square, in `[0.0, 1.0]`.
///
/// An [`f32`] underneath, and a different type for the reason every newtype in
/// [`primitives`](crate::primitives) is one: it carries an INVARIANT its representation cannot
/// state. A coordinate is FINITE and lies in the closed unit interval, so [`new`](Self::new) is the
/// only way in and it refuses everything else. That refusal is what buys the total order below —
/// with `NaN` excluded, `partial_cmp` never answers [`None`], so [`Ord`] is a fact about the type
/// rather than a convention its users have to keep.
///
/// # It is ONE INSTANTIATION and not the family's subject
///
/// [`BoundingBox`](super::BoundingBox), [`Point2`](super::Point2) and [`Quad`](super::Quad) are
/// GENERIC over their component, and this type is one thing a caller may put there. A detector
/// working in the normalized frame writes `BoundingBox<NormCoord>`; a metric one writes
/// `BoundingBox<f64>`; a raster one writes `BoundingBox<u32>` and has no unit square to be checked
/// against. **The openness is the holders', and this is the normalized world's answer to it** — the
/// crate names no other, because naming a metre or a pixel would be naming a UNIT this framework
/// has no reason to hold an opinion about.
///
/// # `-0.0` is admitted and NORMALISED, which is what keeps `Hash` and `Eq` in agreement
///
/// 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` maps it to `+0.0`
/// and is the identity everywhere else in the interval. That is
/// [`Confidence`](crate::Confidence)'s own clause at this width, and it is spent here for the same
/// reason rather than because the two types are one.
///
/// # Why it is not a [`Confidence`](crate::Confidence)
///
/// The two invariants read the same — a finite number in `[0.0, 1.0]` — and the types are
/// deliberately distinct, which is the position [`MediaTimestamp`](crate::MediaTimestamp) holds
/// against [`Timestamp`](crate::Timestamp) one house over. A confidence is a DEGREE OF BELIEF and a
/// coordinate is a POSITION; `BoundingBox<Confidence<f32>>` would be a box of beliefs, and GraphQL's
/// one flat namespace would publish the box's four fields under a name that says a detector's
/// certainty where it means its left edge. The shared interval is a coincidence of arithmetic, not
/// one invariant with two names.
///
/// # Examples
///
/// ```
/// use ingraph::NormCoord;
///
/// assert_eq!(NormCoord::new(0.25).unwrap().get(), 0.25);
/// assert_eq!(NormCoord::ZERO.get(), 0.0);
/// assert_eq!(NormCoord::ONE.get(), 1.0);
///
/// assert!(NormCoord::new(1.5).is_none());
/// assert!(NormCoord::new(-0.1).is_none());
/// assert!(NormCoord::new(f32::NAN).is_none());
/// assert!(NormCoord::new(f32::INFINITY).is_none());
/// ```
///
/// The negative zero is admitted and arrives as the positive one:
///
/// ```
/// use ingraph::NormCoord;
///
/// let signed = NormCoord::new(-0.0).unwrap();
/// assert_eq!(signed, NormCoord::ZERO);
/// assert!(signed.get().is_sign_positive());
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NormCoord(f32);

impl NormCoord {
  /// The near edge — the left of the frame, or its top.
  pub const ZERO: Self = Self(0.0);
  /// The far edge — the right of the frame, or its bottom.
  pub const ONE: Self = Self(1.0);

  /// Construct a coordinate, or refuse a value that is not one.
  ///
  /// Refuses `NaN`, both infinities and everything outside `[0.0, 1.0]`; admits `-0.0` and hands
  /// back `+0.0`, for the reason the type's note gives.
  #[inline]
  #[must_use]
  pub fn new(value: f32) -> Option<Self> {
    if value.is_nan() || !(0.0..=1.0).contains(&value) {
      return None;
    }
    Some(Self(value + 0.0))
  }

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

/// The coordinate, as the plain number.
///
/// ONE direction, and the missing one is the type's whole subject: `From<f32> for NormCoord` would
/// say that any float IS a coordinate, which is exactly the claim this newtype exists to stop being
/// made silently. Minting one is [`NormCoord::new`], where the caller meets the refusal.
impl From<NormCoord> for f32 {
  #[inline]
  fn from(value: NormCoord) -> Self {
    value.0
  }
}

/// The widening every consumer that measures in doubles reaches for, and it is EXACT: every `f32`
/// is an `f64`, so nothing about the value moves and the interval is preserved by construction.
impl From<NormCoord> for f64 {
  #[inline]
  fn from(value: NormCoord) -> Self {
    f64::from(value.0)
  }
}

// `PartialEq` is derived and `Eq` is not, for `Confidence`'s reason: `f32`'s equality is already the
// right one here, and its REFLEXIVITY is a property of THIS type rather than of the float — `x == x`
// fails for `NaN` alone, and a coordinate is never one.
impl Eq for NormCoord {}

impl Ord for NormCoord {
  /// Total because [`NormCoord::new`] refuses every value `f32`'s `partial_cmp` answers [`None`]
  /// for, which is `NaN` and nothing else.
  #[inline]
  fn cmp(&self, other: &Self) -> Ordering {
    self
      .0
      .partial_cmp(&other.0)
      .expect("a coordinate is never NaN")
  }
}

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

impl core::hash::Hash for NormCoord {
  /// The BITS, which is contract-safe only because [`new`](NormCoord::new) left no two equal values
  /// carrying different ones — `-0.0` is the single such pair at this width and it is normalised
  /// away at construction.
  #[inline]
  fn hash<H: Hasher>(&self, state: &mut H) {
    core::hash::Hash::hash(&self.0.to_bits(), state);
  }
}

impl core::fmt::Display for NormCoord {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    core::fmt::Display::fmt(&self.0, f)
  }
}

/// **THE ONE ARITHMETIC THE UNIT INTERVAL IS CLOSED UNDER**, and the whole reason this row exists is
/// [`BoundingBox::area`](super::BoundingBox::area).
///
/// A product of two values in `[0.0, 1.0]` is in `[0.0, 1.0]` — the true product is at most either
/// factor, rounding to nearest is monotone, `1.0` is representable, and neither factor can be `NaN`
/// or an infinity — so this operator is TOTAL and the [`new`](Self::new) below it never refuses. The
/// `expect` is a proof obligation discharged by the constructor that refused every value which could
/// break it, which is [`BoundingBox::right`](super::BoundingBox::right)'s own arrangement one door
/// over.
///
/// # WHY NO `Add`, `Sub` OR `Div` FOLLOW IT — the census, stated where a reader will look
///
/// **None of the other three is closed on this interval**, and the type will not publish an operator
/// that leaves its own domain. `0.6 + 0.7` is `1.3`, `0.2 - 0.8` is `-0.6`, `0.5 / 0.1` is `5.0`;
/// each would have to panic, saturate or clamp, and a coordinate that quietly became `ZERO` because
/// somebody subtracted in the wrong order is precisely the *value minted around the hole* this
/// house's decode refuses one screen down.
///
/// The visible consequence is [`Quad::bounds`](super::Quad::bounds), whose extents are `max - min`
/// and which is therefore bounded on a component whose subtraction is total: `f32`, `f64`, a pixel
/// width, a downstream newtype that says so — and NOT this type. That is out of bounds rather than
/// refused, and it is recorded at that method.
///
/// # It is a POSITION and a product of two of them is not one, which is the pun this row admits
///
/// Stated rather than hidden: multiplying two COORDINATES means nothing, and what is multiplied at
/// the one call site is two EXTENTS — a width and a height, both measured as fractions of the frame,
/// whose product is the fraction of the frame the rectangle covers. So the operator is honest about
/// its arithmetic and narrow about its meaning, and the meaning is documented at
/// [`BoundingBox::area`](super::BoundingBox::area) where it is spent.
///
/// # Examples
///
/// ```
/// use ingraph::NormCoord;
///
/// let half = NormCoord::new(0.5).unwrap();
/// assert_eq!((half * half).get(), 0.25);
/// assert_eq!((NormCoord::ONE * half).get(), 0.5);
/// assert_eq!((NormCoord::ZERO * half).get(), 0.0);
/// ```
impl Mul for NormCoord {
  type Output = Self;

  #[inline]
  fn mul(self, rhs: Self) -> Self {
    Self::new(self.0 * rhs.0)
      .expect("the closed unit interval is closed under multiplication at every width")
  }
}

/// **A SCALAR joins by stating NOTHING** — one column, wherever it is stored.
///
/// The empty segment list is [`ColumnKind`]'s default and this row spells it anyway, because the
/// three holders above are guarded by a leaf assertion read off exactly this const: a component
/// that came to span two columns would break their fixed arity, and the row a reader checks that
/// against should be the type's own rather than a default they have to know about.
impl ColumnKind for NormCoord {}

// A coordinate is the same as a coordinate when its bits are — `-0.0` is normalised to `+0.0` at
// construction, so this type's own derived `PartialEq` already agrees with its `Hash`.
column_eq! { NormCoord }

/// **THE STORED WORD is the float's**, in every dialect that has one.
///
/// A coordinate is an `f32` in the column and a `NormCoord` in the row, and the interval is kept by
/// the DECODE rather than by the schema — no dialect here has a `CHECK` this crate emits, so the
/// promise is enforced where a value crosses back in. See the assemble row below, which refuses.
impl<Db> crate::StoredAs<Db> for NormCoord
where
  f32: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = <f32 as crate::StoredAs<Db>>::WORDS;
}

/// **ONE BIND OUT** — the float, delegated.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for NormCoord
where
  Db: sqlx::Database,
  f32: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <f32 as crate::Carrier<Db>>::push_bind(&self.0, qb);
  }
}

/// **AND THE VALUE BACK IN**, through the constructor rather than around it.
///
/// A database is exactly the place that can hand back a number this type says cannot exist — a
/// hand-written `UPDATE`, a restore, a column shared with something else — so the read refuses
/// rather than clamping into range. That is [`Count`](crate::Count)'s posture at its own column and
/// [`MediaTimeRange`](crate::MediaTimeRange)'s at its pair: loudly, at the row that holds it, never
/// a value quietly minted around the hole.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for NormCoord
where
  f32: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let stored = <f32 as crate::Assemble<'a, R>>::assemble(row, under)?;

    Self::new(stored).ok_or_else(|| sqlx::Error::Decode(Box::new(OutsideTheUnitInterval)))
  }
}

/// **THE KEYSET POSITION** — the float's own bytes, and the order they sort in is the order the
/// values have.
///
/// [`f32`]'s row is what encodes it, and a coordinate inherits the encoding rather than restating
/// it: the two are one number, and a second spelling here is a second thing to keep in agreement.
impl CursorValue for NormCoord {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.0, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    // The interval is checked here as it is at the decode: a cursor is a string a CLIENT hands
    // back, so a forged one must not become a coordinate the type says cannot exist.
    <f32 as CursorValue>::read_cursor(bytes).and_then(Self::new)
  }
}

/// **THE ADMISSION** — a coordinate is one element of one.
///
/// `Vec<NormCoord>` is a polyline's x's, a histogram's bin edges, a sampling grid. Nothing about
/// the value refuses a list of them, and the row that says so is one line.
impl crate::CollectionElement for NormCoord {}

/// **The SCALAR reading**, which is what a total order earns.
///
/// A coordinate has `gt`/`gte`/`lt`/`lte` that mean what they say — *the left edge is past the
/// midline* is a question — so it takes the uniform [`ScalarFilter`](crate::ScalarFilter) rather
/// than a kind of its own. The INTERVAL is not restated as a filter word: an operand outside it is
/// refused at the crossing below, which is where a value becomes this type.
impl ScalarFilterMarker for NormCoord {
  type Filter = crate::ScalarFilter<Self>;
}

impl DefaultMarker for NormCoord {
  type Marker = crate::ScalarMarker<Self>;
}

impl DefaultVecMarker for NormCoord {
  type Marker = crate::ListMarker<Vec<Self>>;
}

/// **THE CROSSING IN — a coordinate arrives as the roster's own `f32`**, and the interval is kept
/// HERE.
///
/// No `#[Scalar]` of its own, and the absence is the [`Score`](crate::Score) retirement's ruling
/// rather than an omission: a named scalar has to say something the roster does not, and what a
/// `NormCoord` scalar would have said is the INTERVAL — a constructor's promise rather than a
/// grammar, which a client can act on nowhere. So a coordinate column and a plain `f32` column
/// publish one SDL scalar, the interval reaches a reader through the FIELD's documentation, and
/// every operand reaches it through [`NormCoord::new`], which this row calls.
#[cfg(feature = "async-graphql")]
impl crate::ToGraphqlInput for NormCoord {
  type Input = crate::F32;
  type Error = OutsideTheUnitInterval;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Self::new(input.into()).ok_or(OutsideTheUnitInterval)
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    Self::Input::from(operand.0)
  }
}

/// **AND OUT**, mirroring the row above so the two directions cannot come to disagree.
///
/// BY VALUE rather than by reference, which is the carrier shape and costs a register move: a
/// coordinate is [`Copy`].
#[cfg(feature = "async-graphql")]
impl crate::ToGraphqlOutput for NormCoord {
  type Output<'a> = crate::F32;

  #[inline]
  fn to_graphql_output(marked: &Self) -> Self::Output<'_> {
    crate::F32::from(marked.0)
  }
}

/// **What a coordinate refuses a value with** — one sentence, at the two doors that mint one from
/// the outside: a stored column and a wire operand.
///
/// It carries no value, which is [`OutsideTheInterval`](crate::OutsideTheInterval)'s own shape and
/// its reason: what is wrong is a property of the number the caller already has in hand, and a copy
/// of it here would be a second spelling of the same digits. The COLUMN's name arrives with the
/// [`sqlx::Error::ColumnDecode`] this is wrapped in, and a wire operand travels back to a client in
/// async-graphql's own error context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutsideTheUnitInterval;

impl core::fmt::Display for OutsideTheUnitInterval {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(
      "a normalized coordinate is a finite number in the closed unit interval `[0.0, 1.0]`",
    )
  }
}

impl core::error::Error for OutsideTheUnitInterval {}