mod order;
pub(crate) mod text;
mod value;
pub use order::{OrderFold, OrderLevels, OrderSignature, OrderTerm, TermName, TermSubject, Walk};
pub use value::{CursorCodec, CursorValue, DialectCursor, dialect, read_member, write_member};
const VERSION: u8 = 1;
const ABSENT: u8 = 0;
const PRESENT: u8 = 1;
const LENGTH: usize = size_of::<u32>();
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Cursor<V> {
signature: OrderSignature,
values: Box<[Option<V>]>,
}
impl<V> Cursor<V> {
#[must_use]
pub fn at(order: &[OrderTerm], values: impl Into<Box<[Option<V>]>>) -> Self {
Self {
signature: OrderSignature::of(order),
values: values.into(),
}
}
#[inline]
#[must_use]
pub const fn signature(&self) -> OrderSignature {
self.signature
}
#[inline]
#[must_use]
pub fn values(&self) -> &[Option<V>] {
&self.values
}
pub fn resume(&self, order: &[OrderTerm]) -> Result<&[Option<V>], CursorError> {
let presented = OrderSignature::of(order);
if presented != self.signature {
return Err(CursorError::Order(OrderMismatch::new(
self.signature,
presented,
)));
}
if self.values.len() != order.len() {
return Err(CursorError::Arity(ArityMismatch::new(
self.values.len(),
order.len(),
)));
}
for (term, value) in order.iter().zip(&self.values) {
if value.is_none() && !term.is_nullable() {
return Err(CursorError::Null(term.identity()));
}
}
Ok(&self.values)
}
}
impl<V: CursorValue> Cursor<V> {
#[must_use]
pub fn encode(&self) -> String {
let mut frame = Vec::with_capacity(1 + self.signature.to_blob().len() + self.values.len() * 8);
frame.push(VERSION);
frame.extend_from_slice(&self.signature.to_blob());
for value in &self.values {
let Some(value) = value else {
frame.push(ABSENT);
continue;
};
frame.push(PRESENT);
let at = frame.len();
frame.extend_from_slice(&[0; LENGTH]);
value.write_cursor(&mut frame);
let length = u32::try_from(frame.len() - at - LENGTH).unwrap_or(u32::MAX);
frame[at..at + LENGTH].copy_from_slice(&length.to_be_bytes());
}
text::encode(&frame)
}
pub fn decode(text: &str) -> Result<Self, CursorError> {
let frame = text::decode(text).ok_or(CursorError::Alphabet)?;
let (version, rest) = frame.split_first().ok_or(CursorError::Truncated)?;
if *version != VERSION {
return Err(CursorError::Version(*version));
}
let (signature, mut rest) = rest
.split_at_checked(size_of::<u64>())
.ok_or(CursorError::Truncated)?;
let signature = OrderSignature::from_blob(signature).ok_or(CursorError::Truncated)?;
let mut values = Vec::new();
while let Some((presence, tail)) = rest.split_first() {
match *presence {
ABSENT => {
values.push(None);
rest = tail;
}
PRESENT => {
let (length, tail) = tail
.split_at_checked(LENGTH)
.ok_or(CursorError::Truncated)?;
let length = usize::try_from(u32::from_be_bytes(
length.try_into().expect("split_at_checked gave four bytes"),
))
.map_err(|_| CursorError::Truncated)?;
let (bytes, tail) = tail
.split_at_checked(length)
.ok_or(CursorError::Truncated)?;
values.push(Some(
V::read_cursor(bytes).ok_or(CursorError::Value(values.len()))?,
));
rest = tail;
}
_ => return Err(CursorError::Truncated),
}
}
Ok(Self {
signature,
values: values.into_boxed_slice(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OrderMismatch {
minted: OrderSignature,
presented: OrderSignature,
}
impl OrderMismatch {
#[inline]
pub(crate) const fn new(minted: OrderSignature, presented: OrderSignature) -> Self {
Self { minted, presented }
}
#[inline]
pub const fn minted(&self) -> OrderSignature {
self.minted
}
#[inline]
pub const fn presented(&self) -> OrderSignature {
self.presented
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArityMismatch {
values: usize,
terms: usize,
}
impl ArityMismatch {
#[inline]
pub(crate) const fn new(values: usize, terms: usize) -> Self {
Self { values, terms }
}
#[inline]
pub const fn values(&self) -> usize {
self.values
}
#[inline]
pub const fn terms(&self) -> usize {
self.terms
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorError {
Alphabet,
Truncated,
Version(u8),
Value(usize),
Order(OrderMismatch),
Arity(ArityMismatch),
Null(&'static TermName),
}
impl core::fmt::Display for CursorError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Alphabet => f.write_str("this cursor is not base64url"),
Self::Truncated => f.write_str("this cursor's frame ends inside a field"),
Self::Version(version) => write!(
f,
"this cursor is version {version} and this build reads version {VERSION}"
),
Self::Value(at) => write!(f, "this cursor's value {at} is not a value of that column"),
Self::Order(mismatch) => write!(
f,
"this cursor was minted under another order ({:#018x}, replayed against {:#018x})",
mismatch.minted().get(),
mismatch.presented().get()
),
Self::Arity(mismatch) => write!(
f,
"this cursor carries {} values and the order has {} terms",
mismatch.values(),
mismatch.terms()
),
Self::Null(term) => {
let term: &str = term;
write!(f, "this cursor is null at `{term}`, which is NOT NULL")
}
}
}
}
impl core::error::Error for CursorError {}
#[cfg(test)]
mod tests;