concordium_base/common/
serialize.rs

1use anyhow::{bail, ensure, Context};
2use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
3use concordium_contracts_common::{Duration, ExchangeRate};
4use core::cmp;
5use sha2::Digest;
6use std::{
7    collections::btree_map::BTreeMap,
8    convert::{TryFrom, TryInto},
9    marker::PhantomData,
10};
11
12/// Maximum capacity of a vector to preallocate when parsing.
13/// This must always be at least 1 to ensure progress.
14static MAX_PREALLOCATED_CAPACITY: usize = 4096;
15
16/// Result when deserializing a value. This is a simple wrapper around `Result`
17/// that fixes the error type to be [anyhow::Error].
18pub type ParseResult<T> = anyhow::Result<T>;
19
20/// As Vec::with_capacity, but only allocate maximum MAX_PREALLOCATED_CAPACITY
21/// elements.
22#[inline]
23pub fn safe_with_capacity<T>(capacity: usize) -> Vec<T> {
24    // TODO: This should probably use the size of the type T as well.
25    // As long as sizeof(T) is not excessive it does not matter very much, but it
26    // would be cleaner.
27    Vec::with_capacity(cmp::min(capacity, MAX_PREALLOCATED_CAPACITY))
28}
29
30/// Trait for types which can be recovered from byte sources.
31pub trait Deserial: Sized {
32    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self>;
33}
34
35impl Deserial for u128 {
36    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u128> {
37        Ok(source.read_u128::<BigEndian>()?)
38    }
39}
40
41impl Deserial for u64 {
42    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u64> {
43        Ok(source.read_u64::<BigEndian>()?)
44    }
45}
46
47impl Deserial for u32 {
48    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u32> {
49        Ok(source.read_u32::<BigEndian>()?)
50    }
51}
52
53impl Deserial for u16 {
54    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u16> {
55        Ok(source.read_u16::<BigEndian>()?)
56    }
57}
58
59impl Deserial for bool {
60    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
61        let x: u8 = source.read_u8()?;
62        match x {
63            0 => Ok(false),
64            1 => Ok(true),
65            _ => anyhow::bail!("Unrecognized boolean value {}", x),
66        }
67    }
68}
69
70impl Deserial for u8 {
71    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<u8> { Ok(source.read_u8()?) }
72}
73
74impl Deserial for i128 {
75    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i128> {
76        Ok(source.read_i128::<BigEndian>()?)
77    }
78}
79
80impl Deserial for i64 {
81    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i64> {
82        Ok(source.read_i64::<BigEndian>()?)
83    }
84}
85
86impl Deserial for i32 {
87    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i32> {
88        Ok(source.read_i32::<BigEndian>()?)
89    }
90}
91
92impl Deserial for i16 {
93    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i16> {
94        Ok(source.read_i16::<BigEndian>()?)
95    }
96}
97
98impl Deserial for i8 {
99    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<i8> { Ok(source.read_i8()?) }
100}
101
102impl Deserial for std::num::NonZeroU8 {
103    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
104        let value = source.get()?;
105        Self::new(value).context("Zero is not valid.")
106    }
107}
108
109impl Deserial for std::num::NonZeroU16 {
110    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
111        let value = source.get()?;
112        Self::new(value).context("Zero is not valid.")
113    }
114}
115impl Deserial for std::num::NonZeroU32 {
116    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
117        let value = source.get()?;
118        Self::new(value).context("Zero is not valid.")
119    }
120}
121
122impl Deserial for std::num::NonZeroU64 {
123    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
124        let value = source.get()?;
125        Self::new(value).context("Zero is not valid.")
126    }
127}
128
129impl Deserial for std::num::NonZeroU128 {
130    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
131        let value = source.get()?;
132        Self::new(value).context("Zero is not valid.")
133    }
134}
135
136impl Deserial for std::num::NonZeroI8 {
137    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
138        let value = source.get()?;
139        Self::new(value).context("Zero is not valid.")
140    }
141}
142
143impl Deserial for std::num::NonZeroI16 {
144    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
145        let value = source.get()?;
146        Self::new(value).context("Zero is not valid.")
147    }
148}
149impl Deserial for std::num::NonZeroI32 {
150    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
151        let value = source.get()?;
152        Self::new(value).context("Zero is not valid.")
153    }
154}
155
156impl Deserial for std::num::NonZeroI64 {
157    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
158        let value = source.get()?;
159        Self::new(value).context("Zero is not valid.")
160    }
161}
162
163impl Deserial for std::num::NonZeroI128 {
164    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
165        let value = source.get()?;
166        Self::new(value).context("Zero is not valid.")
167    }
168}
169
170impl Deserial for num::rational::Ratio<u64> {
171    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
172        let numerator = source.get()?;
173        let denominator = source.get()?;
174        ensure!(denominator != 0, "Denominator of zero is not valid.");
175        Ok(Self::new_raw(numerator, denominator))
176    }
177}
178
179/// Read a vector where the first 8 bytes are taken as length in big endian.
180impl<T: Deserial> Deserial for Vec<T> {
181    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
182        let len: u64 = u64::deserial(source)?;
183        deserial_vector_no_length(source, usize::try_from(len)?)
184    }
185}
186
187/// Read a set where the first 8 bytes are taken as length in big endian.
188/// The values must be serialized in strictly increasing order.
189impl<T: Deserial + std::cmp::Ord> Deserial for BTreeSet<T> {
190    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
191        let len: u64 = u64::deserial(source)?;
192        deserial_set_no_length(source, usize::try_from(len)?)
193    }
194}
195
196/// Read a map where the first 8 bytes are taken as length in big endian.
197/// The values must be serialized in strictly increasing order of keys.
198impl<K: Deserial + std::cmp::Ord, V: Deserial> Deserial for BTreeMap<K, V> {
199    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
200        let len: u64 = u64::deserial(source)?;
201        deserial_map_no_length(source, usize::try_from(len)?)
202    }
203}
204
205impl<T: Deserial, U: Deserial> Deserial for (T, U) {
206    #[inline]
207    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
208        let x = T::deserial(source)?;
209        let y = U::deserial(source)?;
210        Ok((x, y))
211    }
212}
213
214impl<T: Deserial, S: Deserial, U: Deserial> Deserial for (T, S, U) {
215    #[inline]
216    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
217        let x = T::deserial(source)?;
218        let y = S::deserial(source)?;
219        let z = U::deserial(source)?;
220        Ok((x, y, z))
221    }
222}
223
224/// Read a string of given size.
225/// NB: Be aware that this allocates a buffer of the given length, and so this
226/// must only be used when the size is bounded, otherwise it will lead to a
227/// memory allocation failure, and panic.
228pub fn deserial_string<R: ReadBytesExt>(reader: &mut R, l: usize) -> ParseResult<String> {
229    let mut svec = vec![0; l];
230    reader.read_exact(&mut svec)?;
231    Ok(String::from_utf8(svec)?)
232}
233
234/// Write a string directly to the provided sink (without encoding its length).
235/// The string is utf8 encoded.
236pub fn serial_string<R: Buffer>(s: &str, out: &mut R) {
237    out.write_all(s.as_bytes())
238        .expect("Writing to buffer should succeed.")
239}
240
241/// Read a vector of a given size. This protects against excessive memory
242/// allocation by only pre-allocating a maximum safe size.
243pub fn deserial_vector_no_length<R: ReadBytesExt, T: Deserial>(
244    reader: &mut R,
245    len: usize,
246) -> ParseResult<Vec<T>> {
247    let mut vec = safe_with_capacity(len);
248    for _ in 0..len {
249        vec.push(T::deserial(reader)?);
250    }
251    Ok(vec)
252}
253
254/// Read a vector of the given size.
255/// NB: Be aware that this allocates a buffer of the given length, and so this
256/// must only be used when the size is bounded, otherwise it will lead to a
257/// memory allocation failure, and panic.
258pub fn deserial_bytes<R: ReadBytesExt>(reader: &mut R, l: usize) -> ParseResult<Vec<u8>> {
259    let mut svec = vec![0; l];
260    reader.read_exact(&mut svec)?;
261    Ok(svec)
262}
263
264impl<T> Deserial for PhantomData<T> {
265    #[inline]
266    fn deserial<R: ReadBytesExt>(_source: &mut R) -> ParseResult<Self> { Ok(Default::default()) }
267}
268
269impl<T: Deserial> Deserial for Box<T> {
270    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
271        let x = T::deserial(source)?;
272        Ok(Box::new(x))
273    }
274}
275
276/// Trait for writers which will not fail in normal operation with
277/// small amounts of data, e.g., [`Vec<u8>`](Vec).
278/// Moreover having a special trait allows us to implement it for
279/// other types, such as the SHA Digest.
280pub trait Buffer: Sized + WriteBytesExt {
281    type Result;
282    fn start() -> Self;
283    fn start_hint(_l: usize) -> Self { Self::start() }
284    fn result(self) -> Self::Result;
285}
286
287impl Buffer for Vec<u8> {
288    type Result = Vec<u8>;
289
290    fn start() -> Vec<u8> { Vec::new() }
291
292    fn start_hint(l: usize) -> Vec<u8> { Vec::with_capacity(l) }
293
294    fn result(self) -> Self::Result { self }
295}
296
297impl Buffer for sha2::Sha256 {
298    type Result = [u8; 32];
299
300    fn start() -> Self { sha2::Sha256::new() }
301
302    fn result(self) -> Self::Result { self.finalize().into() }
303}
304
305impl Buffer for sha2::Sha512 {
306    type Result = [u8; 64];
307
308    fn start() -> Self { sha2::Sha512::new() }
309
310    fn result(self) -> Self::Result { self.finalize().into() }
311}
312
313/// Trait implemented by types which can be encoded into byte arrays.
314/// The intention is that the encoding is binary and not human readable.
315pub trait Serial {
316    fn serial<B: Buffer>(&self, out: &mut B);
317}
318
319impl Serial for u64 {
320    fn serial<B: Buffer>(&self, out: &mut B) {
321        out.write_u64::<BigEndian>(*self)
322            .expect("Writing to a buffer should not fail.")
323    }
324}
325
326impl Serial for u32 {
327    fn serial<B: Buffer>(&self, out: &mut B) {
328        out.write_u32::<BigEndian>(*self)
329            .expect("Writing to a buffer should not fail.")
330    }
331}
332
333impl Serial for u16 {
334    fn serial<B: Buffer>(&self, out: &mut B) {
335        out.write_u16::<BigEndian>(*self)
336            .expect("Writing to a buffer should not fail.")
337    }
338}
339
340impl Serial for bool {
341    fn serial<B: Buffer>(&self, out: &mut B) {
342        (if *self {
343            out.write_u8(1)
344        } else {
345            out.write_u8(0)
346        })
347        .expect("Writing to a buffer should not fail.");
348    }
349}
350
351impl Serial for u8 {
352    fn serial<B: Buffer>(&self, out: &mut B) {
353        out.write_u8(*self)
354            .expect("Writing to a buffer should not fail.")
355    }
356}
357
358impl Serial for i64 {
359    fn serial<B: Buffer>(&self, out: &mut B) {
360        out.write_i64::<BigEndian>(*self)
361            .expect("Writing to a buffer should not fail.")
362    }
363}
364
365impl Serial for i32 {
366    fn serial<B: Buffer>(&self, out: &mut B) {
367        out.write_i32::<BigEndian>(*self)
368            .expect("Writing to a buffer should not fail.")
369    }
370}
371
372impl Serial for i16 {
373    fn serial<B: Buffer>(&self, out: &mut B) {
374        out.write_i16::<BigEndian>(*self)
375            .expect("Writing to a buffer should not fail.")
376    }
377}
378
379impl Serial for i8 {
380    fn serial<B: Buffer>(&self, out: &mut B) {
381        out.write_i8(*self)
382            .expect("Writing to a buffer should not fail.")
383    }
384}
385
386impl Serial for std::num::NonZeroU8 {
387    fn serial<B: Buffer>(&self, out: &mut B) {
388        out.write_u8(self.get())
389            .expect("Writing to a buffer should not fail.")
390    }
391}
392
393impl Serial for std::num::NonZeroU16 {
394    fn serial<B: Buffer>(&self, out: &mut B) {
395        out.write_u16::<BigEndian>(self.get())
396            .expect("Writing to a buffer should not fail.")
397    }
398}
399
400impl Serial for std::num::NonZeroU32 {
401    fn serial<B: Buffer>(&self, out: &mut B) {
402        out.write_u32::<BigEndian>(self.get())
403            .expect("Writing to a buffer should not fail.")
404    }
405}
406
407impl Serial for std::num::NonZeroU64 {
408    fn serial<B: Buffer>(&self, out: &mut B) {
409        out.write_u64::<BigEndian>(self.get())
410            .expect("Writing to a buffer should not fail.")
411    }
412}
413
414impl Serial for std::num::NonZeroU128 {
415    fn serial<B: Buffer>(&self, out: &mut B) {
416        out.write_u128::<BigEndian>(self.get())
417            .expect("Writing to a buffer should not fail.")
418    }
419}
420
421impl Serial for std::num::NonZeroI8 {
422    fn serial<B: Buffer>(&self, out: &mut B) {
423        out.write_i8(self.get())
424            .expect("Writing to a buffer should not fail.")
425    }
426}
427
428impl Serial for std::num::NonZeroI16 {
429    fn serial<B: Buffer>(&self, out: &mut B) {
430        out.write_i16::<BigEndian>(self.get())
431            .expect("Writing to a buffer should not fail.")
432    }
433}
434
435impl Serial for std::num::NonZeroI32 {
436    fn serial<B: Buffer>(&self, out: &mut B) {
437        out.write_i32::<BigEndian>(self.get())
438            .expect("Writing to a buffer should not fail.")
439    }
440}
441
442impl Serial for std::num::NonZeroI64 {
443    fn serial<B: Buffer>(&self, out: &mut B) {
444        out.write_i64::<BigEndian>(self.get())
445            .expect("Writing to a buffer should not fail.")
446    }
447}
448
449impl Serial for std::num::NonZeroI128 {
450    fn serial<B: Buffer>(&self, out: &mut B) {
451        out.write_i128::<BigEndian>(self.get())
452            .expect("Writing to a buffer should not fail.")
453    }
454}
455
456impl Serial for num::rational::Ratio<u64> {
457    fn serial<B: Buffer>(&self, out: &mut B) {
458        self.numer().serial(out);
459        self.denom().serial(out);
460    }
461}
462
463/// Serialize a vector by encoding its length as a u64 in big endian and then
464/// the list of elements in sequence.
465impl<T: Serial> Serial for Vec<T> {
466    fn serial<B: Buffer>(&self, out: &mut B) {
467        (self.len() as u64).serial(out);
468        serial_vector_no_length(self, out)
469    }
470}
471
472/// Serialize a string by encoding its length as a u64 in big endian and then
473/// the utf8 encoding of the content.
474impl Serial for String {
475    fn serial<B: Buffer>(&self, out: &mut B) {
476        (self.len() as u64).serial(out);
477        out.write_all(self.as_bytes())
478            .expect("Writing to buffer succeeds.")
479    }
480}
481
482impl Deserial for String {
483    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
484        let len = u64::deserial(source)?;
485        if len as usize <= MAX_PREALLOCATED_CAPACITY {
486            let mut data = vec![0u8; len as usize];
487            source.read_exact(&mut data)?;
488            let s = String::from_utf8(data)?;
489            Ok(s)
490        } else {
491            let mut chunk = vec![0u8; MAX_PREALLOCATED_CAPACITY];
492            let mut data = Vec::new();
493            let mut remaining = len as usize;
494            while remaining > 0 {
495                let to_read = std::cmp::min(remaining, MAX_PREALLOCATED_CAPACITY);
496                source.read_exact(&mut chunk[..to_read])?;
497                data.extend_from_slice(&chunk[..to_read]);
498                remaining -= to_read;
499            }
500            let s = String::from_utf8(data)?;
501            Ok(s)
502        }
503    }
504}
505
506/// Serialize a slice by encoding its length as a u64 in big endian and then
507/// the list of elements in sequence.
508impl<T: Serial> Serial for &[T] {
509    fn serial<B: Buffer>(&self, out: &mut B) {
510        (self.len() as u64).serial(out);
511        serial_vector_no_length(self, out)
512    }
513}
514
515/// Serialize a set by encoding its size as a u64 in big endian and then
516/// the list of elements in increasing order.
517impl<V: Serial> Serial for BTreeSet<V> {
518    fn serial<B: Buffer>(&self, out: &mut B) {
519        (self.len() as u64).serial(out);
520        serial_set_no_length(self, out)
521    }
522}
523
524/// Serialize a map by encoding its size as a u64 in big endian and then
525/// the list of key-value pairs in increasing order of keys.
526impl<K: Serial, V: Serial> Serial for BTreeMap<K, V> {
527    fn serial<B: Buffer>(&self, out: &mut B) {
528        (self.len() as u64).serial(out);
529        serial_map_no_length(self, out)
530    }
531}
532
533/// Serialize all of the elements in the iterator.
534pub fn serial_iter<'a, B: Buffer, T: Serial + 'a, I: Iterator<Item = &'a T>>(xs: I, out: &mut B) {
535    for x in xs {
536        x.serial(out);
537    }
538}
539
540/// Write an array without including length information.
541pub fn serial_vector_no_length<B: Buffer, T: Serial>(xs: &[T], out: &mut B) {
542    serial_iter(xs.iter(), out)
543}
544
545/// Serialize an ordered map. Serialization is by increasing order of keys.
546pub fn serial_map_no_length<B: Buffer, K: Serial, V: Serial>(map: &BTreeMap<K, V>, out: &mut B) {
547    for (k, v) in map.iter() {
548        // iterator over ordered pairs.
549        out.put(k);
550        out.put(v);
551    }
552}
553
554/// Deserialize a map from a byte source. This ensures there are no duplicates,
555/// as well as that all keys are in strictly increasing order.
556pub fn deserial_map_no_length<R: ReadBytesExt, K: Deserial + Ord, V: Deserial>(
557    source: &mut R,
558    len: usize,
559) -> ParseResult<BTreeMap<K, V>> {
560    let mut out = BTreeMap::new();
561    let mut x = None;
562    for _ in 0..len {
563        let k = source.get()?;
564        let v = source.get()?;
565        if let Some((old_k, old_v)) = x.take() {
566            if k > old_k {
567                out.insert(old_k, old_v);
568            } else {
569                bail!("Keys not in order.")
570            }
571        }
572        x = Some((k, v));
573    }
574    if let Some((k, v)) = x {
575        out.insert(k, v);
576    }
577    Ok(out)
578}
579
580/// Analogous to [serial_map_no_length], but for sets.
581pub fn serial_set_no_length<B: Buffer, K: Serial>(map: &BTreeSet<K>, out: &mut B) {
582    for k in map.iter() {
583        out.put(k);
584    }
585}
586
587/// Analogous to [deserial_map_no_length], but for sets.
588/// NB: This ensures there are no duplicates, and that all the keys are in
589/// strictly increasing order.
590pub fn deserial_set_no_length<R: ReadBytesExt, K: Deserial + Ord>(
591    source: &mut R,
592    len: usize,
593) -> ParseResult<BTreeSet<K>> {
594    let mut out = BTreeSet::new();
595    let mut x = None;
596    for _ in 0..len {
597        let k = source.get()?;
598        if let Some(old_k) = x.take() {
599            if k > old_k {
600                out.insert(old_k);
601            } else {
602                bail!("Keys not in order.")
603            }
604        }
605        x = Some(k);
606    }
607    if let Some(k) = x {
608        out.insert(k);
609    }
610    Ok(out)
611}
612
613impl<T: Serial, S: Serial> Serial for (T, S) {
614    #[inline]
615    fn serial<B: Buffer>(&self, out: &mut B) {
616        self.0.serial(out);
617        self.1.serial(out);
618    }
619}
620
621impl<T: Serial, S: Serial, U: Serial> Serial for (T, S, U) {
622    #[inline]
623    fn serial<B: Buffer>(&self, out: &mut B) {
624        self.0.serial(out);
625        self.1.serial(out);
626        self.2.serial(out);
627    }
628}
629
630impl<T> Serial for PhantomData<T> {
631    #[inline]
632    fn serial<B: Buffer>(&self, _out: &mut B) {}
633}
634
635impl<T: Serial> Serial for Box<T> {
636    #[inline]
637    fn serial<B: Buffer>(&self, out: &mut B) { self.as_ref().serial(out) }
638}
639
640impl Serial for [u8] {
641    #[inline]
642    fn serial<B: Buffer>(&self, out: &mut B) {
643        out.write_all(self).expect("Writing to buffer is safe.");
644    }
645}
646
647/// Analogue of [Deserial], but instead this has the type to serialize as a type
648/// parameter, and is implemented once for a source. The reason for this trait
649/// is that it is often more convenient to use since we can rely on the
650/// typechecker to fill in more details. Contrast `A::deserial(source)` to
651/// `source.get()`. In the latter case the return type is usually clear from
652/// context.
653pub trait Get<A> {
654    fn get(&mut self) -> ParseResult<A>;
655}
656
657impl<R: ReadBytesExt, A: Deserial> Get<A> for R {
658    #[inline]
659    fn get(&mut self) -> ParseResult<A> { A::deserial(self) }
660}
661
662/// Dual to `Get`, and the analogue of `Serial`. It allows writing
663/// `sink.put(value)` in contrast to `value.serial(sink)`. It is less important
664/// than `Get`.
665pub trait Put<A> {
666    fn put(&mut self, _v: &A);
667}
668
669impl<R: Buffer, A: Serial> Put<A> for R {
670    #[inline]
671    fn put(&mut self, v: &A) { v.serial(self) }
672}
673
674/// A convenient way to refer to both [Serial] and [Deserial] together.
675pub trait Serialize: Serial + Deserial {}
676
677/// Generic instance deriving Deserialize for any type that implements
678/// both put and get.
679impl<A: Deserial + Serial> Serialize for A {}
680
681/// Directly serialize to a vector of bytes.
682#[inline]
683pub fn to_bytes<A: Serial>(x: &A) -> Vec<u8> {
684    let mut buf = Vec::new();
685    buf.put(x);
686    buf
687}
688
689#[inline]
690/// A small wrapper that is sometimes more convenient than `A::deserial`.
691/// It is here mostly for historical reasons, for backwards compatibility.
692pub fn from_bytes<A: Deserial, R: ReadBytesExt>(source: &mut R) -> ParseResult<A> {
693    A::deserial(source)
694}
695
696// Some more generic implementations
697
698impl<T: Serial, const N: usize> Serial for [T; N] {
699    fn serial<B: Buffer>(&self, out: &mut B) {
700        for x in self.iter() {
701            x.serial(out);
702        }
703    }
704}
705
706impl<T: Deserial, const N: usize> Deserial for [T; N] {
707    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
708        let mut out_vec = Vec::with_capacity(N);
709        for _ in 0..N {
710            out_vec.push(T::deserial(source)?);
711        }
712        let out_array: [T; N] = out_vec.try_into().map_err(|_| ()).unwrap();
713        Ok(out_array)
714    }
715}
716
717// Some more std implementations
718use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
719
720impl Serial for Ipv4Addr {
721    fn serial<W: WriteBytesExt>(&self, target: &mut W) {
722        target.write_u8(4).expect("Writing to buffer is safe.");
723        target
724            .write_all(&self.octets())
725            .expect("Writing to buffer is safe.");
726    }
727}
728
729impl Deserial for Ipv4Addr {
730    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
731        let mut octects = [0u8; 4];
732        source.read_exact(&mut octects)?;
733        Ok(Ipv4Addr::from(octects))
734    }
735}
736
737impl Serial for Ipv6Addr {
738    fn serial<W: WriteBytesExt>(&self, target: &mut W) {
739        target.write_u8(6).expect("Writing to buffer is safe.");
740        target
741            .write_all(&self.octets())
742            .expect("Writing to buffer is safe.");
743    }
744}
745
746impl Deserial for Ipv6Addr {
747    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
748        let mut octets = [0u8; 16];
749        source.read_exact(&mut octets)?;
750        Ok(Ipv6Addr::from(octets))
751    }
752}
753
754impl Serial for IpAddr {
755    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
756        match self {
757            IpAddr::V4(ip4) => ip4.serial(target),
758            IpAddr::V6(ip6) => ip6.serial(target),
759        }
760    }
761}
762
763impl Deserial for IpAddr {
764    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
765        match source.read_u8()? {
766            4 => Ok(IpAddr::V4(Ipv4Addr::deserial(source)?)),
767            6 => Ok(IpAddr::V6(Ipv6Addr::deserial(source)?)),
768            x => bail!("Can't deserialize an IpAddr (unknown type: {})", x),
769        }
770    }
771}
772
773impl Serial for SocketAddr {
774    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
775        self.ip().serial(target);
776        self.port().serial(target);
777    }
778}
779
780impl Deserial for SocketAddr {
781    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
782        Ok(SocketAddr::new(
783            IpAddr::deserial(source)?,
784            u16::deserial(source)?,
785        ))
786    }
787}
788
789impl Serial for ExchangeRate {
790    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
791        self.numerator().serial(target);
792        self.denominator().serial(target);
793    }
794}
795
796impl Deserial for ExchangeRate {
797    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
798        let numerator = source.get()?;
799        let denominator = source.get()?;
800        Self::new(numerator, denominator).ok_or_else(|| anyhow::anyhow!("Invalid exchange rate."))
801    }
802}
803
804impl Serial for Duration {
805    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) { self.millis().serial(target); }
806}
807
808impl Deserial for Duration {
809    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
810        let milliseconds = source.get()?;
811        Ok(Self::from_millis(milliseconds))
812    }
813}
814
815use std::{
816    collections::{BTreeSet, HashSet},
817    hash::{BuildHasher, Hash},
818};
819
820impl<T: Serial + Eq + Hash, S: BuildHasher + Default> Serial for HashSet<T, S> {
821    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) {
822        (self.len() as u32).serial(target);
823        self.iter().for_each(|ref item| item.serial(target));
824    }
825}
826
827impl<T: Deserial + Eq + Hash, S: BuildHasher + Default> Deserial for HashSet<T, S> {
828    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
829        let len = u32::deserial(source)?;
830        let mut out = HashSet::with_capacity_and_hasher(
831            std::cmp::min(len as usize, MAX_PREALLOCATED_CAPACITY),
832            Default::default(),
833        );
834
835        for _i in 0..len {
836            out.insert(T::deserial(source)?);
837        }
838        Ok(out)
839    }
840}
841
842impl<T: Serial> Serial for &T {
843    fn serial<W: Buffer + WriteBytesExt>(&self, target: &mut W) { (*self).serial(target) }
844}
845
846// Helpers for json serialization
847
848use hex::{decode, encode};
849use serde::{de, de::Visitor, Deserializer, Serializer};
850use std::{fmt, io::Cursor};
851
852/// Encode the given value into a byte array using its [Serial] instance, and
853/// then encode that byte array as a hex string into the provided serde
854/// Serializer.
855pub fn base16_encode<S: Serializer, T: Serial>(v: &T, ser: S) -> Result<S::Ok, S::Error> {
856    let b16_str = encode(to_bytes(v));
857    ser.serialize_str(&b16_str)
858}
859
860/// Dual to [base16_encode].
861pub fn base16_decode<'de, D: Deserializer<'de>, T: Deserial>(des: D) -> Result<T, D::Error> {
862    struct Base16Visitor<D>(std::marker::PhantomData<D>);
863
864    impl<'de, D: Deserial> Visitor<'de> for Base16Visitor<D> {
865        type Value = D;
866
867        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
868            write!(formatter, "A base 16 string.")
869        }
870
871        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
872            let bytes = decode(v).map_err(de::Error::custom)?;
873            D::deserial(&mut Cursor::new(&bytes)).map_err(de::Error::custom)
874        }
875    }
876
877    des.deserialize_str(Base16Visitor(Default::default()))
878}
879
880/// Encode a byte array as a hex string. This is more efficient than using
881/// the [`base16_encode`] implementation since it outputs the bytes in a chunk.
882pub(crate) fn base16_encode_array<S: Serializer, const N: usize>(
883    v: &[u8; N],
884    ser: S,
885) -> Result<S::Ok, S::Error> {
886    let b16_str = encode(v);
887    ser.serialize_str(&b16_str)
888}
889
890/// Dual to [`base16_encode_array`]. More efficient than [`base16_decode`] since
891/// it reads the entire byte array in one chunk.
892pub(crate) fn base16_decode_array<'de, D: Deserializer<'de>, const N: usize>(
893    des: D,
894) -> Result<[u8; N], D::Error> {
895    struct Base16Visitor<const N: usize>(std::marker::PhantomData<[u8; N]>);
896
897    impl<'de, const N: usize> Visitor<'de> for Base16Visitor<N> {
898        type Value = [u8; N];
899
900        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
901            write!(formatter, "A base 16 string.")
902        }
903
904        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
905            let bytes = decode(v).map_err(de::Error::custom)?;
906            bytes
907                .try_into()
908                .map_err(|_| de::Error::custom("Unexpected array length."))
909        }
910    }
911
912    des.deserialize_str(Base16Visitor(Default::default()))
913}
914
915/// Analogous to [base16_encode], but encodes into a string rather than a serde
916/// Serializer.
917pub fn base16_encode_string<S: Serial>(x: &S) -> String { encode(to_bytes(x)) }
918
919/// Dual to [base16_encode_string].
920pub fn base16_decode_string<S: Deserial>(x: &str) -> ParseResult<S> {
921    let d = decode(x)?;
922    from_bytes(&mut Cursor::new(&d))
923}
924
925/// Analogous to [base16_encode] but after serializing to a byte array it only
926/// encodes the `&[4..]` into the serde Serializer. This is intended to use in
927/// cases where we are encoding a collection such as a vector into JSON. Since
928/// JSON is self-describing we do not need to explicitly record the length,
929/// which we do in binary.
930pub fn base16_ignore_length_encode<S: Serializer, T: Serial>(
931    v: &T,
932    ser: S,
933) -> Result<S::Ok, S::Error> {
934    let b16_str = encode(&to_bytes(v)[4..]);
935    ser.serialize_str(&b16_str)
936}
937
938/// Dual to [base16_ignore_length_encode]
939pub fn base16_ignore_length_decode<'de, D: Deserializer<'de>, T: Deserial>(
940    des: D,
941) -> Result<T, D::Error> {
942    // Deserialization in base 16 for values which explicitly record the length.
943    // In JSON serialization this explicit length is not needed because JSON is
944    // self-describing and we always know the length of input.
945    struct Base16IgnoreLengthVisitor<D>(std::marker::PhantomData<D>);
946
947    impl<'de, D: Deserial> Visitor<'de> for Base16IgnoreLengthVisitor<D> {
948        type Value = D;
949
950        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
951            write!(formatter, "A base 16 string.")
952        }
953
954        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
955            let bytes = decode(v).map_err(de::Error::custom)?;
956            let mut all_bytes = Vec::with_capacity(bytes.len() + 4);
957            all_bytes.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
958            all_bytes.extend_from_slice(&bytes);
959            D::deserial(&mut Cursor::new(&all_bytes)).map_err(de::Error::custom)
960        }
961    }
962    des.deserialize_str(Base16IgnoreLengthVisitor(Default::default()))
963}
964
965#[test]
966fn test_map_serialization() {
967    use rand::Rng;
968    for n in 0..1000 {
969        let mut map = BTreeMap::<u64, u32>::new();
970        for (k, v) in rand::thread_rng()
971            .sample_iter(rand::distributions::Standard)
972            .take(n)
973        {
974            map.insert(k, v);
975        }
976        let deserialized = super::serialize_deserialize(&map).expect("Deserialization succeeds.");
977        assert_eq!(map, deserialized);
978    }
979}
980
981#[test]
982fn test_set_serialization() {
983    use rand::Rng;
984    for n in 0..1000 {
985        let mut set = BTreeSet::<u64>::new();
986        for k in rand::thread_rng()
987            .sample_iter(rand::distributions::Standard)
988            .take(n)
989        {
990            set.insert(k);
991        }
992        let deserialized = super::serialize_deserialize(&set).expect("Deserialization succeeds.");
993        assert_eq!(set, deserialized);
994    }
995}
996
997#[test]
998fn test_string_serialization() {
999    use rand::Rng;
1000    for _ in 0..1000 {
1001        let n: usize = rand::thread_rng().gen_range(0..2 * MAX_PREALLOCATED_CAPACITY);
1002        let s: String = String::from_utf8(vec!['a' as u8; n]).unwrap();
1003        let deserialized = super::serialize_deserialize(&s).expect("Deserialization succeeds.");
1004        assert_eq!(s, deserialized);
1005    }
1006}