Skip to main content

crypto_common/
hazmat.rs

1use crate::array::{
2    Array, ArraySize, sizes,
3    typenum::{Diff, Prod, Sum, U1, U2, U4, U8, U16, Unsigned},
4};
5use core::{convert::TryInto, default::Default, fmt};
6
7/// Serialized internal state.
8pub type SerializedState<T> = Array<u8, <T as SerializableState>::SerializedStateSize>;
9
10/// Alias for `AddSerializedStateSize<T, S> = Sum<T, S::SerializedStateSize>`
11pub type AddSerializedStateSize<T, S> = Sum<T, <S as SerializableState>::SerializedStateSize>;
12
13/// Alias for `SubSerializedStateSize<T, S> = Diff<T, S::SerializedStateSize>`
14pub type SubSerializedStateSize<T, S> = Diff<T, <S as SerializableState>::SerializedStateSize>;
15
16/// The error type returned when an object cannot be deserialized from the state.
17#[derive(Copy, Clone, Eq, PartialEq, Debug)]
18pub struct DeserializeStateError;
19
20impl fmt::Display for DeserializeStateError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
22        f.write_str("Deserialization error")
23    }
24}
25
26impl core::error::Error for DeserializeStateError {}
27
28/// Types which can serialize the internal state and be restored from it.
29///
30/// # Compatibility
31///
32/// Serialized state can be assumed to be stable across backwards compatible
33/// versions of an implementation crate, i.e. any `0.x.y` version of a crate
34/// should be able to decode data serialized with any other `0.x.z` version,
35/// but it may not be able to correctly decode data serialized with a non-`x`
36/// version.
37///
38/// This guarantee is a subject to issues such as security fixes.
39///
40/// # SECURITY WARNING
41///
42/// Serialized state may contain sensitive data.
43pub trait SerializableState
44where
45    Self: Sized,
46{
47    /// Size of serialized internal state.
48    type SerializedStateSize: ArraySize;
49
50    /// Serialize and return internal state.
51    fn serialize(&self) -> SerializedState<Self>;
52
53    /// Create an object from serialized internal state.
54    ///
55    /// # Errors
56    /// If the serialized state could not be deserialized successfully.
57    fn deserialize(serialized_state: &SerializedState<Self>)
58    -> Result<Self, DeserializeStateError>;
59}
60
61macro_rules! impl_seializable_state_unsigned {
62    ($type: ty, $type_size: ty) => {
63        impl SerializableState for $type {
64            type SerializedStateSize = $type_size;
65
66            fn serialize(&self) -> SerializedState<Self> {
67                self.to_le_bytes().into()
68            }
69
70            fn deserialize(
71                serialized_state: &SerializedState<Self>,
72            ) -> Result<Self, DeserializeStateError> {
73                Ok(<$type>::from_le_bytes((*serialized_state).into()))
74            }
75        }
76    };
77}
78
79impl_seializable_state_unsigned!(u8, U1);
80impl_seializable_state_unsigned!(u16, U2);
81impl_seializable_state_unsigned!(u32, U4);
82impl_seializable_state_unsigned!(u64, U8);
83impl_seializable_state_unsigned!(u128, U16);
84
85macro_rules! impl_serializable_state_u8_array {
86    ($($n: ident),*) => {
87        $(
88            impl SerializableState for [u8; sizes::$n::USIZE] {
89                type SerializedStateSize = sizes::$n;
90
91                fn serialize(&self) -> SerializedState<Self> {
92                    (*self).into()
93                }
94
95                fn deserialize(
96                    serialized_state: &SerializedState<Self>,
97                ) -> Result<Self, DeserializeStateError> {
98                    Ok((*serialized_state).into())
99                }
100            }
101        )*
102    };
103}
104
105macro_rules! impl_serializable_state_type_array {
106    ($type: ty, $type_size: ty, $n: ident) => {
107        impl SerializableState for [$type; sizes::$n::USIZE] {
108            type SerializedStateSize = Prod<sizes::$n, $type_size>;
109
110            fn serialize(&self) -> SerializedState<Self> {
111                let mut serialized_state = SerializedState::<Self>::default();
112                for (val, chunk) in self
113                    .iter()
114                    .zip(serialized_state.chunks_exact_mut(<$type_size>::USIZE))
115                {
116                    chunk.copy_from_slice(&val.to_le_bytes());
117                }
118
119                serialized_state
120            }
121
122            fn deserialize(
123                serialized_state: &SerializedState<Self>,
124            ) -> Result<Self, DeserializeStateError> {
125                let mut array = [0; sizes::$n::USIZE];
126                for (val, chunk) in array
127                    .iter_mut()
128                    .zip(serialized_state.chunks_exact(<$type_size>::USIZE))
129                {
130                    *val = <$type>::from_le_bytes(chunk.try_into().unwrap());
131                }
132                Ok(array)
133            }
134        }
135    };
136}
137
138macro_rules! impl_serializable_state_u16_array {
139    ($($n: ident),*) => {
140        $(
141            impl_serializable_state_type_array!(u16, U2, $n);
142        )*
143    };
144}
145
146macro_rules! impl_serializable_state_u32_array {
147    ($($n: ident),*) => {
148        $(
149            impl_serializable_state_type_array!(u32, U4, $n);
150        )*
151    };
152}
153
154macro_rules! impl_serializable_state_u64_array {
155    ($($n: ident),*) => {
156        $(
157            impl_serializable_state_type_array!(u64, U8, $n);
158        )*
159    };
160}
161
162macro_rules! impl_serializable_state_u128_array {
163    ($($n: ident),*) => {
164        $(
165            impl_serializable_state_type_array!(u128, U8, $n);
166        )*
167    };
168}
169
170impl_serializable_state_u8_array! {
171    U1,
172    U2,
173    U3,
174    U4,
175    U5,
176    U6,
177    U7,
178    U8,
179    U9,
180    U10,
181    U11,
182    U12,
183    U13,
184    U14,
185    U15,
186    U16,
187    U17,
188    U18,
189    U19,
190    U20,
191    U21,
192    U22,
193    U23,
194    U24,
195    U25,
196    U26,
197    U27,
198    U28,
199    U29,
200    U30,
201    U31,
202    U32,
203    U33,
204    U34,
205    U35,
206    U36,
207    U37,
208    U38,
209    U39,
210    U40,
211    U41,
212    U42,
213    U43,
214    U44,
215    U45,
216    U46,
217    U47,
218    U48,
219    U49,
220    U50,
221    U51,
222    U52,
223    U53,
224    U54,
225    U55,
226    U56,
227    U57,
228    U58,
229    U59,
230    U60,
231    U61,
232    U62,
233    U63,
234    U64,
235    U96,
236    U128,
237    U192,
238    U256,
239    U384,
240    U448,
241    U512,
242    U768,
243    U896,
244    U1024,
245    U2048,
246    U4096,
247    U8192
248}
249
250impl_serializable_state_u16_array! {
251    U1,
252    U2,
253    U3,
254    U4,
255    U5,
256    U6,
257    U7,
258    U8,
259    U9,
260    U10,
261    U11,
262    U12,
263    U13,
264    U14,
265    U15,
266    U16,
267    U17,
268    U18,
269    U19,
270    U20,
271    U21,
272    U22,
273    U23,
274    U24,
275    U25,
276    U26,
277    U27,
278    U28,
279    U29,
280    U30,
281    U31,
282    U32,
283    U48,
284    U96,
285    U128,
286    U192,
287    U256,
288    U384,
289    U448,
290    U512,
291    U2048,
292    U4096
293}
294
295impl_serializable_state_u32_array! {
296    U1,
297    U2,
298    U3,
299    U4,
300    U5,
301    U6,
302    U7,
303    U8,
304    U9,
305    U10,
306    U11,
307    U12,
308    U13,
309    U14,
310    U15,
311    U16,
312    U24,
313    U32,
314    U48,
315    U64,
316    U96,
317    U128,
318    U192,
319    U256,
320    U512,
321    U1024,
322    U2048
323}
324
325impl_serializable_state_u64_array! {
326    U1,
327    U2,
328    U3,
329    U4,
330    U5,
331    U6,
332    U7,
333    U8,
334    U12,
335    U16,
336    U24,
337    U32,
338    U48,
339    U64,
340    U96,
341    U128,
342    U256,
343    U512,
344    U1024
345}
346
347impl_serializable_state_u128_array! {
348    U1,
349    U2,
350    U3,
351    U4,
352    U6,
353    U8,
354    U12,
355    U16,
356    U24,
357    U32,
358    U48,
359    U64,
360    U128,
361    U256,
362    U512
363}