1#[cfg(test)]
5mod tests;
6
7use crate::Error;
8use alloc::vec::Vec;
9use core::{fmt, marker::PhantomData};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11
12pub trait PackedElement: word::Word {}
15mod word {
16 pub trait Word: bytemuck::Pod + core::fmt::Debug + Eq {
20 const SCHEMA: &'static str;
21 fn read(bytes: &[u8]) -> Self;
22 fn append(self, bytes: &mut alloc::vec::Vec<u8>);
23 }
24 macro_rules! integer {
25 ($($ty:ty),+) => {$(
26 impl super::PackedElement for $ty {}
27 impl Word for $ty {
28 const SCHEMA: &'static str = stringify!($ty);
29 fn read(bytes: &[u8]) -> Self { Self::from_le_bytes(bytes.try_into().unwrap()) }
30 fn append(self, bytes: &mut alloc::vec::Vec<u8>) { bytes.extend_from_slice(&self.to_le_bytes()); }
31 }
32 )+};
33 }
34 integer!(i8, i16, u16, i32, u32, i64, u64);
35 macro_rules! opaque {
36 ($n:literal,$schema:literal) => {
37 impl super::PackedElement for [u8; $n] {}
38 impl Word for [u8; $n] {
39 const SCHEMA: &'static str = $schema;
40 fn read(bytes: &[u8]) -> Self {
41 bytes.try_into().unwrap()
42 }
43
44 fn append(self, bytes: &mut alloc::vec::Vec<u8>) {
45 bytes.extend_from_slice(&self);
46 }
47 }
48 };
49 }
50 opaque!(16, "hash16");
51 opaque!(32, "hash32");
52}
53
54#[derive(Clone, Debug, Eq, PartialEq)]
64pub struct Packed<T, const N: usize = { usize::MAX }>(Vec<T>);
65impl<T, const N: usize> Packed<T, N> {
66 pub fn new(words: Vec<T>) -> Result<Self, Error> {
70 if words.len() > N {
71 Err(Error::Limit)
72 } else {
73 Ok(Self(words))
74 }
75 }
76
77 #[must_use]
79 pub fn as_slice(&self) -> &[T] {
80 &self.0
81 }
82
83 #[must_use]
85 pub fn into_vec(self) -> Vec<T> {
86 self.0
87 }
88}
89impl<T: PackedElement, const N: usize> Serialize for Packed<T, N> {
90 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
91 serialize_words(&self.0, serializer)
92 }
93}
94impl<'de, T: PackedElement, const N: usize> Deserialize<'de> for Packed<T, N> {
95 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
96 deserializer
97 .deserialize_bytes(PackedVisitor::<T> {
98 limit: N,
99 marker: PhantomData,
100 })
101 .map(Self)
102 }
103}
104
105pub(crate) fn serialize_words<T: PackedElement, S: Serializer>(
106 words: &[T],
107 serializer: S,
108) -> Result<S::Ok, S::Error> {
109 if cfg!(target_endian = "little") {
110 serializer.serialize_bytes(bytemuck::must_cast_slice(words))
111 } else {
112 let bytes = little_endian_bytes::<T, S::Error>(words)?;
113 serializer.serialize_bytes(&bytes)
114 }
115}
116
117fn little_endian_bytes<T: PackedElement, E: serde::ser::Error>(words: &[T]) -> Result<Vec<u8>, E> {
120 let length = words
121 .len()
122 .checked_mul(size_of::<T>())
123 .ok_or_else(|| E::custom("length overflow"))?;
124 let mut bytes = Vec::new();
125 bytes
126 .try_reserve_exact(length)
127 .map_err(|_| E::custom("allocation"))?;
128 for word in words {
129 word.append(&mut bytes);
130 }
131 Ok(bytes)
132}
133
134struct PackedVisitor<T> {
137 limit: usize,
138 marker: PhantomData<T>,
139}
140
141impl<T: PackedElement> de::Visitor<'_> for PackedVisitor<T> {
142 type Value = Vec<T>;
143
144 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145 formatter.write_str("packed little-endian words")
146 }
147
148 fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
149 let width = size_of::<T>();
150 if !bytes.len().is_multiple_of(width) || bytes.len() / width > self.limit {
151 return Err(E::custom("invalid packed length"));
152 }
153 let mut values = Vec::new();
154 values
155 .try_reserve_exact(bytes.len() / width)
156 .map_err(|_| E::custom("allocation"))?;
157 values.extend(bytes.chunks_exact(width).map(T::read));
158 Ok(values)
159 }
160}