1use crate::{hex, Array};
2use bytes::{Buf, BufMut};
3use commonware_codec::{Error as CodecError, FixedSize, Read, ReadExt, Write};
4use std::{
5 cmp::{Ord, PartialOrd},
6 fmt::{Debug, Display},
7 hash::Hash,
8 ops::Deref,
9};
10use thiserror::Error;
11
12#[derive(Error, Debug, PartialEq)]
14pub enum Error {
15 #[error("invalid length")]
16 InvalidLength,
17}
18
19#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
21#[repr(transparent)]
22pub struct FixedBytes<const N: usize>([u8; N]);
23
24impl<const N: usize> FixedBytes<N> {
25 pub fn new(value: [u8; N]) -> Self {
27 Self(value)
28 }
29}
30
31impl<const N: usize> Write for FixedBytes<N> {
32 fn write(&self, buf: &mut impl BufMut) {
33 self.0.write(buf);
34 }
35}
36
37impl<const N: usize> Read for FixedBytes<N> {
38 type Cfg = ();
39
40 fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
41 Ok(Self(<[u8; N]>::read(buf)?))
42 }
43}
44
45impl<const N: usize> FixedSize for FixedBytes<N> {
46 const SIZE: usize = N;
47}
48
49impl<const N: usize> Array for FixedBytes<N> {}
50
51impl<const N: usize> AsRef<[u8]> for FixedBytes<N> {
52 fn as_ref(&self) -> &[u8] {
53 &self.0
54 }
55}
56
57impl<const N: usize> Deref for FixedBytes<N> {
58 type Target = [u8];
59 fn deref(&self) -> &[u8] {
60 &self.0
61 }
62}
63
64impl<const N: usize> Display for FixedBytes<N> {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 write!(f, "{}", hex(&self.0))
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73 use bytes::{Buf, BytesMut};
74 use commonware_codec::{DecodeExt, Encode};
75
76 #[test]
77 fn test_codec() {
78 let original = FixedBytes::new([1, 2, 3, 4]);
79 let encoded = original.encode();
80 assert_eq!(encoded.len(), original.len());
81 let decoded = FixedBytes::decode(encoded).unwrap();
82 assert_eq!(original, decoded);
83 }
84
85 #[test]
86 fn test_bytes_creation_and_conversion() {
87 let value = [1, 2, 3, 4];
88 let bytes = FixedBytes::new(value);
89 assert_eq!(bytes.as_ref(), &value);
90
91 let slice = [1, 2, 3, 4];
92 let bytes_from_slice = FixedBytes::decode(slice.as_ref()).unwrap();
93 assert_eq!(bytes_from_slice, bytes);
94
95 let vec = vec![1, 2, 3, 4];
96 let bytes_from_vec = FixedBytes::decode(vec.as_ref()).unwrap();
97 assert_eq!(bytes_from_vec, bytes);
98
99 let slice_too_short = [1, 2, 3];
101 assert!(matches!(
102 FixedBytes::<4>::decode(slice_too_short.as_ref()),
103 Err(CodecError::EndOfBuffer)
104 ));
105
106 let vec_too_long = vec![1, 2, 3, 4, 5];
107 assert!(matches!(
108 FixedBytes::<4>::decode(vec_too_long.as_ref()),
109 Err(CodecError::ExtraData(1))
110 ));
111 }
112
113 #[test]
114 fn test_read() {
115 let mut buf = BytesMut::from(&[1, 2, 3, 4][..]);
116 let bytes = FixedBytes::<4>::read(&mut buf).unwrap();
117 assert_eq!(bytes.as_ref(), &[1, 2, 3, 4]);
118 assert_eq!(buf.remaining(), 0);
119
120 let mut buf = BytesMut::from(&[1, 2, 3][..]);
121 let result = FixedBytes::<4>::read(&mut buf);
122 assert!(matches!(result, Err(CodecError::EndOfBuffer)));
123
124 let mut buf = BytesMut::from(&[1, 2, 3, 4, 5][..]);
125 let bytes = FixedBytes::<4>::read(&mut buf).unwrap();
126 assert_eq!(bytes.as_ref(), &[1, 2, 3, 4]);
127 assert_eq!(buf.remaining(), 1);
128 assert_eq!(buf[0], 5);
129 }
130
131 #[test]
132 fn test_display() {
133 let bytes = FixedBytes::new([0x01, 0x02, 0x03, 0x04]);
134 assert_eq!(format!("{}", bytes), "01020304");
135 }
136
137 #[test]
138 fn test_ord_and_eq() {
139 let a = FixedBytes::new([1, 2, 3, 4]);
140 let b = FixedBytes::new([1, 2, 3, 5]);
141 assert!(a < b);
142 assert_ne!(a, b);
143
144 let c = FixedBytes::new([1, 2, 3, 4]);
145 assert_eq!(a, c);
146 }
147}