ic-db-cli 0.41.0

Local fixture console for IC DB
Documentation
//! Private local fixture messages. Each frame contains one positional Postcard value.
use serde::{Serialize, de::DeserializeOwned};

/// Maximum complete request or reply.
pub const MAX_BYTES: usize = 65_536;
/// One version/direction byte and the little-endian method ID.
pub const HEADER_BYTES: usize = 9;

/// The direction of a fixture call.
#[derive(Clone, Copy)]
pub enum Direction {
    /// Caller to fixture.
    Request,
    /// Fixture to caller.
    Response,
}

/// A bounded fixture protocol refusal.
pub type Error = &'static str;

/// Expected prefix for admission before copying the message body.
#[must_use]
pub fn header(method: u64, direction: Direction) -> [u8; HEADER_BYTES] {
    let mut bytes = [0; HEADER_BYTES];
    bytes[0] = match direction {
        Direction::Request => 0xd2,
        Direction::Response => 0xd3,
    };
    bytes[1..].copy_from_slice(&method.to_le_bytes());
    bytes
}

struct FrameWriter {
    bytes: Vec<u8>,
    limit: usize,
}

impl postcard::ser_flavors::Flavor for FrameWriter {
    type Output = Vec<u8>;

    fn try_extend(&mut self, buf: &[u8]) -> postcard::Result<()> {
        if buf.len() > self.limit - self.bytes.len() {
            return Err(postcard::Error::SerializeBufferFull);
        }
        self.bytes.extend_from_slice(buf);

        Ok(())
    }

    fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
        self.try_extend(&[byte])
    }

    fn finalize(self) -> postcard::Result<Vec<u8>> {
        Ok(self.bytes)
    }
}

/// Encode a fixed fixture call without growing the frame beyond its allowance.
/// # Errors
/// Refuses oversized or unrepresentable messages.
pub fn encode<T: Serialize + ?Sized>(
    value: &T,
    method: u64,
    direction: Direction,
    limit: usize,
) -> Result<Vec<u8>, Error> {
    if limit < HEADER_BYTES {
        return Err("fixture frame exceeds byte allowance");
    }
    let writer = FrameWriter {
        bytes: header(method, direction).to_vec(),
        limit: limit.min(MAX_BYTES),
    };
    postcard::serialize_with_flavor(value, writer)
        .map_err(|_| "fixture encoding failed or exceeded byte allowance")
}

/// Decode exactly one complete, bounded fixture frame.
/// # Errors
/// Refuses a wrong header, invalid or incomplete typed values, and trailing data.
pub fn decode<T: DeserializeOwned>(
    bytes: &[u8],
    method: u64,
    direction: Direction,
    limit: usize,
) -> Result<T, Error> {
    if bytes.len() > limit.min(MAX_BYTES) {
        return Err("fixture frame exceeds byte allowance");
    }
    let body = bytes
        .strip_prefix(&header(method, direction))
        .ok_or("invalid fixture header")?;
    let (value, rest) = postcard::take_from_bytes(body).map_err(|_| "invalid fixture body")?;
    if !rest.is_empty() {
        return Err("trailing fixture bytes");
    }

    Ok(value)
}