commonware_codec/
buffer.rs

1//! Buffer implementation of codec types.
2//!
3//! Numeric types are encoded in big-endian byte order.
4//!
5//! Prefixes varints for length-encoded data.
6
7use crate::{error::Error, varint};
8use bytes::{Buf, BufMut, Bytes, BytesMut};
9
10/// A buffer for reading codec data with safety checks
11#[derive(Debug)]
12pub struct ReadBuffer {
13    /// The underlying bytes
14    inner: Bytes,
15}
16
17impl ReadBuffer {
18    /// Creates a new reader from bytes
19    pub fn new(bytes: Bytes) -> Self {
20        Self { inner: bytes }
21    }
22
23    /// Reads a varint-encoded unsigned integer
24    #[inline]
25    pub fn read_varint(&mut self) -> Result<u64, Error> {
26        varint::decode_varint(&mut self.inner)
27    }
28
29    /// Gets a byte from the buffer
30    #[inline]
31    pub fn get_u8(&mut self) -> Result<u8, Error> {
32        self.at_least(1)?;
33        Ok(self.inner.get_u8())
34    }
35
36    /// Gets remaining bytes
37    #[inline]
38    pub fn remaining(&self) -> usize {
39        self.inner.remaining()
40    }
41
42    /// Checks if the buffer has any remaining bytes
43    #[inline]
44    pub fn has_remaining(&self) -> bool {
45        self.remaining() > 0
46    }
47
48    /// Ensures the buffer has at least `size` bytes remaining
49    #[inline]
50    pub fn at_least(&self, size: usize) -> Result<(), Error> {
51        if self.remaining() < size {
52            return Err(Error::EndOfBuffer);
53        }
54        Ok(())
55    }
56
57    /// Advance the buffer by `cnt` bytes
58    #[inline]
59    pub fn advance(&mut self, cnt: usize) {
60        self.inner.advance(cnt);
61    }
62
63    // Implement methods from Buf trait with safety checks
64    #[inline]
65    pub fn get_u16(&mut self) -> Result<u16, Error> {
66        self.at_least(2)?;
67        Ok(self.inner.get_u16())
68    }
69
70    #[inline]
71    pub fn get_u32(&mut self) -> Result<u32, Error> {
72        self.at_least(4)?;
73        Ok(self.inner.get_u32())
74    }
75
76    #[inline]
77    pub fn get_u64(&mut self) -> Result<u64, Error> {
78        self.at_least(8)?;
79        Ok(self.inner.get_u64())
80    }
81
82    #[inline]
83    pub fn get_u128(&mut self) -> Result<u128, Error> {
84        self.at_least(16)?;
85        Ok(self.inner.get_u128())
86    }
87
88    #[inline]
89    pub fn get_i8(&mut self) -> Result<i8, Error> {
90        self.at_least(1)?;
91        Ok(self.inner.get_i8())
92    }
93
94    #[inline]
95    pub fn get_i16(&mut self) -> Result<i16, Error> {
96        self.at_least(2)?;
97        Ok(self.inner.get_i16())
98    }
99
100    #[inline]
101    pub fn get_i32(&mut self) -> Result<i32, Error> {
102        self.at_least(4)?;
103        Ok(self.inner.get_i32())
104    }
105
106    #[inline]
107    pub fn get_i64(&mut self) -> Result<i64, Error> {
108        self.at_least(8)?;
109        Ok(self.inner.get_i64())
110    }
111
112    #[inline]
113    pub fn get_i128(&mut self) -> Result<i128, Error> {
114        self.at_least(16)?;
115        Ok(self.inner.get_i128())
116    }
117
118    #[inline]
119    pub fn get_f32(&mut self) -> Result<f32, Error> {
120        self.at_least(4)?;
121        Ok(self.inner.get_f32())
122    }
123
124    #[inline]
125    pub fn get_f64(&mut self) -> Result<f64, Error> {
126        self.at_least(8)?;
127        Ok(self.inner.get_f64())
128    }
129
130    #[inline]
131    pub fn copy_to_slice(&mut self, dst: &mut [u8]) -> Result<(), Error> {
132        self.at_least(dst.len())?;
133        self.inner.copy_to_slice(dst);
134        Ok(())
135    }
136
137    #[inline]
138    pub fn split_to(&mut self, size: usize) -> Result<Bytes, Error> {
139        self.at_least(size)?;
140        Ok(self.inner.split_to(size))
141    }
142
143    /// Returns a reference to the internal buffer
144    pub fn inner(&self) -> &Bytes {
145        &self.inner
146    }
147}
148
149/// A buffer for writing codec data
150#[derive(Debug)]
151pub struct WriteBuffer {
152    /// The underlying buffer
153    inner: BytesMut,
154}
155
156impl WriteBuffer {
157    /// Creates a new write buffer
158    pub fn new(capacity: usize) -> Self {
159        Self {
160            inner: BytesMut::with_capacity(capacity),
161        }
162    }
163
164    /// Writes a varint-encoded unsigned integer
165    #[inline]
166    pub fn write_varint(&mut self, value: u64) {
167        varint::encode_varint(value, &mut self.inner);
168    }
169
170    /// Returns the current length of the buffer
171    #[inline]
172    pub fn len(&self) -> usize {
173        self.inner.len()
174    }
175
176    /// Returns the total capacity of the buffer
177    #[inline]
178    pub fn capacity(&self) -> usize {
179        self.inner.capacity()
180    }
181
182    #[inline]
183    pub fn remaining_mut(&mut self) -> usize {
184        self.inner.remaining_mut()
185    }
186
187    /// Checks if the buffer is empty
188    #[inline]
189    pub fn is_empty(&self) -> bool {
190        self.inner.is_empty()
191    }
192
193    /// Freezes the buffer and returns the bytes
194    pub fn freeze(self) -> Bytes {
195        self.inner.freeze()
196    }
197
198    /// Resets the buffer
199    pub fn clear(&mut self) {
200        self.inner.clear();
201    }
202
203    // Delegate to inner buffer's BufMut implementation
204    #[inline]
205    pub fn put_u8(&mut self, v: u8) {
206        self.inner.put_u8(v);
207    }
208
209    #[inline]
210    pub fn put_u16(&mut self, v: u16) {
211        self.inner.put_u16(v);
212    }
213
214    #[inline]
215    pub fn put_u32(&mut self, v: u32) {
216        self.inner.put_u32(v);
217    }
218
219    #[inline]
220    pub fn put_u64(&mut self, v: u64) {
221        self.inner.put_u64(v);
222    }
223
224    #[inline]
225    pub fn put_u128(&mut self, v: u128) {
226        self.inner.put_u128(v);
227    }
228
229    #[inline]
230    pub fn put_i8(&mut self, v: i8) {
231        self.inner.put_i8(v);
232    }
233
234    #[inline]
235    pub fn put_i16(&mut self, v: i16) {
236        self.inner.put_i16(v);
237    }
238
239    #[inline]
240    pub fn put_i32(&mut self, v: i32) {
241        self.inner.put_i32(v);
242    }
243
244    #[inline]
245    pub fn put_i64(&mut self, v: i64) {
246        self.inner.put_i64(v);
247    }
248
249    #[inline]
250    pub fn put_i128(&mut self, v: i128) {
251        self.inner.put_i128(v);
252    }
253
254    #[inline]
255    pub fn put_f32(&mut self, v: f32) {
256        self.inner.put_f32(v);
257    }
258
259    #[inline]
260    pub fn put_f64(&mut self, v: f64) {
261        self.inner.put_f64(v);
262    }
263
264    #[inline]
265    pub fn put_slice(&mut self, src: &[u8]) {
266        self.inner.put_slice(src);
267    }
268}
269
270impl From<WriteBuffer> for Vec<u8> {
271    fn from(buffer: WriteBuffer) -> Self {
272        buffer.inner.to_vec()
273    }
274}
275
276impl From<WriteBuffer> for Bytes {
277    fn from(buffer: WriteBuffer) -> Self {
278        buffer.freeze()
279    }
280}
281
282impl AsRef<[u8]> for WriteBuffer {
283    fn as_ref(&self) -> &[u8] {
284        &self.inner
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::Reader;
292    use bytes::Bytes;
293
294    #[test]
295    fn test_read_buffer_split() {
296        let mut buffer = ReadBuffer::new(Bytes::from_static(&[0x01, 0x02, 0x03]));
297        let split = buffer.split_to(2).unwrap();
298        assert_eq!(split, Bytes::from_static(&[0x01, 0x02]));
299        assert_eq!(buffer.remaining(), 1);
300        assert_eq!(buffer.read_n_bytes(1).unwrap(), Bytes::from_static(&[0x03]));
301    }
302
303    #[test]
304    fn test_write_buffer_append() {
305        let mut writer = WriteBuffer::new(4);
306        writer.put_u32(0x01020304);
307        let frozen = writer.freeze();
308        assert_eq!(frozen, Bytes::from_static(&[0x01, 0x02, 0x03, 0x04]));
309    }
310
311    #[test]
312    fn test_buffer_remaining() {
313        let mut buffer = ReadBuffer::new(Bytes::from_static(&[0x01, 0x02, 0x03]));
314        assert_eq!(buffer.remaining(), 3);
315        let _ = buffer.read_n_bytes(2).unwrap();
316        assert_eq!(buffer.remaining(), 1);
317    }
318}