commonware_utils/sequence/
unit.rs

1use crate::{Array, Span};
2use bytes::{Buf, BufMut};
3use commonware_codec::{FixedSize, Read, Write};
4use core::{
5    fmt::{Debug, Display},
6    ops::Deref,
7};
8
9/// An `Array` implementation for the unit type `()`.
10#[derive(Clone, Copy, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
11#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
12pub struct Unit;
13
14impl Write for Unit {
15    fn write(&self, _: &mut impl BufMut) {}
16}
17
18impl FixedSize for Unit {
19    const SIZE: usize = 0;
20}
21
22impl Read for Unit {
23    type Cfg = ();
24
25    fn read_cfg(_buf: &mut impl Buf, _: &()) -> Result<Self, commonware_codec::Error> {
26        Ok(Self)
27    }
28}
29
30impl Debug for Unit {
31    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
32        write!(f, "()")
33    }
34}
35
36impl Display for Unit {
37    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
38        write!(f, "()")
39    }
40}
41
42impl Deref for Unit {
43    type Target = [u8];
44
45    fn deref(&self) -> &Self::Target {
46        &[]
47    }
48}
49
50impl AsRef<[u8]> for Unit {
51    fn as_ref(&self) -> &[u8] {
52        &[]
53    }
54}
55
56impl Span for Unit {}
57impl Array for Unit {}
58
59#[cfg(test)]
60mod test {
61    use super::*;
62    use commonware_codec::Encode;
63
64    #[test]
65    fn test_debug_display() {
66        let unit = Unit;
67        assert_eq!(format!("{unit:?}"), "()");
68        assert_eq!(unit.to_string(), "()");
69    }
70
71    #[test]
72    fn test_deref_asref() {
73        let unit = Unit;
74        assert_eq!(unit.deref(), &[]);
75        assert_eq!(unit.as_ref(), &[]);
76    }
77
78    #[test]
79    fn test_codec() {
80        let mut encoded = Unit.encode();
81        assert_eq!(encoded.len(), 0);
82
83        let decoded = Unit::read_cfg(&mut encoded, &()).unwrap();
84        assert_eq!(decoded, Unit);
85    }
86
87    #[cfg(feature = "arbitrary")]
88    mod conformance {
89        use super::*;
90        use commonware_codec::conformance::CodecConformance;
91
92        commonware_conformance::conformance_tests! {
93            CodecConformance<Unit>,
94        }
95    }
96}