1use std::borrow::Cow;
3
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum Bound {
11 Unbounded,
13 Bounded {
15 max_size: u32,
17 is_fixed_size: bool,
19 },
20}
21
22impl Bound {
23 pub(crate) const fn check(self, bytes: &[u8]) {
24 if let Self::Bounded {
25 max_size,
26 is_fixed_size,
27 } = self
28 && !(bytes.len() <= max_size as usize
29 && (!is_fixed_size || bytes.len() == max_size as usize))
30 {
31 panic!("record violates codec bound");
32 }
33 }
34}
35
36pub trait Storable: Sized {
44 const BOUND: Bound;
46 fn to_bytes(&self) -> Cow<'_, [u8]>;
49 fn into_bytes(self) -> Vec<u8> {
52 self.to_bytes().into_owned()
53 }
54 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self;
57 fn check_bounds(bytes: &[u8]) {
60 Self::BOUND.check(bytes)
61 }
62 fn to_bytes_checked(&self) -> Cow<'_, [u8]> {
65 let bytes = self.to_bytes();
66 Self::BOUND.check(&bytes);
67 bytes
68 }
69 fn into_bytes_checked(self) -> Vec<u8> {
72 let bytes = self.into_bytes();
73 Self::BOUND.check(&bytes);
74 bytes
75 }
76}
77
78macro_rules! integer {
79 ($($ty:ty),* $(,)?) => {$ (
80 impl Storable for $ty {
81 const BOUND: Bound = Bound::Bounded { max_size: size_of::<Self>() as u32, is_fixed_size: true };
82 fn to_bytes(&self) -> Cow<'_, [u8]> { Cow::Owned(self.to_le_bytes().to_vec()) }
83 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self { Self::from_le_bytes(bytes.as_ref().try_into().expect("integer width")) }
84 }
85 )*};
86}
87integer!(u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64);
88impl Storable for u8 {
89 const BOUND: Bound = Bound::Bounded {
90 max_size: 1,
91 is_fixed_size: true,
92 };
93 fn to_bytes(&self) -> Cow<'_, [u8]> {
94 Cow::Borrowed(std::slice::from_ref(self))
95 }
96 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
97 Self::from_le_bytes(bytes.as_ref().try_into().expect("integer width"))
98 }
99}
100impl Storable for () {
101 const BOUND: Bound = Bound::Bounded {
102 max_size: 0,
103 is_fixed_size: true,
104 };
105 fn to_bytes(&self) -> Cow<'_, [u8]> {
106 Cow::Borrowed(&[])
107 }
108 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
109 Self::check_bounds(&bytes)
110 }
111}
112impl Storable for bool {
113 const BOUND: Bound = Bound::Bounded {
114 max_size: 1,
115 is_fixed_size: true,
116 };
117 fn to_bytes(&self) -> Cow<'_, [u8]> {
118 Cow::Borrowed(if *self { &[1] } else { &[0] })
119 }
120 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
121 match bytes.as_ref() {
122 [0] => false,
123 [1] => true,
124 _ => panic!("invalid boolean encoding"),
125 }
126 }
127}
128impl Storable for Vec<u8> {
129 const BOUND: Bound = Bound::Unbounded;
130 fn to_bytes(&self) -> Cow<'_, [u8]> {
131 Cow::Borrowed(self)
132 }
133 fn into_bytes(self) -> Vec<u8> {
134 self
135 }
136 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
137 bytes.into_owned()
138 }
139}
140impl Storable for String {
141 const BOUND: Bound = Bound::Unbounded;
142 fn to_bytes(&self) -> Cow<'_, [u8]> {
143 Cow::Borrowed(self.as_bytes())
144 }
145 fn into_bytes(self) -> Vec<u8> {
146 self.into_bytes()
147 }
148 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
149 Self::from_utf8(bytes.into_owned()).expect("invalid UTF-8 record")
150 }
151}
152impl<const N: usize> Storable for [u8; N] {
153 const BOUND: Bound = Bound::Bounded {
154 max_size: {
155 assert!(N <= u32::MAX as usize);
156 N as u32
157 },
158 is_fixed_size: true,
159 };
160 fn to_bytes(&self) -> Cow<'_, [u8]> {
161 Cow::Borrowed(self)
162 }
163 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
164 bytes.as_ref().try_into().expect("invalid byte array width")
165 }
166}
167impl<T: Storable> Storable for Option<T> {
168 const BOUND: Bound = match T::BOUND {
169 Bound::Unbounded => Bound::Unbounded,
170 Bound::Bounded { max_size, .. } => Bound::Bounded {
171 max_size: max_size.checked_add(1).expect("optional bound overflow"),
172 is_fixed_size: false,
173 },
174 };
175 fn to_bytes(&self) -> Cow<'_, [u8]> {
176 let mut bytes = vec![u8::from(self.is_some())];
177 if let Some(value) = self {
178 bytes.extend_from_slice(&value.to_bytes_checked());
179 }
180 Cow::Owned(bytes)
181 }
182 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
183 match bytes.as_ref().split_first() {
184 Some((0, [])) => None,
185 Some((1, payload)) => {
186 T::check_bounds(payload);
187 Some(T::from_bytes(Cow::Borrowed(payload)))
188 }
189 _ => panic!("invalid optional record tag"),
190 }
191 }
192}
193
194const fn pair_bound(left: Bound, right: Bound) -> Bound {
195 match (left, right) {
196 (
197 Bound::Bounded {
198 max_size: a,
199 is_fixed_size: af,
200 },
201 Bound::Bounded {
202 max_size: b,
203 is_fixed_size: bf,
204 },
205 ) => {
206 let width = a as u64 + b as u64 + 4;
207 if width <= u32::MAX as u64 {
208 Bound::Bounded {
209 max_size: width as u32,
210 is_fixed_size: af && bf,
211 }
212 } else {
213 Bound::Unbounded
214 }
215 }
216 _ => Bound::Unbounded,
217 }
218}
219
220fn push_component(bytes: &mut Vec<u8>, component: &[u8]) {
222 let length = u32::try_from(component.len()).expect("tuple component exceeds u32");
223 bytes.extend_from_slice(&length.to_le_bytes());
224 bytes.extend_from_slice(component);
225}
226
227fn take_component<T: Storable>(bytes: &mut &[u8]) -> T {
228 let (prefix, payload) = bytes.split_at(4);
229 let length = u32::from_le_bytes(prefix.try_into().unwrap()) as usize;
230 let (component, rest) = payload.split_at(length);
231 *bytes = rest;
232 decode_component(component)
233}
234
235fn decode_component<T: Storable>(bytes: &[u8]) -> T {
236 T::BOUND.check(bytes);
237 T::from_bytes(Cow::Borrowed(bytes))
238}
239
240impl<A: Storable, B: Storable> Storable for (A, B) {
241 const BOUND: Bound = pair_bound(A::BOUND, B::BOUND);
242
243 fn to_bytes(&self) -> Cow<'_, [u8]> {
244 let left = self.0.to_bytes();
245 let right = self.1.to_bytes();
246 A::BOUND.check(&left);
247 B::BOUND.check(&right);
248 let mut bytes = Vec::with_capacity(4 + left.len() + right.len());
249 push_component(&mut bytes, &left);
250 bytes.extend_from_slice(&right);
251 Cow::Owned(bytes)
252 }
253
254 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
255 let mut payload = bytes.as_ref();
256 (take_component(&mut payload), decode_component(payload))
257 }
258}
259
260impl<A: Storable, B: Storable, C: Storable> Storable for (A, B, C) {
261 const BOUND: Bound = pair_bound(A::BOUND, pair_bound(B::BOUND, C::BOUND));
262
263 fn to_bytes(&self) -> Cow<'_, [u8]> {
264 let a = self.0.to_bytes();
265 let b = self.1.to_bytes();
266 let c = self.2.to_bytes();
267 A::BOUND.check(&a);
268 B::BOUND.check(&b);
269 C::BOUND.check(&c);
270 let mut bytes = Vec::with_capacity(8 + a.len() + b.len() + c.len());
271 push_component(&mut bytes, &a);
272 push_component(&mut bytes, &b);
273 bytes.extend_from_slice(&c);
274 Cow::Owned(bytes)
275 }
276
277 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
278 let mut payload = bytes.as_ref();
279 (
280 take_component(&mut payload),
281 take_component(&mut payload),
282 decode_component(payload),
283 )
284 }
285}