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
//! The single error type returned by reads and writes.
//!
//! Every failure mode is a variant of [`Error`]. Each variant carries the
//! context that applies to it: the version found on the wire, the versions the
//! reader was built to handle, the byte counts from a trailing-byte check, or a
//! decoder's own error as the [`source`](std::error::Error::source). Not every
//! variant carries every field; [`Empty`](Error::Empty) and
//! [`Truncated`](Error::Truncated) fail before any version is known.

use std::error::Error as StdError;
use std::fmt;

/// A boxed decoder or encoder error, preserved as the [`source`](StdError::source).
pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;

/// Anything that can go wrong while framing, reading, or migrating a value.
///
/// The framing errors ([`Empty`](Error::Empty), [`Truncated`](Error::Truncated))
/// come from the version tag itself. The routing errors
/// ([`UnknownVersion`](Error::UnknownVersion),
/// [`ForwardIncompatible`](Error::ForwardIncompatible)) come from comparing the
/// tag against the versions a reader was built to handle. The payload errors
/// ([`Decode`](Error::Decode), [`Encode`](Error::Encode),
/// [`TrailingBytes`](Error::TrailingBytes)) come from your own format.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// The input held no bytes, so there was no version tag to read.
    Empty,

    /// The input ended before the whole version tag could be read.
    Truncated {
        /// Bytes the tag needs (always [`crate::wire::TAG_LEN`]).
        needed: usize,
        /// Bytes actually available.
        got: usize,
    },

    /// The tag names a version older than the oldest one the reader handles, or
    /// one that falls in a gap between the versions it handles.
    ///
    /// This is a version the reader has no decoder for. It is distinct from
    /// [`ForwardIncompatible`](Error::ForwardIncompatible), which is a version
    /// newer than anything the reader knows.
    UnknownVersion {
        /// The version found on the wire.
        found: u16,
        /// The versions the reader was built to handle, in registration order.
        known: Vec<u16>,
    },

    /// The tag names a version newer than the newest one the reader handles.
    ///
    /// The data was written by a later revision of your schema. Reading it here
    /// would be a downgrade, which this crate does not do. The fix is to run a
    /// build new enough to know the version.
    ForwardIncompatible {
        /// The version found on the wire.
        found: u16,
        /// The newest version the reader handles.
        current: u16,
    },

    /// The payload decoded, but the decoder did not consume all of it.
    ///
    /// This check rejects a decoder that consumed fewer (or more) bytes than the
    /// payload holds, such as a wrong-length payload that decodes as a prefix and
    /// stops short.
    TrailingBytes {
        /// The version whose decoder ran.
        version: u16,
        /// Bytes the decoder reported consuming.
        consumed: usize,
        /// Bytes in the payload.
        total: usize,
    },

    /// The version's decoder returned an error. The original error is the
    /// [`source`](StdError::source).
    Decode {
        /// The version whose decoder ran.
        version: u16,
        /// The decoder's own error.
        source: BoxError,
    },

    /// The encoder passed to [`write`](crate::write) returned an error. The
    /// original error is the [`source`](StdError::source).
    Encode {
        /// The version being written.
        version: u16,
        /// The encoder's own error.
        source: BoxError,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Empty => write!(f, "empty input: no version tag"),
            Error::Truncated { needed, got } => {
                write!(f, "truncated version tag: need {needed} bytes, got {got}")
            }
            Error::UnknownVersion { found, known } => {
                write!(f, "unknown version {found} (reader handles ")?;
                write_versions(f, known)?;
                write!(f, ")")
            }
            Error::ForwardIncompatible { found, current } => write!(
                f,
                "version {found} is newer than this reader's current version {current}"
            ),
            Error::TrailingBytes {
                version,
                consumed,
                total,
            } => {
                if consumed <= total {
                    write!(
                        f,
                        "version {version} decoder consumed {consumed} of {total} \
                         payload bytes, leaving {} unconsumed",
                        total - consumed
                    )
                } else {
                    write!(
                        f,
                        "version {version} decoder reported consuming {consumed} bytes \
                         of a {total}-byte payload"
                    )
                }
            }
            Error::Decode { version, source } => {
                write!(f, "version {version} failed to decode: {source}")
            }
            Error::Encode { version, source } => {
                write!(f, "version {version} failed to encode: {source}")
            }
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Decode { source, .. } | Error::Encode { source, .. } => {
                Some(&**source as &(dyn StdError + 'static))
            }
            _ => None,
        }
    }
}

fn write_versions(f: &mut fmt::Formatter<'_>, versions: &[u16]) -> fmt::Result {
    for (i, v) in versions.iter().enumerate() {
        if i > 0 {
            write!(f, ", ")?;
        }
        write!(f, "{v}")?;
    }
    Ok(())
}