Skip to main content

ic_db_cli/
fixture_codec.rs

1//! Private local fixture messages. Each frame contains one positional Postcard value.
2use serde::{Serialize, de::DeserializeOwned};
3
4/// Maximum complete request or reply.
5pub const MAX_BYTES: usize = 65_536;
6/// One version/direction byte and the little-endian method ID.
7pub const HEADER_BYTES: usize = 9;
8
9/// The direction of a fixture call.
10#[derive(Clone, Copy)]
11pub enum Direction {
12    /// Caller to fixture.
13    Request,
14    /// Fixture to caller.
15    Response,
16}
17
18/// A bounded fixture protocol refusal.
19pub type Error = &'static str;
20
21/// Expected prefix for admission before copying the message body.
22#[must_use]
23pub fn header(method: u64, direction: Direction) -> [u8; HEADER_BYTES] {
24    let mut bytes = [0; HEADER_BYTES];
25    bytes[0] = match direction {
26        Direction::Request => 0xd2,
27        Direction::Response => 0xd3,
28    };
29    bytes[1..].copy_from_slice(&method.to_le_bytes());
30    bytes
31}
32
33struct FrameWriter {
34    bytes: Vec<u8>,
35    limit: usize,
36}
37
38impl postcard::ser_flavors::Flavor for FrameWriter {
39    type Output = Vec<u8>;
40
41    fn try_extend(&mut self, buf: &[u8]) -> postcard::Result<()> {
42        if buf.len() > self.limit - self.bytes.len() {
43            return Err(postcard::Error::SerializeBufferFull);
44        }
45        self.bytes.extend_from_slice(buf);
46
47        Ok(())
48    }
49
50    fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
51        self.try_extend(&[byte])
52    }
53
54    fn finalize(self) -> postcard::Result<Vec<u8>> {
55        Ok(self.bytes)
56    }
57}
58
59/// Encode a fixed fixture call without growing the frame beyond its allowance.
60/// # Errors
61/// Refuses oversized or unrepresentable messages.
62pub fn encode<T: Serialize + ?Sized>(
63    value: &T,
64    method: u64,
65    direction: Direction,
66    limit: usize,
67) -> Result<Vec<u8>, Error> {
68    if limit < HEADER_BYTES {
69        return Err("fixture frame exceeds byte allowance");
70    }
71    let writer = FrameWriter {
72        bytes: header(method, direction).to_vec(),
73        limit: limit.min(MAX_BYTES),
74    };
75    postcard::serialize_with_flavor(value, writer)
76        .map_err(|_| "fixture encoding failed or exceeded byte allowance")
77}
78
79/// Decode exactly one complete, bounded fixture frame.
80/// # Errors
81/// Refuses a wrong header, invalid or incomplete typed values, and trailing data.
82pub fn decode<T: DeserializeOwned>(
83    bytes: &[u8],
84    method: u64,
85    direction: Direction,
86    limit: usize,
87) -> Result<T, Error> {
88    if bytes.len() > limit.min(MAX_BYTES) {
89        return Err("fixture frame exceeds byte allowance");
90    }
91    let body = bytes
92        .strip_prefix(&header(method, direction))
93        .ok_or("invalid fixture header")?;
94    let (value, rest) = postcard::take_from_bytes(body).map_err(|_| "invalid fixture body")?;
95    if !rest.is_empty() {
96        return Err("trailing fixture bytes");
97    }
98
99    Ok(value)
100}