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 collection ELEMENT codec: [`JsonElement`], and the canonical array a collection operand
//! binds as.
//!
//! # Why a collection operand is not a list of binds
//!
//! Every other kind's operands are values in a column's own type, and [`Carrier`](super::Carrier)
//! binds each one. A collection operand is not: `encloses: [a, b, c]` asks whether a STORED
//! COLLECTION contains a set, which is a question about the column's elements rather than about the
//! column, and no dialect answers it by comparing a placeholder. Each of them decomposes both sides
//! instead — SQLite with `json_each`, Postgres with `jsonb`'s `@>`, MySQL with `JSON_CONTAINS` — and
//! all three read the operand as ONE JSON value.
//!
//! So a SQL engine stores a collection column as a JSON array string, and an operand is encoded the
//! same way and bound once. That settles the question a slice-shaped operand would otherwise raise:
//!
//! - **No array bind is needed anywhere.** `push_bind(&[T])` is `E0277` on Postgres without a
//!   `PgHasArrayType` row and does not exist at all on SQLite, and neither matters — nothing here
//!   binds a slice.
//! - **The bind count is independent of the operand's LENGTH.** One bind per operator, two for the
//!   unordered whole-collection equality that binds each direction of a mutual containment. The
//!   65535 / 32766 ceilings are unreachable from this kind, where an `IN` list of the same size
//!   would spend one bind per element.
//!
//! The price is that both sides have to agree on the encoding, which is why this is a TRAIT with one
//! canonical writer rather than a `to_string` per type: the same tokens a stored column is written
//! with are the tokens an operand compares against, and `json_each` value equality is exact only if
//! they match.
//!
//! # It is infallible, and that is the architecture rather than a simplification
//!
//! `legacy/ingraph`'s writer returns a `Result`, because a `jiff::Timestamp` element had no JSON
//! rendering and was refused while lowering. Here an element type without a rendering has no impl,
//! so the same case is an unsatisfied bound naming the type — and a `Timestamp` COLUMN reaches its
//! comparison as the `i64` its declared converter produced, which has one. The refusal moved to the
//! crossing with everything else.

/// One collection ELEMENT's canonical JSON token.
///
/// Public, and for the reason [`Carrier`](super::Carrier) is: a downstream element type joins the
/// collection vocabulary by implementing it, and both column-stored collection kinds are already
/// generic over the element.
///
/// The precision rule is this crate's rather than JSON's. A JSON number is a double, so the widths
/// that lose exactness past 2^53 — `u64`, `u128`, `i128` — render as decimal STRINGS, and bytes
/// render as lowercase hex. A token that round-trips through a JSON parser unchanged is what makes
/// element equality exact on every engine.
pub trait JsonElement {
  /// Append this value's canonical JSON token to `out`.
  ///
  /// A `String` where the render path takes [`Backend::Buffer`](crate::Backend::Buffer), and the
  /// two are the same rule rather than two conventions: this token is an OPERAND — [`json_elements`]
  /// returns the value a leaf binds — and an operand is a `String` because that is what binds, where
  /// an identifier is SQL text and takes the buffer a backend renders text into. It is the split
  /// `dialect`'s note already draws for [`like_pattern`](super::like_pattern).
  ///
  /// The buffer could not follow the render path in any case: every numeric row below writes through
  /// [`core::fmt::Write`], which smol-bytes 0.1 implements for `BytesMut` and not for
  /// `Utf8BytesMut`, and which the type exposes no `&mut` inner buffer to reach around.
  fn push_json(&self, out: &mut String);
}

/// A borrowed element encodes exactly as the owned one does — the same arrangement
/// [`Carrier`](super::Carrier) has, and what makes `SqlListComparison<&'a T, Db>` a real type.
impl<T: JsonElement + ?Sized> JsonElement for &T {
  #[inline]
  fn push_json(&self, out: &mut String) {
    T::push_json(self, out);
  }
}

/// Render an element slice as a canonical JSON array — the WHOLE of a collection operand's encoding,
/// and the single value each dialect's leaf binds.
pub fn json_elements<T: JsonElement>(items: &[T]) -> String {
  let mut out = String::from("[");
  for (i, item) in items.iter().enumerate() {
    if i > 0 {
      out.push(',');
    }
    item.push_json(&mut out);
  }
  out.push(']');
  out
}

/// A JSON string token, with the six escapes JSON requires and a `\u00xx` for every other control
/// character. Nothing else is escaped: a JSON string carries UTF-8 as it stands.
fn push_json_string(out: &mut String, text: &str) {
  use core::fmt::Write;

  out.push('"');
  for ch in text.chars() {
    match ch {
      '"' => out.push_str("\\\""),
      '\\' => out.push_str("\\\\"),
      '\n' => out.push_str("\\n"),
      '\r' => out.push_str("\\r"),
      '\t' => out.push_str("\\t"),
      // Writing into a `String` cannot fail — `core::fmt::Write for String` returns `Ok` always —
      // so the unreachable error is discarded rather than propagated into this trait's signature.
      ch if (ch as u32) < 0x20 => {
        let _ = write!(out, "\\u{:04x}", ch as u32);
      }
      ch => out.push(ch),
    }
  }
  out.push('"');
}

/// A byte string as a lowercase hex JSON string — escape-free by construction, so it streams
/// straight between the quotes.
fn push_hex(out: &mut String, bytes: &[u8]) {
  const HEX: &[u8; 16] = b"0123456789abcdef";

  out.push('"');
  for &byte in bytes {
    out.push(char::from(HEX[usize::from(byte >> 4)]));
    out.push(char::from(HEX[usize::from(byte & 0x0f)]));
  }
  out.push('"');
}

/// The widths a JSON number holds exactly.
macro_rules! json_number {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl JsonElement for $ty {
        #[inline]
        fn push_json(&self, out: &mut String) {
          use core::fmt::Write;

          let _ = write!(out, "{self}");
        }
      }
    )+
  };
}

/// The widths a JSON number would ROUND: decimal digits between quotes, which need no escaping.
///
/// `u64::MAX` is 18446744073709551615 and the nearest double is 18446744073709551616, so a bare
/// number would compare equal to a different key. A quoted token compares as text and cannot.
macro_rules! json_quoted_number {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl JsonElement for $ty {
        #[inline]
        fn push_json(&self, out: &mut String) {
          use core::fmt::Write;

          out.push('"');
          let _ = write!(out, "{self}");
          out.push('"');
        }
      }
    )+
  };
}

json_number!(i8, i16, i32, i64, u8, u16, u32, f64);
json_quoted_number!(u64, u128, i128);

impl JsonElement for bool {
  #[inline]
  fn push_json(&self, out: &mut String) {
    out.push_str(if *self { "true" } else { "false" });
  }
}

/// Widened through `f64`, whose `Display` is what the `f64` row uses — so a `Vec<f32>` and a
/// `Vec<f64>` of the same values encode identically.
///
/// JSON has NO non-finite number, and neither row refuses one: an infinity renders `inf` and a NaN
/// renders `NaN`, tokens no JSON parser accepts. That hole is `legacy/ingraph`'s and is inherited
/// rather than introduced, and it is why [`Score`](crate::Score) — which excludes all three at
/// construction — is the float element with no such edge.
impl JsonElement for f32 {
  #[inline]
  fn push_json(&self, out: &mut String) {
    f64::from(*self).push_json(out);
  }
}

/// What is encoded is the WRAPPED value, at whatever width the confidence measures in — and the
/// interval is what keeps it a finite one, which is the whole reason a confidence is the float
/// element with no non-finite edge.
impl<S: crate::ConfidenceCarrier + JsonElement> JsonElement for crate::Confidence<S> {
  #[inline]
  fn push_json(&self, out: &mut String) {
    self.get().push_json(out);
  }
}

impl JsonElement for str {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_json_string(out, self);
  }
}

impl JsonElement for String {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_json_string(out, self);
  }
}

impl JsonElement for [u8] {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_hex(out, self);
  }
}

impl JsonElement for Vec<u8> {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_hex(out, self);
  }
}

impl<const N: usize> JsonElement for [u8; N] {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_hex(out, self);
  }
}

#[cfg(feature = "smol_str")]
impl JsonElement for smol_str::SmolStr {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_json_string(out, self);
  }
}

impl JsonElement for bytes::Bytes {
  #[inline]
  fn push_json(&self, out: &mut String) {
    push_hex(out, self);
  }
}

#[cfg(test)]
mod tests;