techy 0.1.4

A fast, extensible LaTeX parser for Rust
Documentation
//! The value model of the serialized form: [`SerialValue`], [`SerialEntry`],
//! [`TableId`], and the [`SerialIndex`] bound. Nothing here names a source, a state, or
//! a spec — every kind of object is written in these terms alike.

use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;

/// A serialized value: the in-memory, format-independent form that every
/// serialization produces and every deserialization reads.
///
/// A value is produced by a [`SerializableValue`](crate::serialize::SerializableValue)
/// implementation or by the driver of a table, and a whole serialized object is such a
/// value together with the identifier of what it describes: a [`SerialEntry`].
///
/// The variant set is deliberately small, so that every value has exactly one JSON
/// rendering — JSON is the format the public serialization contract is stated in — and
/// so that two values render identically exactly when they compare equal. That is why
/// there are no floating-point numbers and no sized-integer variants (every integer is
/// an [`Int`](SerialValue::Int)), why map keys are strings and never begin with `$`,
/// and why the order of a [`Map`](SerialValue::Map)'s entries is part of the value.
///
/// The two variants without a native JSON form, [`Bytes`](SerialValue::Bytes) and
/// [`Index`](SerialValue::Index), render as reserved one-entry objects whose key begins
/// with `$`; no other value can produce such a key.
///
/// # Nesting depth
///
/// A value's *nesting depth* is the number of lists and maps that enclose its most
/// deeply nested part ([`nesting_depth`](SerialValue::nesting_depth)); it is bounded
/// by [`MAX_NESTING_DEPTH`](SerialValue::MAX_NESTING_DEPTH) at every point where a
/// value enters or leaves a session or a serialized form — read through serde,
/// converted to or from a [`Segment`](crate::serialize::Segment), interned into a
/// session — so that a malicious input cannot make a reader recurse without limit.
/// See the constant.
///
/// # Rendering through serde
///
/// With the `serde` cargo feature the type implements `Serialize` and `Deserialize`.
/// The rendering depends on the format: a human-readable one (serde's
/// `is_human_readable()`) gets the canonical rendering, every other format a compact
/// one. Both read back to the identical value.
///
/// The canonical rendering — not yet frozen, see "Stability of the serialized form" in
/// the [module documentation](crate::serialize) — stated for JSON: `Null` → `null`,
/// `Bool` → boolean, `Int` → number, `Str` → string, `List` → array, `Map` → object in
/// entry order; `Bytes` → the one-entry object `{"$bytes": "<base64>"}` (standard
/// alphabet, `=` padding, no line breaks); `Index` → the one-entry object
/// `{"$index": [<table>, <index>]}` (two integers: the table's ordinal, then the
/// position).
///
/// Those two keys are the only keys beginning with `$` the rendering ever writes. A
/// `Map` holding a key that begins with `$` is a rendering error — the prefix is
/// reserved and there is no escaping — and on reading, an object key beginning with `$`
/// that is not one of the two reserved forms is an error, as are floating-point
/// numbers, integers outside `i64`, and malformed reserved objects.
///
/// The compact rendering is the externally tagged form of this enum (the variant name,
/// then its data), with `Bytes` written through the format's
/// `serialize_bytes`/`deserialize_bytes` methods, `Index` as the two-integer pair, and
/// `Map` as a serde map.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SerialValue {
    /// The absent value: what `()` serializes to, and what an `Option` that is `None`
    /// becomes.
    Null,
    /// A boolean.
    Bool(bool),
    /// An integer. The only numeric variant: integers of every width are represented
    /// as `i64` (a value that does not fit is a serialization error, never a silent
    /// truncation).
    Int(i64),
    /// A string. Every text in the serialized form is one of these — a name, an
    /// identifier, a piece of source text, and a `char` as a one-character string.
    Str(String),
    /// A byte string: data that is not text, such as a source's digest. Rendered as
    /// base64 text in JSON.
    Bytes(Vec<u8>),
    /// An ordered sequence of values: what a `Vec<T>` becomes, and every repeated part
    /// of an entry, such as the nodes of a tree.
    List(Vec<SerialValue>),
    /// A string-keyed map: an ordered list of entries. This is what a structure with
    /// named fields becomes, each field under its own key.
    ///
    /// The order is part of the value — equality is order-sensitive and the rendering
    /// preserves the order — so two maps with the same entries in different orders are
    /// different values that render differently. Keys are expected to be unique and
    /// must not begin with `$` (the prefix is reserved for the rendering's own objects;
    /// a key that begins with it is a rendering or bridge error); the value model itself
    /// enforces neither at construction.
    Map(Vec<(String, SerialValue)>),
    /// A reference to the object at position `index` of the table `table`.
    ///
    /// This is what makes sharing survive a round trip: an object is written into its
    /// table once, and everything that refers to it stores an `Index` instead of a copy.
    /// Rust code holds the same two parts as a typed position — see [`SerialIndex`].
    Index {
        /// The table the referenced object is stored in.
        table: TableId,
        /// The referenced object's position within that table.
        index: u32,
    },
}

impl SerialValue {
    /// The greatest nesting depth a serialized value may have: no value that crosses
    /// the serialization boundary has a [`nesting_depth`](SerialValue::nesting_depth)
    /// above this.
    ///
    /// The bound is checked at every such boundary — reading a value through serde (the
    /// `Deserialize` impls of `SerialValue` and of [`Segment`](crate::serialize::Segment),
    /// with the `serde` cargo feature), converting a segment from its serialized form
    /// ([`Segment::from_serial_value`](crate::serialize::Segment::from_serial_value)),
    /// absorbing a segment ([`SerdeSession::push_segment`](crate::serialize::SerdeSession::push_segment)),
    /// and interning an object ([`SerdeSession::intern`](crate::serialize::SerdeSession::intern)).
    /// A deeper value is a
    /// [`SerialValueError::NestingTooDeep`](crate::serialize::SerialValueError::NestingTooDeep)
    /// error there, so that a malicious input cannot exhaust the stack of a reader that
    /// walks values recursively, and so that a writer learns at once when an entry would
    /// be unreadable.
    ///
    /// A segment's serialized form counts as one value: its own structure — the segment
    /// map, its table list, a table's map, its entry list — takes four levels, so an
    /// entry's stored form may nest at most four levels less than this (a table that
    /// stores identifiers with the data wraps each entry in one more map).
    ///
    /// The bound is well above what any serialized object of this crate needs (a tree's
    /// entry nests about ten levels), and below the default recursion limit of the
    /// `serde_json` reader (128), so that the same bound is in force whatever the
    /// format.
    pub const MAX_NESTING_DEPTH: usize = 64;

    /// The value's nesting depth: the number of lists and maps that enclose its most
    /// deeply nested part.
    ///
    /// A value that is not a list or a map has depth `0`; a list or map holding no list
    /// or map has depth `1`; a list holding one list holding one integer — `[[1]]` in
    /// JSON — has depth `2`. The computation does not recurse, so a value of any depth
    /// can be measured. The depth a value may have when it crosses the serialization
    /// boundary is bounded by [`MAX_NESTING_DEPTH`](SerialValue::MAX_NESTING_DEPTH).
    pub fn nesting_depth(&self) -> usize {
        let mut deepest = 0;
        let mut pending: Vec<(&SerialValue, usize)> = Vec::from([(self, 0)]);
        while let Some((value, enclosing)) = pending.pop() {
            let inner = enclosing + 1;
            match value {
                SerialValue::List(items) => {
                    deepest = deepest.max(inner);
                    pending.extend(items.iter().map(|item| (item, inner)));
                }
                SerialValue::Map(entries) => {
                    deepest = deepest.max(inner);
                    pending.extend(entries.iter().map(|(_, item)| (item, inner)));
                }
                SerialValue::Null
                | SerialValue::Bool(_)
                | SerialValue::Int(_)
                | SerialValue::Str(_)
                | SerialValue::Bytes(_)
                | SerialValue::Index { .. } => {}
            }
        }
        deepest
    }

    /// The name of this value's kind — `null`, `bool`, `int`, `str`, `bytes`, `list`,
    /// `map`, or `index` — as error messages report it (the `found` of a
    /// [`SerialValueError::TypeMismatch`](crate::serialize::SerialValueError::TypeMismatch)).
    pub(crate) fn kind_name(&self) -> &'static str {
        match self {
            SerialValue::Null => "null",
            SerialValue::Bool(_) => "bool",
            SerialValue::Int(_) => "int",
            SerialValue::Str(_) => "str",
            SerialValue::Bytes(_) => "bytes",
            SerialValue::List(_) => "list",
            SerialValue::Map(_) => "map",
            SerialValue::Index { .. } => "index",
        }
    }
}

/// The result of serializing one object: the object's identifier and its data.
///
/// This is what a
/// [`SerializableObject::serialize_object`](crate::serialize::SerializableObject::serialize_object)
/// call returns, and what a table stores for each object it holds.
///
/// The `identifier` names the kind of object `data` describes: a deliberately chosen,
/// stable string owned by whoever defines the object type — never a Rust type name. It
/// is a `Cow<'static, str>`, so that a fixed identifier can be a string literal while a
/// type whose identifier depends on the instance supplies an owned string. A table that
/// holds objects of one kind only does not write the identifier out; even then the
/// entry has a real, non-empty identifier.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SerialEntry {
    /// The identifier of the kind of object `data` describes.
    pub identifier: Cow<'static, str>,
    /// The serialized object.
    pub data: SerialValue,
}

/// The ordinal of a table: which numbered table a [`SerialValue::Index`] refers to.
///
/// Tables are numbered deterministically, in the order they are registered with a
/// [`SerdeSession`](crate::serialize::SerdeSession). User code receives `TableId`s —
/// inside typed table positions and on
/// [`TableHandle`](crate::serialize::TableHandle)s — and passes them along, but never
/// creates them.
///
/// A `TableId` is meaningful only relative to the session that assigned it: two
/// sessions that register the same tables in different orders number them differently.
/// Inside a segment, table references use the writing session's ids and are translated
/// by table *name* when another session absorbs the segment (see
/// [`SerdeSession::push_segment`](crate::serialize::SerdeSession::push_segment)). A
/// typed position held in Rust code is not translated, so it is exchanged between
/// sessions as its table's name and its `u32` index (see
/// [`SerialIndex`](crate::serialize::SerialIndex)).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TableId(u32);

impl TableId {
    /// A table id with the given ordinal. Crate-internal: table ids are assigned by
    /// the session that registers tables, in registration order.
    pub(crate) fn new(ordinal: u32) -> TableId {
        TableId(ordinal)
    }

    /// The table's ordinal: its position in the registration order of the session
    /// that assigned it, from `0`.
    pub fn ordinal(self) -> u32 {
        self.0
    }
}

/// The bound every typed table position satisfies: a `Copy` value holding both the
/// [`TableId`] of its table and the `u32` position within it.
///
/// A typed position is the `Index` type of an
/// [`ObjectSerdeDriver`](crate::serialize::ObjectSerdeDriver). It holds the same two
/// parts as a [`SerialValue::Index`], so that a position in one table cannot be mistaken
/// for a position in another and its serialized form needs no further context.
///
/// Position types are defined with the [`serial_index!`](crate::serialize::serial_index)
/// macro, which supplies this impl together with the conversions to and from the
/// serialized form; each kind of table has its own position type, defined next to
/// the driver of that table. Positions are created by the session (a
/// [`SerializeContext::intern`](crate::serialize::SerializeContext::intern) call
/// returns one) or rebuilt from a bare index with
/// [`TableHandle::position`](crate::serialize::TableHandle::position); on the
/// reading side, the session validates both parts.
///
/// **A typed position is scoped to the session that created it.** Its `TableId` is that
/// session's, and two sessions that register the same tables in different orders number
/// them differently: a position from a writing session, passed unchanged to a reading
/// session, names the wrong table there
/// ([`DeserializeError::WrongTable`](crate::serialize::DeserializeError::WrongTable)).
///
/// References *inside* entries need no such care: a segment stores positions as `u32`
/// indices scoped to the stream, and the reading session translates the table
/// references by table name. A position held in Rust code and passed from one session
/// to another is exchanged as its table's name
/// ([`ObjectSerdeDriver::table_name`](crate::serialize::ObjectSerdeDriver::table_name))
/// and its `u32` index ([`index`](SerialIndex::index)), and rebuilt on the receiving
/// side with `TableHandle::position`.
pub trait SerialIndex: Copy + Eq + core::hash::Hash + core::fmt::Debug + Send + Sync + 'static {
    /// The position `index` of table `table`.
    fn from_parts(table: TableId, index: u32) -> Self;

    /// The table this position refers into.
    fn table(self) -> TableId;

    /// The position within the table, from `0`.
    fn index(self) -> u32;
}