commonware-codec 2026.5.0

Serialize structured data.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Core traits for encoding and decoding.

use crate::error::Error;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use bytes::{Buf, BufMut, Bytes, BytesMut};
#[cfg(feature = "std")]
use std::vec::Vec;

/// Trait for types with a known, fixed encoded size.
///
/// Implementing this trait signifies that the encoded representation of this type *always* has the
/// same byte length, regardless of the specific value.
///
/// This automatically provides an implementation of [EncodeSize].
pub trait FixedSize {
    /// The size of the encoded value (in bytes).
    const SIZE: usize;
}

/// Trait for types that can provide their encoded size in bytes.
///
/// This must be implemented by all encodable types. For types implementing [FixedSize], this
/// trait is implemented automatically. For variable-size types, this requires calculating the size
/// based on the value.
pub trait EncodeSize {
    /// Returns the encoded size of this value (in bytes).
    fn encode_size(&self) -> usize;

    /// Returns the total encoded size of a sequence, excluding any container-specific length
    /// prefix.
    ///
    /// Container implementations call this hook so element types can provide a more efficient
    /// aggregate size calculation. The default preserves normal element-by-element sizing.
    /// Fixed-size implementations compute `SIZE * len`, which avoids an O(n) sizing prepass
    /// before containers such as `Vec<T>` allocate their output buffer.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized
    /// container impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation because it is an implementation hook for
    /// codec's container types, not part of the intended user-facing API. Most users should
    /// implement [EncodeSize::encode_size] or [FixedSize] instead.
    #[doc(hidden)]
    #[inline]
    fn encode_size_slice(values: &[Self]) -> usize
    where
        Self: Sized,
    {
        values.iter().map(EncodeSize::encode_size).sum()
    }

    /// Returns the encoded size excluding bytes passed to [`BufsMut::push`]
    /// during [`Write::write_bufs`]. Used to size the working buffer for inline
    /// writes. Override alongside [`Write::write_bufs`] for types where large
    /// [`Bytes`] fields go via push; failing to do so will over-allocate.
    #[inline]
    fn encode_inline_size(&self) -> usize {
        self.encode_size()
    }

    /// Returns the total inline encoded size of a sequence, excluding any container-specific
    /// length prefix.
    ///
    /// This hidden hook is the slice equivalent of [EncodeSize::encode_inline_size]. The
    /// default preserves normal element-by-element sizing. Fixed-size implementations override
    /// this to compute `SIZE * len`, matching [EncodeSize::encode_size_slice] for the
    /// [`Write::write_bufs`] path.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized
    /// container impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation for the same reason as
    /// [EncodeSize::encode_size_slice].
    #[doc(hidden)]
    #[inline]
    fn encode_inline_size_slice(values: &[Self]) -> usize
    where
        Self: Sized,
    {
        values
            .iter()
            .map(EncodeSize::encode_inline_size)
            .sum::<usize>()
    }
}

// Automatically implement `EncodeSize` for types that are `FixedSize`.
impl<T: FixedSize> EncodeSize for T {
    #[inline]
    fn encode_size(&self) -> usize {
        Self::SIZE
    }

    #[inline]
    fn encode_size_slice(values: &[Self]) -> usize
    where
        Self: Sized,
    {
        Self::SIZE * values.len()
    }

    #[inline]
    fn encode_inline_size_slice(values: &[Self]) -> usize
    where
        Self: Sized,
    {
        Self::encode_size_slice(values)
    }
}

/// Trait for types that can be written (encoded) to a byte buffer.
pub trait Write {
    /// Writes the binary representation of `self` to the provided buffer `buf`.
    ///
    /// Implementations should panic if the buffer doesn't have enough capacity.
    fn write(&self, buf: &mut impl BufMut);

    /// Writes the encoded payload for a sequence, excluding any container-specific length
    /// prefix.
    ///
    /// Container implementations call this hook so element types can provide a more efficient
    /// aggregate write path. The default preserves normal element-by-element encoding.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized
    /// container impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation because it is an implementation hook for
    /// codec's container types, not part of the intended user-facing API. Most users should
    /// implement [Write::write] instead.
    #[doc(hidden)]
    #[inline]
    fn write_slice(values: &[Self], buf: &mut impl BufMut)
    where
        Self: Sized,
    {
        for item in values {
            item.write(buf);
        }
    }

    /// Writes to a [`BufsMut`], allowing existing [`Bytes`] chunks to be
    /// appended via [`BufsMut::push`] instead of written inline. Must encode
    /// to the same format as [`Write::write`]. Defaults to [`Write::write`].
    #[inline]
    fn write_bufs(&self, buf: &mut impl BufsMut) {
        self.write(buf);
    }

    /// Writes the encoded payload for a sequence to a [`BufsMut`], excluding any
    /// container-specific length prefix.
    ///
    /// This hidden hook is the slice equivalent of [Write::write_bufs]. The default preserves
    /// normal element-by-element encoding.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized
    /// container impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation for the same reason as [Write::write_slice].
    #[doc(hidden)]
    #[inline]
    fn write_slice_bufs(values: &[Self], buf: &mut impl BufsMut)
    where
        Self: Sized,
    {
        for item in values {
            item.write_bufs(buf);
        }
    }
}

/// Trait for types that can be read (decoded) from a byte buffer.
pub trait Read: Sized {
    /// The `Cfg` type parameter allows passing configuration during the read process. This is
    /// crucial for safely decoding untrusted data, for example, by providing size limits for
    /// collections or strings.
    ///
    /// Use `Cfg = ()` if no configuration is needed for a specific type.
    type Cfg: Clone + Send + Sync + 'static;

    /// Reads a value from the buffer using the provided configuration `cfg`.
    ///
    /// Implementations should consume the exact number of bytes required from `buf` to reconstruct
    /// the value.
    ///
    /// Returns [Error] if decoding fails due to invalid data, insufficient bytes in the buffer,
    /// or violation of constraints imposed by the `cfg`.
    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, Error>;

    /// Reads `len` values from the buffer into a vector.
    ///
    /// Container implementations call this hook so element types can provide a more efficient
    /// vector read path. The default preserves normal element-by-element decoding.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized
    /// container impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation because it is an implementation hook for
    /// codec's container types, not part of the intended user-facing API. Most users should
    /// implement [Read::read_cfg] instead.
    #[doc(hidden)]
    #[inline]
    fn read_vec(buf: &mut impl Buf, len: usize, cfg: &Self::Cfg) -> Result<Vec<Self>, Error> {
        let mut values = Vec::with_capacity(len);
        for _ in 0..len {
            values.push(Self::read_cfg(buf, cfg)?);
        }
        Ok(values)
    }

    /// Reads exactly `N` values from the buffer into an array.
    ///
    /// This hidden hook is the array equivalent of [Read::read_vec]. The default preserves
    /// normal element-by-element decoding.
    ///
    /// This hook exists because stable Rust cannot express the overlapping specialized array
    /// impls that would otherwise provide this aggregate path directly.
    ///
    /// This is hidden from generated documentation for the same reason as [Read::read_vec].
    #[doc(hidden)]
    #[inline]
    fn read_array<const N: usize>(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<[Self; N], Error> {
        Ok(Self::read_vec(buf, N, cfg)?
            .try_into()
            .unwrap_or_else(|_| unreachable!("array length should match capacity")))
    }
}

/// Trait combining [Write] and [EncodeSize] for types that can be fully encoded.
///
/// This trait provides the convenience [Encode::encode] method which handles
/// buffer allocation, writing, and size assertion in one go.
pub trait Encode: Write + EncodeSize {
    /// Encodes `self` into a new [Bytes] buffer.
    ///
    /// This method calculates the required size using [EncodeSize::encode_size], allocates a
    /// buffer of that exact capacity, writes the value using [Write::write], and performs a
    /// sanity check assertion.
    ///
    /// # Panics
    ///
    /// Panics if `encode_size()` does not return the same number of bytes actually written by
    /// `write()`
    fn encode(&self) -> Bytes {
        self.encode_mut().freeze()
    }

    /// Encodes `self` into a new [BytesMut] buffer.
    ///
    /// This method calculates the required size using [EncodeSize::encode_size], allocates a
    /// buffer of that exact capacity, writes the value using [Write::write], and performs a
    /// sanity check assertion.
    ///
    /// # Panics
    ///
    /// Panics if `encode_size()` does not return the same number of bytes actually written by
    /// `write()`
    fn encode_mut(&self) -> BytesMut {
        let len = self.encode_size();
        let mut buffer = BytesMut::with_capacity(len);
        self.write(&mut buffer);
        assert_eq!(buffer.len(), len, "write() did not write expected bytes");
        buffer
    }
}

// Automatically implement `Encode` for types that implement `Write` and `EncodeSize`.
impl<T: Write + EncodeSize> Encode for T {}

/// Convenience trait combining `Encode` with thread-safety bounds.
///
/// Represents types that can be fully encoded and safely shared across threads.
pub trait EncodeShared: Encode + Send + Sync {}

// Automatically implement `EncodeShared` for types that meet all bounds.
impl<T: Encode + Send + Sync> EncodeShared for T {}

/// Trait combining [Read] with a check for remaining bytes.
///
/// Ensures that *all* bytes from the input buffer were consumed during decoding.
pub trait Decode: Read {
    /// Decodes a value from `buf` using `cfg`, ensuring the entire buffer is consumed.
    ///
    /// Returns [Error] if decoding fails via [Read::read_cfg] or if there are leftover bytes in
    /// `buf` after reading.
    fn decode_cfg(mut buf: impl Buf, cfg: &Self::Cfg) -> Result<Self, Error> {
        let result = Self::read_cfg(&mut buf, cfg)?;

        // Check that the buffer is fully consumed.
        let remaining = buf.remaining();
        if remaining > 0 {
            return Err(Error::ExtraData(remaining));
        }

        Ok(result)
    }
}

// Automatically implement `Decode` for types that implement `Read`.
impl<T: Read> Decode for T {}

/// Convenience trait combining [Encode] and [Decode].
///
/// Represents types that can be both fully encoded and decoded.
pub trait Codec: Encode + Decode {}

/// Automatically implement `Codec` for types that implement `Encode` and `Decode`.
impl<T: Encode + Decode> Codec for T {}

/// Convenience trait for [FixedSize] types that can be encoded directly into a fixed-size array.
pub trait EncodeFixed: Write + FixedSize {
    /// Encodes `self` into a fixed-size byte array `[u8; N]`.
    ///
    /// # Panics
    ///
    /// Panics if `N` is not equal to `<Self as FixedSize>::SIZE`.
    /// Also panics if the `write()` implementation does not write exactly `N` bytes.
    fn encode_fixed<const N: usize>(&self) -> [u8; N] {
        // Ideally this is a compile-time check, but we can't do that in the current Rust version
        // without adding a new generic parameter to the trait.
        assert_eq!(
            N,
            Self::SIZE,
            "Can't encode {} bytes into {} bytes",
            Self::SIZE,
            N
        );

        let mut array = [0u8; N];
        let mut buf = &mut array[..];
        self.write(&mut buf);
        assert_eq!(buf.len(), 0);
        array
    }
}

// Automatically implement `EncodeFixed` for types that implement `Write` and `FixedSize`.
impl<T: Write + FixedSize> EncodeFixed for T {}

/// Convenience trait combining `FixedSize` and `Codec`.
///
/// Represents types that can be both fully encoded and decoded from a fixed-size byte sequence.
pub trait CodecFixed: Codec + FixedSize {}

// Automatically implement `CodecFixed` for types that implement `Codec` and `FixedSize`.
impl<T: Codec + FixedSize> CodecFixed for T {}

/// Convenience trait combining `Codec` with thread-safety bounds.
///
/// Represents types that can be fully encoded/decoded and safely shared across threads.
pub trait CodecShared: Codec + Send + Sync {}

// Automatically implement `CodecShared` for types that meet all bounds.
impl<T: Codec + Send + Sync> CodecShared for T {}

/// Convenience trait combining `CodecFixed` with thread-safety bounds and unit config.
///
/// Represents fixed-size types that can be fully encoded/decoded, require no configuration,
/// and can be safely shared across threads.
pub trait CodecFixedShared: CodecFixed<Cfg = ()> + Send + Sync {}

// Automatically implement `CodecFixedShared` for types that meet all bounds.
impl<T: CodecFixed<Cfg = ()> + Send + Sync> CodecFixedShared for T {}

/// A [`BufMut`] that can also append pre-existing [`Bytes`] chunks.
pub trait BufsMut: BufMut {
    /// Appends a [`Bytes`] chunk instead of writing its contents inline into
    /// the destination buffer.
    fn push(&mut self, bytes: impl Into<Bytes>);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        extensions::{DecodeExt, ReadExt},
        Error,
    };
    use bytes::Bytes;

    #[test]
    fn test_insufficient_buffer() {
        let mut reader = Bytes::from_static(&[0x01, 0x02]);
        assert!(matches!(u32::read(&mut reader), Err(Error::EndOfBuffer)));
    }

    #[test]
    fn test_extra_data() {
        let encoded = Bytes::from_static(&[0x01, 0x02]);
        assert!(matches!(u8::decode(encoded), Err(Error::ExtraData(1))));
    }

    #[test]
    fn test_encode_fixed() {
        let value = 42u32;
        let encoded: [u8; 4] = value.encode_fixed();
        let decoded = <u32>::decode(&encoded[..]).unwrap();
        assert_eq!(value, decoded);
    }

    #[test]
    #[should_panic(expected = "Can't encode 4 bytes into 5 bytes")]
    fn test_encode_fixed_panic() {
        let _: [u8; 5] = 42u32.encode_fixed();
    }
}