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 framework's CARDINALITY: [`Count`], and the refusal a stored one that is not a count earns.

#[cfg(test)]
mod tests;

/// **HOW MANY — a cardinality, and the currency every count in this framework is answered in.**
///
/// A [`u64`] underneath, and a different type on purpose. What the newtype adds is an INVARIANT its
/// representation cannot state: *a cardinality counts rows that EXIST*, so it is bounded by the
/// physical store — no database holds 2^63 rows, and no walk this framework makes produces a count
/// that is not a length of something already in memory. **Its dialect crossings are allowed to spend
/// that invariant, which is exactly what a bare `u64`'s crossings must not.**
///
/// That one sentence is the whole difference, and it is why this type exists rather than an sqlx
/// `Encode` row for `u64`. A bare `u64` is an ARBITRARY 64-bit magnitude — a hash, a file offset, an
/// id minted by something else — and the top half of its range is ordinary traffic, so narrowing one
/// into an `i64` is a value silently lost. That is why `u64` has no SQLite or PostgreSQL carrier at
/// all and why [`BeU64`](crate::BeU64) is the escape a `u64` column declares.
/// A `Count` is not arbitrary. It is bounded by a fact about the machine, so the same narrowing
/// crosses no information at all — and the saturating arm below is DOCUMENTED UNREACHABLE rather
/// than merely improbable.
///
/// # Its per-dialect knowledge lives in its CARRIER ROWS, which is where every type's does
///
/// There is no new trait here and no associated type threaded through the fold contract. A `Count`
/// column is `Count` in every dialect — the width is one — and each backend's family states how one
/// binds:
///
/// | dialect | stored as | the crossing |
/// |---|---|---|
/// | MySQL | `BIGINT UNSIGNED` | native, identity — the value is the column |
/// | SQLite | `INTEGER` | [`to_signed`](Self::to_signed), saturating; [`from_signed`](Self::from_signed) on the way back |
/// | PostgreSQL | `int8` | the same pair |
/// | MongoDB | `Int64` | [`to_signed`](Self::to_signed), the same authority |
///
/// One codec and it belongs to the type, which is [`BeU64::to_blob`](crate::BeU64::to_blob)'s own
/// law one house over: four families each writing `i64::try_from(…)` into their own row would be
/// four encodings that agree today and are free to stop.
///
/// # A NEGATIVE stored value is a CORRUPT ROW, and it is refused by name
///
/// Nothing that wrote through [`to_signed`](Self::to_signed) can produce one — the narrowing
/// saturates at [`i64::MAX`] and has no negative arm — so a negative column is a row this code did
/// not write: a hand-edited database, a column shared with something else, a bit flip. The read
/// refuses it as [`NegativeCount`] rather than clamping to zero or reinterpreting the bits, which is
/// `NonZeroColumnError`'s own posture one type over: loudly, at the row that holds it, never a value
/// quietly minted around the hole.
///
/// # The API is what has been ASKED FOR, and no arithmetic suite stands beside it
///
/// A count is produced by a fold and read back out of a column. It is not added to, not multiplied,
/// and not counted down — so there is no `Add`, no `Sum` and no `checked_*` family here. The day one
/// is demanded it is one impl; a suite written ahead of the demand is a surface with no caller to
/// hold it honest, which is the rule the module above grows by.
///
/// # Examples
///
/// ```
/// use ingraph::Count;
///
/// let tracks = Count::new(3);
/// assert_eq!(tracks.get(), 3);
/// assert_eq!(u64::from(tracks), 3);
/// ```
///
/// The stored form is signed, and the saturation is the arm no count reaches:
///
/// ```
/// use ingraph::Count;
///
/// assert_eq!(Count::new(7).to_signed(), 7);
/// assert_eq!(Count::new(u64::MAX).to_signed(), i64::MAX);
/// assert_eq!(Count::from_signed(7), Ok(Count::new(7)));
/// assert!(Count::from_signed(-1).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Count(u64);

impl Count {
  /// The cardinality `value` names.
  ///
  /// `const` and total: every [`u64`] is a count of something, and what this type promises is about
  /// where the value CAME FROM rather than which values it admits — see the type's own note.
  #[inline]
  #[must_use]
  pub const fn new(value: u64) -> Self {
    Self(value)
  }

  /// How many.
  #[inline]
  #[must_use]
  pub const fn get(self) -> u64 {
    self.0
  }

  /// **The stored form on every dialect with no unsigned 64-bit column** — this count as an
  /// [`i64`], SATURATING at [`i64::MAX`].
  ///
  /// # The saturating arm is UNREACHABLE, and that is the ruling this type carries
  ///
  /// A count past `i64::MAX` would be a group holding more than 9,223,372,036,854,775,807 rows,
  /// which no store this framework writes to holds and no machine this framework runs on could have
  /// enumerated — the fold's own answer is a slice's length, and a slice lives in memory. So the
  /// conversion loses nothing, and the arm is written rather than cast for the reason every
  /// narrowing in this crate is: a cast that truncates silently is the failure mode this crate
  /// refuses everywhere, and it saturates rather than panicking because the caller is a WRITE — an
  /// aggregate that aborted an upsert over an impossibility would stop answering forever.
  ///
  /// The same form [`Counting`](crate::Counting)'s fold narrows a slice length with, one direction
  /// over and for the same reason.
  #[inline]
  #[must_use]
  pub fn to_signed(self) -> i64 {
    i64::try_from(self.0).unwrap_or(i64::MAX)
  }

  /// The count `stored` holds, or [`NegativeCount`] where the column holds a value no write of this
  /// framework's could have put there.
  ///
  /// The other half of [`to_signed`](Self::to_signed), so the encoding is a ROUND TRIP rather than a
  /// one-way bind helper — [`BeU64::from_blob`](crate::BeU64::from_blob)'s own argument, and what
  /// makes the pair testable as one.
  ///
  /// # Errors
  ///
  /// [`NegativeCount`] when `stored` is below zero. See the type's note: nothing this framework
  /// writes can produce one.
  #[inline]
  pub fn from_signed(stored: i64) -> Result<Self, NegativeCount> {
    u64::try_from(stored)
      .map(Self)
      .map_err(|_| NegativeCount { stored })
  }
}

/// The count, as the plain magnitude — [`get`](Count::get) in the spelling a generic caller writes.
///
/// ONE direction, and the missing one is the type's whole subject: `From<u64> for Count` would say
/// that any 64-bit magnitude IS a cardinality, which is exactly the claim this newtype exists to
/// stop being made silently. Minting one is [`Count::new`], where the caller writes the word.
impl From<Count> for u64 {
  #[inline]
  fn from(value: Count) -> Self {
    value.0
  }
}

/// **Why a stored column is not a cardinality** — the read-path refusal a [`Count`] column makes,
/// and the only value it has to make one about.
///
/// It carries the value it refused, because that value is the evidence: a reader looking at a
/// corrupt row wants to know what was in it, and the column's own NAME arrives with the
/// `sqlx::Error::ColumnDecode` this is wrapped in. `NonZeroColumnError` carries nothing for the
/// opposite reason — there is only one value it can be about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NegativeCount {
  stored: i64,
}

impl NegativeCount {
  /// The value the column held.
  #[inline]
  #[must_use]
  pub const fn stored(&self) -> i64 {
    self.stored
  }
}

impl core::fmt::Display for NegativeCount {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "the stored value is {}, and a cardinality is never negative: this code did not write that \
       row, its own narrowing saturating at i64::MAX",
      self.stored
    )
  }
}

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