Skip to main content

microrti_encoding/
buffer.rs

1//! Byte buffers used while encoding and decoding.
2//!
3//! Both sides track the offset from the start of the outermost value, because every padding rule of the
4//! HLA encodings is expressed relative to that offset (the Java API does the same in `ByteWrapper.align`).
5
6use crate::error::{DecoderError, EncoderError};
7
8/// Octet boundary of the element count that starts every `HLAvariableArray`.
9pub(crate) const COUNT_BOUNDARY: usize = 4;
10
11/// Largest of the given octet boundaries, 1 for an empty list. Usable in constants.
12pub const fn max_boundary(boundaries: &[usize]) -> usize {
13    let mut max = 1;
14    let mut index = 0;
15    while index < boundaries.len() {
16        if boundaries[index] > max {
17            max = boundaries[index];
18        }
19        index += 1;
20    }
21    max
22}
23
24/// Number of padding octets needed at `offset` to reach the next multiple of `boundary`.
25pub const fn padding_for(offset: usize, boundary: usize) -> usize {
26    if boundary <= 1 { 0 } else { (boundary - offset % boundary) % boundary }
27}
28
29/// Destination of an encoding.
30///
31/// A writer either appends to a `Vec<u8>` or only counts octets ([`ByteWriter::counter`]), which is how
32/// encoded lengths are computed with the very same code that encodes.
33///
34/// Typed encoders cannot return errors; the rare failures (an array with more than `i32::MAX` elements)
35/// are recorded with [`ByteWriter::fail`] and reported by [`ByteWriter::status`].
36#[derive(Debug)]
37pub struct ByteWriter<'a> {
38    buffer: Option<&'a mut Vec<u8>>,
39    position: usize,
40    error: Option<EncoderError>,
41}
42
43impl<'a> ByteWriter<'a> {
44    /// Starts a new outermost value at the current end of `buffer`.
45    pub fn new(buffer: &'a mut Vec<u8>) -> Self {
46        Self { buffer: Some(buffer), position: 0, error: None }
47    }
48
49    /// A writer that stores nothing and only counts the octets written.
50    pub fn counter() -> ByteWriter<'static> {
51        ByteWriter { buffer: None, position: 0, error: None }
52    }
53
54    /// Octets written since the start of the outermost value.
55    pub fn position(&self) -> usize {
56        self.position
57    }
58
59    /// Writes zero octets until the position is a multiple of `boundary`.
60    pub fn align(&mut self, boundary: usize) {
61        let padding = padding_for(self.position, boundary);
62        if padding > 0 {
63            if let Some(buffer) = self.buffer.as_deref_mut() {
64                buffer.resize(buffer.len() + padding, 0);
65            }
66            self.position += padding;
67        }
68    }
69
70    /// Writes one octet.
71    pub fn put_u8(&mut self, octet: u8) {
72        self.put_slice(&[octet]);
73    }
74
75    /// Writes octets as they are.
76    pub fn put_slice(&mut self, octets: &[u8]) {
77        if let Some(buffer) = self.buffer.as_deref_mut() {
78            buffer.extend_from_slice(octets);
79        }
80        self.position += octets.len();
81    }
82
83    /// Writes the element count of a variable array (`HLAinteger32BE`, no alignment is performed).
84    ///
85    /// A count above `i32::MAX` records [`EncoderError::TooManyElements`].
86    pub fn put_count(&mut self, count: usize) {
87        let encoded = match i32::try_from(count) {
88            Ok(value) => value,
89            Err(_) => {
90                self.fail(EncoderError::TooManyElements { count });
91                i32::MAX
92            }
93        };
94        self.put_slice(&encoded.to_be_bytes());
95    }
96
97    /// Records that the value being written cannot be encoded. The first error wins.
98    pub fn fail(&mut self, error: EncoderError) {
99        self.error.get_or_insert(error);
100    }
101
102    /// `Err` with the first recorded error, `Ok` if the encoding is sound so far.
103    pub fn status(&self) -> Result<(), EncoderError> {
104        match &self.error {
105            Some(error) => Err(error.clone()),
106            None => Ok(()),
107        }
108    }
109}
110
111/// Source of a decoding: a cursor over a byte slice.
112///
113/// Every read is bounds checked and returns [`DecoderError::Truncated`] instead of panicking.
114#[derive(Debug, Clone)]
115pub struct ByteReader<'a> {
116    data: &'a [u8],
117    position: usize,
118}
119
120impl<'a> ByteReader<'a> {
121    /// Starts decoding an outermost value at the beginning of `data`.
122    pub fn new(data: &'a [u8]) -> Self {
123        Self { data, position: 0 }
124    }
125
126    /// Octets consumed since the start of the outermost value.
127    pub fn position(&self) -> usize {
128        self.position
129    }
130
131    /// Octets left.
132    pub fn remaining(&self) -> usize {
133        self.data.len() - self.position
134    }
135
136    /// True when every octet has been consumed.
137    pub fn is_empty(&self) -> bool {
138        self.remaining() == 0
139    }
140
141    /// Skips padding octets until the position is a multiple of `boundary`. Padding content is ignored.
142    pub fn align(&mut self, boundary: usize) -> Result<(), DecoderError> {
143        self.take(padding_for(self.position, boundary)).map(|_| ())
144    }
145
146    /// Consumes `len` octets.
147    pub fn take(&mut self, len: usize) -> Result<&'a [u8], DecoderError> {
148        let remaining = self.remaining();
149        if len > remaining {
150            return Err(DecoderError::Truncated { offset: self.position, needed: len, remaining });
151        }
152        let start = self.position;
153        self.position += len;
154        Ok(&self.data[start..self.position])
155    }
156
157    /// Consumes exactly `N` octets.
158    pub fn take_array<const N: usize>(&mut self) -> Result<[u8; N], DecoderError> {
159        let mut octets = [0u8; N];
160        octets.copy_from_slice(self.take(N)?);
161        Ok(octets)
162    }
163
164    /// Consumes one octet.
165    pub fn read_u8(&mut self) -> Result<u8, DecoderError> {
166        let [octet] = self.take_array::<1>()?;
167        Ok(octet)
168    }
169
170    /// Reads the element count of a variable array (`HLAinteger32BE`, no alignment is performed).
171    ///
172    /// Negative counts are rejected, and so are counts larger than the number of octets left: an element
173    /// of any real datatype takes at least one octet, and refusing early keeps hostile counts from
174    /// driving allocations. The price is that an array of zero-length elements (an array of empty fixed
175    /// arrays, say) only decodes while its count does not exceed the octets that follow it.
176    pub fn read_count(&mut self) -> Result<usize, DecoderError> {
177        let raw = i32::from_be_bytes(self.take_array()?);
178        let count = usize::try_from(raw).map_err(|_| DecoderError::InvalidCount { count: raw })?;
179        let remaining = self.remaining();
180        if count > remaining {
181            return Err(DecoderError::CountExceedsInput { count, remaining });
182        }
183        Ok(count)
184    }
185
186    /// Splits off the next `len` octets as a reader of their own. Offsets (and therefore padding) stay
187    /// relative to the outermost value.
188    pub fn window(&mut self, len: usize) -> Result<ByteReader<'a>, DecoderError> {
189        let remaining = self.remaining();
190        if len > remaining {
191            return Err(DecoderError::Truncated { offset: self.position, needed: len, remaining });
192        }
193        let start = self.position;
194        self.position += len;
195        Ok(ByteReader { data: &self.data[..self.position], position: start })
196    }
197
198    /// Fails with [`DecoderError::TrailingBytes`] unless every octet has been consumed.
199    pub fn expect_end(&self) -> Result<(), DecoderError> {
200        match self.remaining() {
201            0 => Ok(()),
202            count => Err(DecoderError::TrailingBytes { count }),
203        }
204    }
205}