1use alloc::vec::Vec;
3use core::{
4 fmt::{self, Debug},
5 marker::PhantomData,
6};
7use serde::Serialize;
8
9pub trait PackedElement: sealed::Word {}
12mod sealed {
13 use super::Debug;
14 #[cfg(any(target_endian = "big", test))]
15 use alloc::vec::Vec;
16 pub trait Word: bytemuck::Pod + Debug + Eq {
17 #[cfg(all(feature = "typescript", not(target_family = "wasm")))]
18 const SCHEMA: &'static str;
19 fn read_le(bytes: &[u8]) -> Self;
20 #[cfg(any(target_endian = "big", test))]
21 fn append_le(self, bytes: &mut Vec<u8>);
22 }
23 macro_rules! words {
26 ($($ty:ty),*) => {$(
27 impl super::PackedElement for $ty {}
28 impl Word for $ty {
29 #[cfg(all(feature = "typescript", not(target_family = "wasm")))]
30 const SCHEMA: &'static str = stringify!($ty);
31 #[inline]
32 fn read_le(bytes: &[u8]) -> Self {
33 Self::from_le_bytes(bytes.try_into().unwrap())
34 }
35 #[cfg(any(target_endian = "big", test))]
36 #[inline]
37 fn append_le(self, bytes: &mut Vec<u8>) {
38 bytes.extend_from_slice(&self.to_le_bytes());
39 }
40 }
41 )*};
42}
43 words!(i8, i16, u16, i32, u32, i64, u64);
44 impl super::PackedElement for [u8; 16] {}
45 impl Word for [u8; 16] {
46 #[cfg(all(feature = "typescript", not(target_family = "wasm")))]
47 const SCHEMA: &'static str = "hash16";
48 #[inline]
49 fn read_le(bytes: &[u8]) -> Self {
50 bytes.try_into().unwrap()
51 }
52 #[cfg(any(target_endian = "big", test))]
53 #[inline]
54 fn append_le(self, bytes: &mut Vec<u8>) {
55 bytes.extend_from_slice(&self);
56 }
57 }
58 impl super::PackedElement for [u8; 32] {}
59 impl Word for [u8; 32] {
60 #[cfg(all(feature = "typescript", not(target_family = "wasm")))]
61 const SCHEMA: &'static str = "hash32";
62 #[inline]
63 fn read_le(bytes: &[u8]) -> Self {
64 bytes.try_into().unwrap()
65 }
66 #[cfg(any(target_endian = "big", test))]
67 #[inline]
68 fn append_le(self, bytes: &mut Vec<u8>) {
69 bytes.extend_from_slice(&self);
70 }
71 }
72}
73
74#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct Packed<T>(Vec<T>);
90impl<T> Packed<T> {
91 #[must_use]
93 pub fn new(values: Vec<T>) -> Self {
94 Self(values)
95 }
96 #[must_use]
98 pub fn as_slice(&self) -> &[T] {
99 &self.0
100 }
101 #[must_use]
103 pub fn into_vec(self) -> Vec<T> {
104 self.0
105 }
106}
107impl<T: PackedElement> Serialize for Packed<T> {
108 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
109 serialize_words(&self.0, serializer)
124 }
125}
126pub(crate) fn serialize_words<T: PackedElement, S: serde::Serializer>(
127 words: &[T],
128 serializer: S,
129) -> Result<S::Ok, S::Error> {
130 #[cfg(target_endian = "little")]
131 {
132 serializer.serialize_bytes(bytemuck::must_cast_slice(words))
133 }
134 #[cfg(target_endian = "big")]
135 {
136 let mut bytes = Vec::new();
137 let len = words
138 .len()
139 .checked_mul(size_of::<T>())
140 .ok_or_else(|| serde::ser::Error::custom("length overflow"))?;
141 bytes
142 .try_reserve_exact(len)
143 .map_err(|_| serde::ser::Error::custom("allocation"))?;
144 for value in words {
145 value.append_le(&mut bytes);
146 }
147 serializer.serialize_bytes(&bytes)
148 }
149}
150impl<'de, T: PackedElement> serde::Deserialize<'de> for Packed<T> {
151 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
152 deserializer
153 .deserialize_bytes(PackedVisitor {
154 marker: PhantomData,
155 })
156 .map(Self)
157 }
158}
159macro_rules! decode_words {
164 ($error:ty, $bytes:ident, $width:expr, $excess:expr, $words:expr) => {{
165 if !$bytes.len().is_multiple_of($width) || $excess {
166 return Err(<$error as serde::de::Error>::custom(
167 "invalid packed length",
168 ));
169 }
170 let mut values = alloc::vec::Vec::new();
171 values
172 .try_reserve_exact($bytes.len() / $width)
173 .map_err(|_| <$error as serde::de::Error>::custom("allocation"))?;
174 values.extend($words);
175 Ok(values)
176 }};
177}
178pub(crate) use decode_words;
179
180struct PackedVisitor<T> {
184 marker: PhantomData<T>,
185}
186impl<T: PackedElement> serde::de::Visitor<'_> for PackedVisitor<T> {
187 type Value = Vec<T>;
188 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 f.write_str("packed little-endian words")
190 }
191 #[inline(never)]
192 fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
193 let width = size_of::<T>();
194 #[cfg(target_endian = "little")]
198 if align_of::<T>() == 1 {
199 if !bytes.len().is_multiple_of(width) {
200 return Err(E::custom("invalid packed length"));
201 }
202 let mut values = Vec::new();
203 values
204 .try_reserve_exact(bytes.len() / width)
205 .map_err(|_| E::custom("allocation"))?;
206 let words =
207 bytemuck::try_cast_slice(bytes).map_err(|_| E::custom("invalid packed length"))?;
208 values.extend_from_slice(words);
209 return Ok(values);
210 }
211 decode_words!(
212 E,
213 bytes,
214 width,
215 false,
216 bytes.chunks_exact(width).map(T::read_le)
217 )
218 }
219}
220
221#[cfg(test)]
222mod tests;