verstamp 0.1.0

An explicit version tag in the byte stream, plus a forward migration chain, for binary formats that can't describe themselves.
Documentation
//! Framing: putting a version tag in front of a payload, and taking it back off.
//!
//! The frame is deliberately tiny. A value on the wire is a two-byte,
//! big-endian [`u16`] version followed by your encoded payload:
//!
//! ```text
//! byte 0    byte 1    byte 2 ..
//! +--------+--------+---------------------------+
//! | ver hi | ver lo |  payload (your format)    |
//! +--------+--------+---------------------------+
//!  \_______________/ \_________________________/
//!    u16 big-endian     opaque to verstamp
//! ```
//!
//! That is the whole format. verstamp never looks inside the payload; encoding
//! and decoding it stays entirely yours. Starting versions at 1 is a
//! recommendation: a reader that never registers version 0 then rejects an
//! all-zero buffer as [`Error::UnknownVersion`]. verstamp does not enforce it.
//!
//! [`frame`] and [`write()`] add the tag. [`read`] takes it off and hands you a
//! [`Frame`] to route on.

use crate::chain::Chain;
use crate::error::{BoxError, Error};

/// The width of the version tag, in bytes.
///
/// ```
/// assert_eq!(verstamp::wire::TAG_LEN, 2);
/// ```
pub const TAG_LEN: usize = 2;

/// Prepend a version tag to already-encoded payload bytes.
///
/// This is the infallible half of writing: you encode with your format of
/// choice, then stamp the result. Use [`write()`] when you would rather hand the
/// encoder a buffer to append into.
///
/// ```
/// let bytes = verstamp::frame(3, &[0xAA, 0xBB]);
/// assert_eq!(bytes, [0x00, 0x03, 0xAA, 0xBB]);
/// ```
#[must_use = "the framed bytes are the value you meant to write"]
pub fn frame(version: u16, payload: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(TAG_LEN + payload.len());
    out.extend_from_slice(&version.to_be_bytes());
    out.extend_from_slice(payload);
    out
}

/// Write a version tag, then let `encode` append the payload.
///
/// `encode` receives a buffer that already holds the two tag bytes; it appends
/// the payload and returns `Ok(())`, or an error that becomes
/// [`Error::Encode`]. This suits encoders that write into a `Vec<u8>` or an
/// `impl std::io::Write`.
///
/// ```
/// let bytes = verstamp::write(1, |buf| {
///     buf.extend_from_slice(&42u32.to_be_bytes());
///     Ok::<_, std::convert::Infallible>(())
/// })?;
/// assert_eq!(bytes, [0x00, 0x01, 0x00, 0x00, 0x00, 0x2A]);
/// # Ok::<(), verstamp::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`Error::Encode`] if `encode` returns an error, preserving it as the
/// [`source`](std::error::Error::source).
pub fn write<F, E>(version: u16, encode: F) -> Result<Vec<u8>, Error>
where
    F: FnOnce(&mut Vec<u8>) -> Result<(), E>,
    E: Into<BoxError>,
{
    let mut out = Vec::new();
    out.extend_from_slice(&version.to_be_bytes());
    match encode(&mut out) {
        Ok(()) => Ok(out),
        Err(e) => Err(Error::Encode {
            version,
            source: e.into(),
        }),
    }
}

/// Read the version tag off a byte stream.
///
/// The returned [`Frame`] exposes the [`version`](Frame::version) and the
/// [`payload`](Frame::payload), and starts a migration chain through
/// [`Frame::at`]. Empty and truncated inputs fail here, before any decoder
/// runs.
///
/// ```
/// let bytes = verstamp::frame(7, b"payload");
/// let frame = verstamp::read(&bytes)?;
/// assert_eq!(frame.version(), 7);
/// assert_eq!(frame.payload(), b"payload");
/// # Ok::<(), verstamp::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`Error::Empty`] if `bytes` is empty, or [`Error::Truncated`] if it
/// is shorter than the two-byte tag.
pub fn read(bytes: &[u8]) -> Result<Frame<'_>, Error> {
    if bytes.is_empty() {
        return Err(Error::Empty);
    }
    if bytes.len() < TAG_LEN {
        return Err(Error::Truncated {
            needed: TAG_LEN,
            got: bytes.len(),
        });
    }
    let version = u16::from_be_bytes([bytes[0], bytes[1]]);
    Ok(Frame {
        version,
        payload: &bytes[TAG_LEN..],
    })
}

/// A stream whose version tag has been read, ready to route on.
///
/// Build a reader by naming the oldest version you can decode with
/// [`at`](Frame::at), then adding one [`then`](Chain::then) per migration step,
/// in strictly increasing version order. The tag decides which decoder runs;
/// migrations carry the result forward to the current type.
#[must_use = "a frame does nothing until you route it with `at`"]
#[derive(Debug, Clone, Copy)]
pub struct Frame<'a> {
    version: u16,
    payload: &'a [u8],
}

impl<'a> Frame<'a> {
    /// The version found on the wire.
    ///
    /// ```
    /// let bytes = verstamp::frame(5, b"body");
    /// assert_eq!(verstamp::read(&bytes)?.version(), 5);
    /// # Ok::<(), verstamp::Error>(())
    /// ```
    #[must_use]
    pub fn version(&self) -> u16 {
        self.version
    }

    /// The payload bytes, everything after the tag.
    ///
    /// ```
    /// let bytes = verstamp::frame(5, b"body");
    /// assert_eq!(verstamp::read(&bytes)?.payload(), b"body");
    /// # Ok::<(), verstamp::Error>(())
    /// ```
    #[must_use]
    pub fn payload(&self) -> &'a [u8] {
        self.payload
    }

    /// Begin a migration chain at the oldest version this reader can decode.
    ///
    /// `decode` runs only if the tag equals `version`. It returns the decoded
    /// value together with the number of payload bytes it consumed; verstamp
    /// checks that count against the payload length and rejects any leftover as
    /// [`Error::TrailingBytes`]. Add later versions with [`Chain::then`], in
    /// strictly increasing version order, then finish with [`Chain::done`].
    ///
    /// ```
    /// # #[derive(Debug, PartialEq)]
    /// # struct V1(u8);
    /// let bytes = verstamp::frame(1, &[9]);
    /// let v1: V1 = verstamp::read(&bytes)?
    ///     .at(1, |b| {
    ///         if b.is_empty() {
    ///             return Err("short");
    ///         }
    ///         Ok::<_, &str>((V1(b[0]), 1))
    ///     })
    ///     .done()?;
    /// assert_eq!(v1, V1(9));
    /// # Ok::<(), verstamp::Error>(())
    /// ```
    pub fn at<T, F, E>(self, version: u16, decode: F) -> Chain<'a, T>
    where
        F: FnOnce(&[u8]) -> Result<(T, usize), E>,
        E: Into<BoxError>,
    {
        Chain::seed(self.version, self.payload, version, decode)
    }
}