Skip to main content

astrs_wire/
codec.rs

1//! The payload codec: one configuration, exact size hints, no trailing bytes.
2//!
3//! Blueprint §7.1 fixes the payload encoding to **oxicode with a little-endian,
4//! varint configuration**, requires `encode_size_hint()` on every
5//! payload-carrying type so buffers can be pre-sized exactly, and requires the
6//! decoder to **reject trailing bytes**.
7//!
8//! Those three rules are expressed here as [`WIRE_CONFIG`], [`WireEncode`] and
9//! [`WireDecode`]. Both traits have blanket implementations over
10//! [`oxicode::Encode`] / [`oxicode::Decode`], so every wire type in this crate
11//! gets them by deriving the two oxicode traits — there is exactly one codec
12//! and no type can opt into a different one.
13//!
14//! # Why trailing bytes are fatal
15//!
16//! A decoder that stops at the end of a message it recognises and ignores what
17//! follows will happily accept a payload written by a peer with a *different*
18//! idea of the message's shape. The mismatch then surfaces later, somewhere
19//! unrelated, as corrupt data. Rejecting the remainder turns a silent
20//! compatibility break into an immediate, named error at the connection that
21//! caused it.
22//!
23//! # Examples
24//!
25//! ```
26//! use astrs_wire::{WireDecode, WireEncode, WireError};
27//!
28//! let value: u32 = 4_242;
29//! let bytes = value.encode_to_vec()?;
30//! assert_eq!(bytes.len(), value.encode_size_hint()?);
31//! assert_eq!(u32::decode_exact(&bytes)?, 4_242);
32//!
33//! // One extra byte is an error, never a shrug.
34//! let mut corrupted = bytes.clone();
35//! corrupted.push(0);
36//! assert!(matches!(
37//!     u32::decode_exact(&corrupted),
38//!     Err(WireError::TrailingBytes { .. })
39//! ));
40//! # Ok::<(), astrs_wire::WireError>(())
41//! ```
42
43use oxicode::config::Configuration;
44use oxicode::enc::Writer;
45
46use crate::error::{WireError, WireResult};
47
48/// The one and only payload codec configuration: little-endian, varint,
49/// no built-in length limit.
50///
51/// The limit is deliberately left to [`crate::FrameLimits`], which enforces it
52/// on the frame as a whole rather than per nested collection — one cap, checked
53/// in one place, before any allocation.
54pub type WireConfig = Configuration;
55
56/// The payload codec configuration mandated by blueprint §7.1.
57///
58/// # Examples
59///
60/// ```
61/// // Varint encoding: a small integer costs one byte, not four.
62/// let bytes = oxicode::encode_to_vec_with_config(&1u32, astrs_wire::WIRE_CONFIG)?;
63/// assert_eq!(bytes, vec![1]);
64/// # Ok::<(), oxicode::error::Error>(())
65/// ```
66pub const WIRE_CONFIG: WireConfig = oxicode::config::standard();
67
68/// A [`Writer`] that appends to a caller-owned [`Vec<u8>`].
69///
70/// `oxicode::enc::VecWriter` owns its buffer, which would force an extra
71/// allocation and copy every time a payload is appended to a frame that
72/// already contains a header. This adapter writes straight into the tail of an
73/// existing buffer instead.
74struct VecAppendWriter<'a> {
75    /// The buffer being appended to.
76    out: &'a mut Vec<u8>,
77}
78
79impl Writer for VecAppendWriter<'_> {
80    fn write(&mut self, bytes: &[u8]) -> Result<(), oxicode::error::Error> {
81        self.out.extend_from_slice(bytes);
82        Ok(())
83    }
84}
85
86/// Encoding half of the wire codec.
87///
88/// Implemented blanket-style for every [`oxicode::Encode`] type, so wire
89/// messages acquire it by `#[derive(oxicode::Encode)]`.
90///
91/// [`WireEncode::encode_size_hint`] is **exact**, not an estimate: it performs
92/// a real size pass with `oxicode`'s counting writer. Every other method
93/// depends on that exactness, and [`WireEncode::encode_presized`] verifies it
94/// on every call.
95pub trait WireEncode {
96    /// The exact number of bytes [`WireEncode::encode_presized`] will produce.
97    ///
98    /// # Errors
99    ///
100    /// Returns [`WireError::Codec`] if the value cannot be encoded at all
101    /// (for instance a collection longer than `u64::MAX`).
102    ///
103    /// # Examples
104    ///
105    /// ```
106    /// use astrs_wire::WireEncode;
107    ///
108    /// // Varint: 300 needs more than one byte, 1 does not.
109    /// assert_eq!(1u32.encode_size_hint()?, 1);
110    /// assert!(300u32.encode_size_hint()? > 1);
111    /// # Ok::<(), astrs_wire::WireError>(())
112    /// ```
113    fn encode_size_hint(&self) -> WireResult<usize>;
114
115    /// Appends the encoded form to `out`, reserving the exact space first.
116    ///
117    /// Returns the number of bytes appended. `out` is left untouched — not
118    /// merely truncated back to a plausible length, but restored to its
119    /// original length — if encoding fails part-way through.
120    ///
121    /// # Errors
122    ///
123    /// - [`WireError::Codec`] if the value cannot be encoded.
124    /// - [`WireError::SizeHintMismatch`] if the number of bytes written differs
125    ///   from [`WireEncode::encode_size_hint`], which indicates a broken
126    ///   `oxicode::Encode` implementation.
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use astrs_wire::WireEncode;
132    ///
133    /// let mut buffer = vec![0xAA];
134    /// let written = 7u32.encode_presized(&mut buffer)?;
135    /// assert_eq!(written, 1);
136    /// assert_eq!(buffer, vec![0xAA, 7]);
137    /// # Ok::<(), astrs_wire::WireError>(())
138    /// ```
139    fn encode_presized(&self, out: &mut Vec<u8>) -> WireResult<usize>;
140
141    /// Encodes into a freshly allocated, exactly-sized [`Vec<u8>`].
142    ///
143    /// # Errors
144    ///
145    /// As [`WireEncode::encode_presized`].
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use astrs_wire::WireEncode;
151    ///
152    /// let bytes = (-1i32).encode_to_vec()?;
153    /// assert!(!bytes.is_empty());
154    /// # Ok::<(), astrs_wire::WireError>(())
155    /// ```
156    fn encode_to_vec(&self) -> WireResult<Vec<u8>> {
157        let hint = self.encode_size_hint()?;
158        let mut out = Vec::with_capacity(hint);
159        self.encode_presized(&mut out)?;
160        Ok(out)
161    }
162}
163
164impl<T: oxicode::Encode> WireEncode for T {
165    fn encode_size_hint(&self) -> WireResult<usize> {
166        Ok(oxicode::encoded_size_with_config(self, WIRE_CONFIG)?)
167    }
168
169    fn encode_presized(&self, out: &mut Vec<u8>) -> WireResult<usize> {
170        let hint = self.encode_size_hint()?;
171        let start = out.len();
172        out.reserve(hint);
173
174        let result = {
175            let writer = VecAppendWriter { out };
176            oxicode::encode_into_writer(self, writer, WIRE_CONFIG)
177        };
178        if let Err(err) = result {
179            out.truncate(start);
180            return Err(WireError::Codec(err));
181        }
182
183        let written = out.len() - start;
184        if written != hint {
185            out.truncate(start);
186            return Err(WireError::SizeHintMismatch { hint, written });
187        }
188        Ok(written)
189    }
190}
191
192/// Decoding half of the wire codec.
193///
194/// Implemented blanket-style for every [`oxicode::Decode`] type.
195pub trait WireDecode: Sized {
196    /// Decodes a value that must occupy **all** of `bytes`.
197    ///
198    /// # Errors
199    ///
200    /// - [`WireError::Codec`] if the bytes are not a valid encoding.
201    /// - [`WireError::TrailingBytes`] if a value decoded successfully but did
202    ///   not consume the whole slice.
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// use astrs_wire::{WireDecode, WireEncode};
208    ///
209    /// let bytes = "camera".to_owned().encode_to_vec()?;
210    /// assert_eq!(String::decode_exact(&bytes)?, "camera");
211    /// # Ok::<(), astrs_wire::WireError>(())
212    /// ```
213    fn decode_exact(bytes: &[u8]) -> WireResult<Self>;
214
215    /// Decodes a value from the front of `bytes`, returning it together with
216    /// the number of bytes consumed.
217    ///
218    /// Unlike [`WireDecode::decode_exact`] this tolerates a remainder — it
219    /// exists for callers that are parsing a concatenation they framed
220    /// themselves (the protocol snapshot writer, for one), never for frame
221    /// payloads.
222    ///
223    /// # Errors
224    ///
225    /// [`WireError::Codec`] if the prefix is not a valid encoding.
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use astrs_wire::{WireDecode, WireEncode};
231    ///
232    /// let mut bytes = 9u16.encode_to_vec()?;
233    /// bytes.extend_from_slice(b"tail");
234    /// let (value, consumed) = u16::decode_prefix(&bytes)?;
235    /// assert_eq!(value, 9);
236    /// assert_eq!(&bytes[consumed..], b"tail");
237    /// # Ok::<(), astrs_wire::WireError>(())
238    /// ```
239    fn decode_prefix(bytes: &[u8]) -> WireResult<(Self, usize)>;
240}
241
242impl<T: oxicode::Decode> WireDecode for T {
243    fn decode_exact(bytes: &[u8]) -> WireResult<Self> {
244        let (value, consumed) = Self::decode_prefix(bytes)?;
245        if consumed != bytes.len() {
246            return Err(WireError::TrailingBytes {
247                consumed,
248                trailing: bytes.len() - consumed,
249            });
250        }
251        Ok(value)
252    }
253
254    fn decode_prefix(bytes: &[u8]) -> WireResult<(Self, usize)> {
255        Ok(oxicode::decode_from_slice_with_config(bytes, WIRE_CONFIG)?)
256    }
257}
258
259/// Round-trips a value through the wire codec.
260///
261/// A convenience for tests and for callers that need a deep copy of a message
262/// with wire semantics (i.e. one that proves the value survives the wire).
263///
264/// # Errors
265///
266/// Any [`WireError`] raised by encoding or decoding.
267///
268/// # Examples
269///
270/// ```
271/// use astrs_wire::codec::round_trip;
272///
273/// assert_eq!(round_trip(&vec![1u8, 2, 3])?, vec![1, 2, 3]);
274/// # Ok::<(), astrs_wire::WireError>(())
275/// ```
276pub fn round_trip<T>(value: &T) -> WireResult<T>
277where
278    T: oxicode::Encode + oxicode::Decode,
279{
280    let bytes = value.encode_to_vec()?;
281    T::decode_exact(&bytes)
282}
283
284#[cfg(test)]
285mod tests {
286    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
287
288    use std::collections::BTreeMap;
289
290    use super::*;
291
292    #[test]
293    fn config_is_little_endian_varint() {
294        // Varint: values below 251 occupy a single byte in oxicode's varint
295        // encoding, and multi-byte forms are little-endian.
296        let one = oxicode::encode_to_vec_with_config(&1u32, WIRE_CONFIG).unwrap();
297        assert_eq!(one, vec![1]);
298
299        let large = oxicode::encode_to_vec_with_config(&0x0102_0304u32, WIRE_CONFIG).unwrap();
300        // Marker byte followed by little-endian bytes.
301        assert!(large.len() > 1);
302        assert_eq!(&large[1..], &[0x04, 0x03, 0x02, 0x01]);
303    }
304
305    #[test]
306    fn size_hint_is_exact_for_a_range_of_shapes() {
307        macro_rules! check {
308            ($value:expr) => {{
309                let value = $value;
310                let hint = value.encode_size_hint().unwrap();
311                let bytes = value.encode_to_vec().unwrap();
312                assert_eq!(hint, bytes.len(), "hint mismatch for {:?}", value);
313            }};
314        }
315
316        check!(0u8);
317        check!(u64::MAX);
318        check!(-1i64);
319        check!(1.5f64);
320        check!(String::from("astrs"));
321        check!(vec![0u8; 1000]);
322        check!(Some(7u32));
323        check!(Option::<u32>::None);
324        check!(BTreeMap::from([(1u8, "a".to_owned()), (2, "b".to_owned())]));
325        check!((1u8, 2u16, 3u32));
326    }
327
328    #[test]
329    fn encode_presized_appends_without_disturbing_the_prefix() {
330        let mut buffer = b"header".to_vec();
331        let written = vec![1u8, 2, 3].encode_presized(&mut buffer).unwrap();
332        assert_eq!(&buffer[..6], b"header");
333        assert_eq!(buffer.len(), 6 + written);
334    }
335
336    #[test]
337    fn encode_presized_reserves_exactly_the_hint() {
338        let value = vec![7u8; 4096];
339        let hint = value.encode_size_hint().unwrap();
340        let mut buffer = Vec::new();
341        let written = value.encode_presized(&mut buffer).unwrap();
342        assert_eq!(written, hint);
343        assert_eq!(buffer.len(), hint);
344    }
345
346    #[test]
347    fn decode_exact_rejects_trailing_bytes() {
348        let mut bytes = 1234u32.encode_to_vec().unwrap();
349        let good = bytes.len();
350        bytes.extend_from_slice(&[0, 0, 0]);
351        match u32::decode_exact(&bytes) {
352            Err(WireError::TrailingBytes { consumed, trailing }) => {
353                assert_eq!(consumed, good);
354                assert_eq!(trailing, 3);
355            }
356            other => panic!("expected TrailingBytes, got {other:?}"),
357        }
358    }
359
360    #[test]
361    fn decode_exact_rejects_truncated_input() {
362        let bytes = String::from("hello").encode_to_vec().unwrap();
363        let err = String::decode_exact(&bytes[..bytes.len() - 1]).unwrap_err();
364        assert!(matches!(err, WireError::Codec(_)));
365    }
366
367    #[test]
368    fn decode_prefix_tolerates_a_remainder() {
369        let mut bytes = 9u16.encode_to_vec().unwrap();
370        bytes.extend_from_slice(b"rest");
371        let (value, consumed) = u16::decode_prefix(&bytes).unwrap();
372        assert_eq!(value, 9);
373        assert_eq!(&bytes[consumed..], b"rest");
374    }
375
376    #[test]
377    fn round_trip_preserves_nested_collections() {
378        let value: BTreeMap<String, Vec<u32>> =
379            BTreeMap::from([("a".to_owned(), vec![1, 2, 3]), ("b".to_owned(), vec![])]);
380        assert_eq!(round_trip(&value).unwrap(), value);
381    }
382
383    #[test]
384    fn empty_input_decodes_only_zero_sized_shapes() {
385        assert_eq!(<()>::decode_exact(&[]).unwrap(), ());
386        assert!(u8::decode_exact(&[]).is_err());
387    }
388
389    #[test]
390    fn encoding_is_deterministic() {
391        let value = BTreeMap::from([(3u8, "c"), (1, "a"), (2, "b")]);
392        let first = value.encode_to_vec().unwrap();
393        let second = value.encode_to_vec().unwrap();
394        assert_eq!(first, second);
395    }
396}