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