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
//! TWO TOY SINKS, shared by every test that needs a column language to speak into.
//!
//! [`Fallback`] implements the required kinds and nothing else, so every defaulted method's own body
//! runs and each landed column is opaque bytes. [`Native`] overrides the same kinds to land a column
//! per width, as an engine with typed columns of its own would. A row written once is read back off
//! both, which is the claim these two exist to put under test: a row speaks columns and the engine
//! decides what a column IS.
//!
//! They live here rather than in one test file because two of them want the pair — the column
//! language's own tests, and [`Field`](crate::Field)'s rows one module over. A toy copied per test
//! file is two engines free to drift, which would make the second file's round trip a test of its
//! own copy.

use uuid::Uuid;

use super::{ColumnError, ColumnReader, ColumnWriter};

/// ONE LANDED COLUMN — this toy engine's whole storage vocabulary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Col {
  I8(i8),
  I16(i16),
  I32(i32),
  I64(i64),
  I128(i128),
  U8(u8),
  U16(u16),
  U32(u32),
  U64(u64),
  U128(u128),
  Text(String),
  Bytes(Vec<u8>),
  Uuid(Uuid),
}

impl Col {
  /// What a refusal names this column as.
  const fn kind(&self) -> &'static str {
    match self {
      Self::I8(_) => "i8",
      Self::I16(_) => "i16",
      Self::I32(_) => "i32",
      Self::I64(_) => "i64",
      Self::I128(_) => "i128",
      Self::U8(_) => "u8",
      Self::U16(_) => "u16",
      Self::U32(_) => "u32",
      Self::U64(_) => "u64",
      Self::U128(_) => "u128",
      Self::Text(_) => "text",
      Self::Bytes(_) => "bytes",
      Self::Uuid(_) => "uuid",
    }
  }
}

/// THIS ENGINE'S REFUSAL — one error for the whole read phase, whatever raised it.
///
/// Every arm but [`Custom`](Self::Custom) is the engine's own, raised where the cursor reads or
/// where the key finishes. `Custom` is every refusal a ROW raised, because this toy takes
/// [`ColumnError`]'s named methods AS THEY COME: `domain` and `width` arrive already worded by their
/// defaults and land there beside a refusal a row wrote itself. An engine that would rather match on
/// a named refusal overrides the method instead — which is a second toy error, in this module's
/// tests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Refusal {
  /// A column was asked for past the last one landed.
  End,
  /// The next column is not the kind asked for.
  Kind {
    wanted: &'static str,
    found: &'static str,
  },
  /// A byte column does not hold the octets a fixed-width read demands.
  ///
  /// The ENGINE's own check, raised by [`ColumnReader::fixed`], where the row named the width before
  /// it read.
  ///
  /// NOT [`ColumnError::width`], and the name says so. That one is the ROW's — a key that reads its
  /// arms apart BY width, naming the whole set it admits — and this engine leaves it defaulted, so a
  /// row's arrives as [`Custom`](Self::Custom) instead. Two refusals about two parties, and while
  /// both were called `width` the only way to tell which a test had caught was to read the arm's
  /// fields.
  Octets { wanted: usize, found: usize },
  /// A row refused what it read, in whatever words reached [`ColumnError::custom`].
  Custom(String),
  /// Columns remain after the key finished reading.
  Trailing(usize),
}

impl Refusal {
  fn kind(wanted: &'static str, found: &Col) -> Self {
    Self::Kind {
      wanted,
      found: found.kind(),
    }
  }
}

impl ColumnError for Refusal {
  fn custom<T: core::fmt::Display>(msg: T) -> Self {
    Self::Custom(msg.to_string())
  }
}

/// A SINK WITH ONLY THE REQUIRED KINDS — every other column arrives through a defaulted method.
#[derive(Debug, Default)]
pub(crate) struct Fallback(pub(crate) Vec<Col>);

impl Fallback {
  /// The cursor over what this sink landed.
  pub(crate) fn read(self) -> FallbackRead {
    FallbackRead(Cursor::new(self.0))
  }
}

impl ColumnWriter for Fallback {
  fn i64(&mut self, value: i64) {
    self.0.push(Col::I64(value));
  }

  fn u64(&mut self, value: u64) {
    self.0.push(Col::U64(value));
  }

  fn text(&mut self, value: &str) {
    self.0.push(Col::Text(value.to_owned()));
  }

  fn bytes(&mut self, value: &[u8]) {
    self.0.push(Col::Bytes(value.to_vec()));
  }

  fn uuid(&mut self, value: Uuid) {
    self.0.push(Col::Uuid(value));
  }
}

/// A SINK WITH A COLUMN PER WIDTH — what an engine whose storage has typed integer columns writes.
#[derive(Debug, Default)]
pub(crate) struct Native(pub(crate) Vec<Col>);

impl Native {
  /// The cursor over what this sink landed.
  pub(crate) fn read(self) -> NativeRead {
    NativeRead(Cursor::new(self.0))
  }
}

impl ColumnWriter for Native {
  fn i64(&mut self, value: i64) {
    self.0.push(Col::I64(value));
  }

  fn u64(&mut self, value: u64) {
    self.0.push(Col::U64(value));
  }

  fn text(&mut self, value: &str) {
    self.0.push(Col::Text(value.to_owned()));
  }

  fn bytes(&mut self, value: &[u8]) {
    self.0.push(Col::Bytes(value.to_vec()));
  }

  fn uuid(&mut self, value: Uuid) {
    self.0.push(Col::Uuid(value));
  }

  fn i8(&mut self, value: i8) {
    self.0.push(Col::I8(value));
  }

  fn i16(&mut self, value: i16) {
    self.0.push(Col::I16(value));
  }

  fn i32(&mut self, value: i32) {
    self.0.push(Col::I32(value));
  }

  fn i128(&mut self, value: i128) {
    self.0.push(Col::I128(value));
  }

  fn u8(&mut self, value: u8) {
    self.0.push(Col::U8(value));
  }

  fn u16(&mut self, value: u16) {
    self.0.push(Col::U16(value));
  }

  fn u32(&mut self, value: u32) {
    self.0.push(Col::U32(value));
  }

  fn u128(&mut self, value: u128) {
    self.0.push(Col::U128(value));
  }
}

/// THE READ MECHANICS both cursors share: one position, advanced and never rewound.
#[derive(Debug)]
pub(crate) struct Cursor {
  cols: Vec<Col>,
  at: usize,
}

impl Cursor {
  pub(crate) fn new(cols: Vec<Col>) -> Self {
    Self { cols, at: 0 }
  }

  /// The next column, with the position moved past it before the borrow leaves.
  fn take(&mut self) -> Result<&Col, Refusal> {
    let at = self.at;
    if at >= self.cols.len() {
      return Err(Refusal::End);
    }
    self.at = at + 1;
    Ok(&self.cols[at])
  }

  fn text(&mut self) -> Result<&str, Refusal> {
    match self.take()? {
      Col::Text(value) => Ok(value),
      found => Err(Refusal::kind("text", found)),
    }
  }

  fn bytes(&mut self) -> Result<&[u8], Refusal> {
    match self.take()? {
      Col::Bytes(value) => Ok(value),
      found => Err(Refusal::kind("bytes", found)),
    }
  }

  fn uuid(&mut self) -> Result<Uuid, Refusal> {
    match self.take()? {
      Col::Uuid(value) => Ok(*value),
      found => Err(Refusal::kind("uuid", found)),
    }
  }

  fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Refusal> {
    let value = self.bytes()?;
    let found = value.len();
    <[u8; N]>::try_from(value).map_err(|_| Refusal::Octets { wanted: N, found })
  }

  fn remaining(&self) -> usize {
    self.cols.len() - self.at
  }
}

/// One arm-typed read per macro line — the eleven shapes that differ only in which arm they want.
macro_rules! reads {
  ($($method:ident => $arm:ident as $ty:ty),* $(,)?) => {
    impl Cursor {
      $(fn $method(&mut self) -> Result<$ty, Refusal> {
        match self.take()? {
          Col::$arm(value) => Ok(*value),
          found => Err(Refusal::kind(stringify!($method), found)),
        }
      })*
    }
  };
}

reads!(
  i8 => I8 as i8,
  i16 => I16 as i16,
  i32 => I32 as i32,
  i64 => I64 as i64,
  i128 => I128 as i128,
  u8 => U8 as u8,
  u16 => U16 as u16,
  u32 => U32 as u32,
  u64 => U64 as u64,
  u128 => U128 as u128,
);

/// The cursor over [`Fallback`]'s columns — the required reads, and the rest defaulted.
#[derive(Debug)]
pub(crate) struct FallbackRead(pub(crate) Cursor);

impl ColumnReader for FallbackRead {
  type Error = Refusal;

  fn i64(&mut self) -> Result<i64, Self::Error> {
    self.0.i64()
  }

  fn u64(&mut self) -> Result<u64, Self::Error> {
    self.0.u64()
  }

  fn text(&mut self) -> Result<&str, Self::Error> {
    self.0.text()
  }

  fn bytes(&mut self) -> Result<&[u8], Self::Error> {
    self.0.bytes()
  }

  fn uuid(&mut self) -> Result<Uuid, Self::Error> {
    self.0.uuid()
  }

  fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Self::Error> {
    self.0.fixed()
  }

  fn finish(self) -> Result<(), Self::Error> {
    match self.0.remaining() {
      0 => Ok(()),
      surplus => Err(Refusal::Trailing(surplus)),
    }
  }
}

/// The cursor over [`Native`]'s columns — every kind taken from the arm its write landed.
#[derive(Debug)]
pub(crate) struct NativeRead(pub(crate) Cursor);

impl ColumnReader for NativeRead {
  type Error = Refusal;

  fn i64(&mut self) -> Result<i64, Self::Error> {
    self.0.i64()
  }

  fn u64(&mut self) -> Result<u64, Self::Error> {
    self.0.u64()
  }

  fn text(&mut self) -> Result<&str, Self::Error> {
    self.0.text()
  }

  fn bytes(&mut self) -> Result<&[u8], Self::Error> {
    self.0.bytes()
  }

  fn uuid(&mut self) -> Result<Uuid, Self::Error> {
    self.0.uuid()
  }

  fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Self::Error> {
    self.0.fixed()
  }

  fn i8(&mut self) -> Result<i8, Self::Error> {
    self.0.i8()
  }

  fn i16(&mut self) -> Result<i16, Self::Error> {
    self.0.i16()
  }

  fn i32(&mut self) -> Result<i32, Self::Error> {
    self.0.i32()
  }

  fn i128(&mut self) -> Result<i128, Self::Error> {
    self.0.i128()
  }

  fn u8(&mut self) -> Result<u8, Self::Error> {
    self.0.u8()
  }

  fn u16(&mut self) -> Result<u16, Self::Error> {
    self.0.u16()
  }

  fn u32(&mut self) -> Result<u32, Self::Error> {
    self.0.u32()
  }

  fn u128(&mut self) -> Result<u128, Self::Error> {
    self.0.u128()
  }

  fn finish(self) -> Result<(), Self::Error> {
    match self.0.remaining() {
      0 => Ok(()),
      surplus => Err(Refusal::Trailing(surplus)),
    }
  }
}