reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! Private support shared by every `serde` implementation in the crate.
//!
//! No public type's format lives here. Each `Serialize` and `Deserialize` sits
//! beside the invariants it has to preserve, which is what ADR-019 D7 asks for;
//! what this module holds is the machinery those implementations would otherwise
//! repeat sixteen times over — identifier decoding, duplicate- and missing-field
//! reporting, the sequence form a non-self-describing format presents a struct
//! in, and the byte encoding ADR-019 D5 freezes.
//!
//! Sharing it is not only brevity. A duplicate-field rejection written sixteen
//! times is sixteen chances to word one of them as a silent overwrite, and the
//! wire contract says a field appears exactly once.

use std::fmt::{self, Formatter};

use serde_core::de::{
    self, Deserialize, DeserializeSeed, Deserializer, Error as _, IgnoredAny, SeqAccess,
    Unexpected, Visitor,
};
use serde_core::ser::{Serialize, Serializer};

/// A struct field name or enum variant name, read as a serde identifier.
pub(crate) struct Identifier(pub(crate) String);

/// Reads one identifier against the declaration's own list of names.
///
/// Reading through `deserialize_identifier` rather than as a plain string is what
/// lets a self-describing format hand over a name while a compact one hands over
/// a position for the same declaration. The list is what turns the second into
/// the first, and it is the list the type already had to name for
/// `deserialize_struct`, `deserialize_enum` and its unknown-name error — so
/// nothing here is a second spelling of the field set.
pub(crate) struct IdentifierSeed(pub(crate) &'static [&'static str]);

impl<'de> DeserializeSeed<'de> for IdentifierSeed {
    type Value = Identifier;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_identifier(IdentifierVisitor(self.0))
    }
}

struct IdentifierVisitor(&'static [&'static str]);

impl Visitor<'_> for IdentifierVisitor {
    type Value = Identifier;

    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str("a field or variant name")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(Identifier(value.to_owned()))
    }

    /// Resolves the position a compact format sends instead of a name.
    ///
    /// An out-of-range position is refused rather than folded into the
    /// unknown-name path, because the two are different mistakes: one is a
    /// document from a newer writer, the other is a corrupt index.
    fn visit_u64<E>(self, index: u64) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        match usize::try_from(index)
            .ok()
            .and_then(|index| self.0.get(index))
        {
            Some(name) => Ok(Identifier((*name).to_owned())),
            None => Err(E::invalid_value(
                Unexpected::Unsigned(index),
                &"a declared field or variant position",
            )),
        }
    }
}

/// Records a field the first time it appears and refuses a repeat.
///
/// ADR-019 D5 makes a field appear exactly once, so a second occurrence is a
/// malformed record rather than a later value winning.
pub(crate) fn accept<T, E>(slot: &mut Option<T>, value: T, field: &'static str) -> Result<(), E>
where
    E: de::Error,
{
    match slot {
        Some(_) => Err(E::duplicate_field(field)),
        None => {
            *slot = Some(value);
            Ok(())
        }
    }
}

/// Unwraps a field the format is never allowed to omit.
///
/// There is no `#[serde(default)]` anywhere in this crate: a missing field is an
/// error, because a defaulted one would be a value no caller wrote.
pub(crate) fn require<T, E>(slot: Option<T>, field: &'static str) -> Result<T, E>
where
    E: de::Error,
{
    match slot {
        Some(value) => Ok(value),
        None => Err(E::missing_field(field)),
    }
}

/// Reads the next field of a struct presented as a sequence.
///
/// A non-self-describing format renders a struct as its fields in declaration
/// order, so every struct visitor in the crate answers `visit_seq` as well as
/// `visit_map`. Running out of elements is the sequence form's spelling of a
/// missing field.
pub(crate) fn element<'de, T, A>(sequence: &mut A, index: usize) -> Result<T, A::Error>
where
    T: Deserialize<'de>,
    A: SeqAccess<'de>,
{
    match sequence.next_element()? {
        Some(value) => Ok(value),
        None => Err(A::Error::invalid_length(index, &"every struct field")),
    }
}

/// Refuses a trailing value after every declared struct field was read.
///
/// A format's outer framing is not required to check that a visitor exhausted
/// its [`SeqAccess`]. Calling this from each struct visitor makes sequence and map
/// forms agree: neither may contain an undeclared field. Each call's `fields`
/// count matches the adjacent producer's `serialize_struct` declaration in that
/// type's source module.
pub(crate) fn end<'de, A>(sequence: &mut A, fields: usize) -> Result<(), A::Error>
where
    A: SeqAccess<'de>,
{
    match sequence.next_element::<IgnoredAny>()? {
        Some(_) => Err(A::Error::invalid_length(
            fields.saturating_add(1),
            &"exactly the declared struct fields",
        )),
        None => Ok(()),
    }
}

/// Writes a byte string through `serialize_bytes`, never as a sequence of
/// integers.
///
/// ADR-019 D5 freezes the byte encoding as serde's own byte form: core may not
/// parse or re-encode payload bytes, which rules out base64, and the sequence
/// form would tell a binary format that these are numbers. JSON renders both the
/// same way; CBOR, `MessagePack` and postcard do not.
pub(crate) struct Bytes<'a>(pub(crate) &'a [u8]);

impl Serialize for Bytes<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bytes(self.0)
    }
}

/// Reads a byte string written by [`Bytes`].
pub(crate) struct ByteBuf(pub(crate) Box<[u8]>);

impl<'de> Deserialize<'de> for ByteBuf {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_byte_buf(ByteBufVisitor)
    }
}

struct ByteBufVisitor;

impl<'de> Visitor<'de> for ByteBufVisitor {
    type Value = ByteBuf;

    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str("a byte string")
    }

    fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(ByteBuf(Box::from(value)))
    }

    /// Accepts the array of integers a JSON writer produced for a byte string.
    ///
    /// Capacity is not taken from `size_hint`, which is attacker-controlled on
    /// the ingress path this exists to serve.
    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut bytes = Vec::new();
        while let Some(byte) = sequence.next_element::<u8>()? {
            bytes.push(byte);
        }
        Ok(ByteBuf(bytes.into_boxed_slice()))
    }
}

impl ByteBuf {
    /// Converts an optional byte string read from the wire into a field value.
    pub(crate) fn into_optional(value: Option<Self>) -> Option<Box<[u8]>> {
        value.map(|buffer| buffer.0)
    }
}

#[cfg(test)]
#[path = "wire_tests.rs"]
pub(crate) mod wire_tests;