Skip to main content

zaun_community_protocol/encoding/
writer.rs

1//! The canonical encoder.
2
3use super::{Encode, EncodeError};
4
5/// Appends canonical encodings to a buffer. Variable fields take their limit and fail above it,
6/// mirroring [`super::Reader`].
7#[derive(Debug, Default, Clone)]
8pub struct Writer {
9    buf: Vec<u8>,
10}
11
12fn length(len: usize, max: usize) -> Result<u32, EncodeError> {
13    let max = max.min(u32::MAX as usize);
14    if len > max {
15        return Err(EncodeError::OverLimit { len, max });
16    }
17    u32::try_from(len).map_err(|_| EncodeError::OverLimit { len, max })
18}
19
20impl Writer {
21    /// An empty writer.
22    #[must_use]
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// The encoding so far.
28    #[must_use]
29    pub fn into_bytes(self) -> Vec<u8> {
30        self.buf
31    }
32
33    /// `u8`.
34    pub fn u8(&mut self, value: u8) {
35        self.buf.push(value);
36    }
37
38    /// `u16`, big-endian.
39    pub fn u16(&mut self, value: u16) {
40        self.buf.extend_from_slice(&value.to_be_bytes());
41    }
42
43    /// `u32`, big-endian.
44    pub fn u32(&mut self, value: u32) {
45        self.buf.extend_from_slice(&value.to_be_bytes());
46    }
47
48    /// `u64`, big-endian.
49    pub fn u64(&mut self, value: u64) {
50        self.buf.extend_from_slice(&value.to_be_bytes());
51    }
52
53    /// `bool`: `0x00` or `0x01`.
54    pub fn bool(&mut self, value: bool) {
55        self.buf.push(u8::from(value));
56    }
57
58    /// `bytes[N]`: the bytes, no prefix.
59    pub fn fixed(&mut self, bytes: &[u8]) {
60        self.buf.extend_from_slice(bytes);
61    }
62
63    /// Variable `bytes`: `u32` length, then the bytes.
64    ///
65    /// # Errors
66    /// [`EncodeError::OverLimit`] when longer than `max`.
67    pub fn bytes(&mut self, bytes: &[u8], max: usize) -> Result<(), EncodeError> {
68        let len = length(bytes.len(), max)?;
69        self.u32(len);
70        self.fixed(bytes);
71        Ok(())
72    }
73
74    /// `string`: `u32` byte length, then UTF-8. `max` is in bytes.
75    ///
76    /// # Errors
77    /// [`EncodeError::OverLimit`] when longer than `max` bytes.
78    pub fn string(&mut self, text: &str, max: usize) -> Result<(), EncodeError> {
79        self.bytes(text.as_bytes(), max)
80    }
81
82    /// `option<T>`: `0x00`, or `0x01` then the value written by `f`.
83    ///
84    /// # Errors
85    /// Whatever `f` returns.
86    pub fn option<T>(
87        &mut self,
88        value: Option<&T>,
89        f: impl FnOnce(&mut Self, &T) -> Result<(), EncodeError>,
90    ) -> Result<(), EncodeError> {
91        match value {
92            None => {
93                self.u8(0);
94                Ok(())
95            }
96            Some(value) => {
97                self.u8(1);
98                f(self, value)
99            }
100        }
101    }
102
103    /// `list<T>`: `u32` count, then each element written by `f`.
104    ///
105    /// # Errors
106    /// [`EncodeError::OverLimit`] when more than `max` elements, or whatever `f` returns.
107    pub fn list<T>(
108        &mut self,
109        items: &[T],
110        max: usize,
111        mut f: impl FnMut(&mut Self, &T) -> Result<(), EncodeError>,
112    ) -> Result<(), EncodeError> {
113        let count = length(items.len(), max)?;
114        self.u32(count);
115        items.iter().try_for_each(|item| f(self, item))
116    }
117
118    /// Writes a value with a canonical encoding.
119    ///
120    /// # Errors
121    /// Whatever the value's encoder returns.
122    pub fn put<T: Encode + ?Sized>(&mut self, value: &T) -> Result<(), EncodeError> {
123        value.encode(self)
124    }
125}