commonware-codec 2026.7.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Core traits for encoding and decoding.

use crate::error::Error;
#[cfg(not(feature = "std"))]
use alloc::{sync::Arc, vec::Vec};
use bytes::{Buf, BufMut, Bytes, BytesMut};
#[cfg(feature = "std")]
use std::{sync::Arc, 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);
        }
    }
}

impl<T: EncodeSize + ?Sized> EncodeSize for Arc<T> {
    #[inline]
    fn encode_size(&self) -> usize {
        self.as_ref().encode_size()
    }

    #[inline]
    fn encode_inline_size(&self) -> usize {
        self.as_ref().encode_inline_size()
    }
}

impl<T: Write + ?Sized> Write for Arc<T> {
    #[inline]
    fn write(&self, buf: &mut impl BufMut) {
        self.as_ref().write(buf);
    }

    #[inline]
    fn write_bufs(&self, buf: &mut impl BufsMut) {
        self.as_ref().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 for [FixedSize] types that can be decoded directly from a fixed-size array.
pub trait DecodeFixed: Read<Cfg = ()> + FixedSize {
    /// Decodes a value from a fixed-size byte array `[u8; N]`, ensuring all bytes are consumed.
    ///
    /// # Panics
    ///
    /// Panics if `N` is not equal to `<Self as FixedSize>::SIZE`.
    fn decode_fixed<const N: usize>(bytes: [u8; N]) -> Result<Self, Error> {
        assert_eq!(
            N,
            Self::SIZE,
            "Can't decode {} bytes into {} bytes",
            N,
            Self::SIZE
        );

        Self::decode_cfg(bytes.as_ref(), &())
    }
}

// Automatically implement `DecodeFixed` for types that implement `Read<Cfg = ()>` and `FixedSize`.
impl<T: Read<Cfg = ()> + FixedSize> DecodeFixed 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, FixedArray,
    };
    use bytes::Bytes;
    use core::marker::PhantomData;

    #[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]
    fn test_arc_encode() {
        let value = Arc::new(vec![1u8, 2, 3]);

        assert_eq!(value.encode(), value.as_ref().encode());
        assert_eq!(value.encode_size(), value.as_ref().encode_size());
    }

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

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    struct FixedBytes([u8; 2]);

    impl Write for FixedBytes {
        fn write(&self, buf: &mut impl BufMut) {
            self.0.write(buf);
        }
    }

    impl Read for FixedBytes {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self(<[u8; Self::SIZE]>::read(buf)?))
        }
    }

    impl FixedSize for FixedBytes {
        const SIZE: usize = 2;
    }

    #[test]
    fn test_fixed_array() {
        let value = FixedBytes([1, 2]);
        let encoded: [u8; FixedBytes::SIZE] = (&value).into();
        assert_eq!(encoded, [1, 2]);
        assert_eq!(<[u8; FixedBytes::SIZE]>::from(value), encoded);
        assert_eq!(FixedBytes::try_from(encoded).unwrap(), FixedBytes([1, 2]));
        assert_eq!(FixedBytes::try_from(&encoded).unwrap(), FixedBytes([1, 2]));
        assert_eq!(
            FixedBytes::try_from([1u8, 2].as_slice()).unwrap(),
            FixedBytes([1, 2])
        );
        assert!(matches!(
            FixedBytes::try_from([1u8].as_slice()),
            Err(Error::EndOfBuffer)
        ));
        assert!(matches!(
            FixedBytes::try_from([1u8, 2, 3].as_slice()),
            Err(Error::ExtraData(1))
        ));
    }

    #[test]
    fn test_decode_fixed() {
        assert_eq!(
            FixedBytes::decode_fixed([1, 2]).unwrap(),
            FixedBytes([1, 2])
        );
    }

    #[test]
    #[should_panic(expected = "Can't decode 3 bytes into 2 bytes")]
    fn test_decode_fixed_panic() {
        let _ = FixedBytes::decode_fixed([1, 2, 3]);
    }

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    #[fixed_array(infallible)]
    struct InfallibleFixedBytes([u8; 2]);

    impl Write for InfallibleFixedBytes {
        fn write(&self, buf: &mut impl BufMut) {
            self.0.write(buf);
        }
    }

    impl Read for InfallibleFixedBytes {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self(<[u8; Self::SIZE]>::read(buf)?))
        }
    }

    impl FixedSize for InfallibleFixedBytes {
        const SIZE: usize = 2;
    }

    #[test]
    fn test_fixed_array_infallible() {
        let value = InfallibleFixedBytes([1, 2]);
        let encoded: [u8; InfallibleFixedBytes::SIZE] = (&value).into();
        assert_eq!(encoded, [1, 2]);
        assert_eq!(<[u8; InfallibleFixedBytes::SIZE]>::from(value), encoded);
        assert_eq!(
            InfallibleFixedBytes::from(encoded),
            InfallibleFixedBytes([1, 2])
        );
        assert_eq!(
            InfallibleFixedBytes::from(&encoded),
            InfallibleFixedBytes([1, 2])
        );
        assert_eq!(
            InfallibleFixedBytes::try_from([1u8, 2].as_slice()).unwrap(),
            InfallibleFixedBytes([1, 2])
        );
        assert!(matches!(
            InfallibleFixedBytes::try_from([1u8, 2, 3].as_slice()),
            Err(Error::ExtraData(1))
        ));
    }

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    #[fixed_array(bytes([u8; N]))]
    struct GenericFixed<const N: usize>([u8; N]);

    impl<const N: usize> Write for GenericFixed<N> {
        fn write(&self, buf: &mut impl BufMut) {
            self.0.write(buf);
        }
    }

    impl<const N: usize> Read for GenericFixed<N> {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self(<[u8; N]>::read(buf)?))
        }
    }

    impl<const N: usize> FixedSize for GenericFixed<N> {
        const SIZE: usize = N;
    }

    #[test]
    fn test_fixed_array_generic() {
        let value = GenericFixed::<3>([1, 2, 3]);
        let encoded: [u8; 3] = (&value).into();
        assert_eq!(encoded, [1, 2, 3]);
        assert_eq!(<[u8; 3]>::from(value), encoded);
        assert_eq!(
            GenericFixed::<3>::try_from(encoded).unwrap(),
            GenericFixed([1, 2, 3])
        );
        assert_eq!(
            GenericFixed::<3>::try_from(&encoded).unwrap(),
            GenericFixed([1, 2, 3])
        );
        assert_eq!(
            GenericFixed::<3>::try_from([1u8, 2, 3].as_slice()).unwrap(),
            GenericFixed([1, 2, 3])
        );
    }

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    #[fixed_array(infallible, bytes([u8; N]))]
    struct GenericInfallible<const N: usize>([u8; N]);

    impl<const N: usize> Write for GenericInfallible<N> {
        fn write(&self, buf: &mut impl BufMut) {
            self.0.write(buf);
        }
    }

    impl<const N: usize> Read for GenericInfallible<N> {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self(<[u8; N]>::read(buf)?))
        }
    }

    impl<const N: usize> FixedSize for GenericInfallible<N> {
        const SIZE: usize = N;
    }

    #[test]
    fn test_fixed_array_generic_infallible() {
        let value = GenericInfallible::<3>([1, 2, 3]);
        let encoded: [u8; 3] = (&value).into();
        assert_eq!(encoded, [1, 2, 3]);
        assert_eq!(<[u8; 3]>::from(value), encoded);
        assert_eq!(
            GenericInfallible::<3>::from(encoded),
            GenericInfallible([1, 2, 3])
        );
        assert_eq!(
            GenericInfallible::<3>::from(&encoded),
            GenericInfallible([1, 2, 3])
        );
        assert_eq!(
            GenericInfallible::<3>::try_from([1u8, 2, 3].as_slice()).unwrap(),
            GenericInfallible([1, 2, 3])
        );
    }

    trait FixedArrayBound {}

    #[derive(Debug, Eq, PartialEq)]
    struct Bounded;

    impl FixedArrayBound for Bounded {}

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    #[fixed_array(bytes([u8; 2]))]
    struct BoundedGeneric<T> {
        marker: PhantomData<T>,
        raw: [u8; 2],
    }

    impl<T: FixedArrayBound> Write for BoundedGeneric<T> {
        fn write(&self, buf: &mut impl BufMut) {
            self.raw.write(buf);
        }
    }

    impl<T: FixedArrayBound> Read for BoundedGeneric<T> {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self {
                marker: PhantomData,
                raw: <[u8; 2]>::read(buf)?,
            })
        }
    }

    impl<T: FixedArrayBound> FixedSize for BoundedGeneric<T> {
        const SIZE: usize = 2;
    }

    #[test]
    fn test_fixed_array_bounded_generic() {
        let value = BoundedGeneric::<Bounded> {
            marker: PhantomData,
            raw: [1, 2],
        };
        let encoded: [u8; 2] = (&value).into();
        assert_eq!(encoded, [1, 2]);
        assert_eq!(<[u8; 2]>::from(value).as_ref(), &[1, 2]);
        assert_eq!(
            BoundedGeneric::<Bounded>::try_from(encoded).unwrap().raw,
            [1, 2]
        );
        assert_eq!(
            BoundedGeneric::<Bounded>::try_from(&encoded).unwrap().raw,
            [1, 2]
        );
        assert_eq!(
            BoundedGeneric::<Bounded>::try_from([1u8, 2].as_slice())
                .unwrap()
                .raw,
            [1, 2]
        );
    }

    #[derive(Debug, Eq, PartialEq, FixedArray)]
    #[fixed_array(bytes([u8; 2]))]
    struct LifetimeFixed<'a> {
        marker: PhantomData<&'a ()>,
        raw: [u8; 2],
    }

    impl Write for LifetimeFixed<'_> {
        fn write(&self, buf: &mut impl BufMut) {
            self.raw.write(buf);
        }
    }

    impl Read for LifetimeFixed<'_> {
        type Cfg = ();

        fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
            Ok(Self {
                marker: PhantomData,
                raw: <[u8; 2]>::read(buf)?,
            })
        }
    }

    impl FixedSize for LifetimeFixed<'_> {
        const SIZE: usize = 2;
    }

    #[test]
    fn test_fixed_array_lifetime() {
        let value = LifetimeFixed {
            marker: PhantomData,
            raw: [1, 2],
        };
        let encoded: [u8; LifetimeFixed::SIZE] = (&value).into();
        assert_eq!(encoded, [1, 2]);
        assert_eq!(<[u8; LifetimeFixed::SIZE]>::from(value).as_ref(), &[1, 2]);
        assert_eq!(LifetimeFixed::try_from(encoded).unwrap().raw, [1, 2]);
        assert_eq!(LifetimeFixed::try_from(&encoded).unwrap().raw, [1, 2]);
        assert_eq!(
            LifetimeFixed::try_from([1u8, 2].as_slice()).unwrap().raw,
            [1, 2]
        );
    }
}