ark_serialize/
impls.rs

1use crate::{
2    CanonicalDeserialize, CanonicalSerialize, Compress, SerializationError, Valid, Validate,
3};
4use ark_std::{
5    borrow::*,
6    collections::{BTreeMap, BTreeSet, LinkedList, VecDeque},
7    io::{Read, Write},
8    marker::PhantomData,
9    rc::Rc,
10    string::*,
11    vec::*,
12};
13use arrayvec::ArrayVec;
14use num_bigint::BigUint;
15
16impl Valid for bool {
17    fn check(&self) -> Result<(), SerializationError> {
18        Ok(())
19    }
20}
21
22impl CanonicalSerialize for bool {
23    #[inline]
24    fn serialize_with_mode<W: Write>(
25        &self,
26        mut writer: W,
27        _compress: Compress,
28    ) -> Result<(), SerializationError> {
29        writer.write(&[*self as u8])?;
30        Ok(())
31    }
32
33    #[inline]
34    fn serialized_size(&self, _compress: Compress) -> usize {
35        1
36    }
37}
38
39impl CanonicalDeserialize for bool {
40    #[inline]
41    fn deserialize_with_mode<R: Read>(
42        reader: R,
43        compress: Compress,
44        validate: Validate,
45    ) -> Result<Self, SerializationError> {
46        match u8::deserialize_with_mode(reader, compress, validate)? {
47            0u8 => Ok(false),
48            1u8 => Ok(true),
49            _ => Err(SerializationError::InvalidData),
50        }
51    }
52}
53
54macro_rules! impl_uint {
55    ($type:ty) => {
56        impl CanonicalSerialize for $type {
57            #[inline]
58            fn serialize_with_mode<W: Write>(
59                &self,
60                mut writer: W,
61                _compress: Compress,
62            ) -> Result<(), SerializationError> {
63                Ok(writer.write_all(&self.to_le_bytes())?)
64            }
65
66            #[inline]
67            fn serialized_size(&self, _compress: Compress) -> usize {
68                core::mem::size_of::<$type>()
69            }
70        }
71
72        impl Valid for $type {
73            #[inline]
74            fn check(&self) -> Result<(), SerializationError> {
75                Ok(())
76            }
77
78            #[inline]
79            fn batch_check<'a>(
80                _batch: impl Iterator<Item = &'a Self>,
81            ) -> Result<(), SerializationError>
82            where
83                Self: 'a,
84            {
85                Ok(())
86            }
87        }
88
89        impl CanonicalDeserialize for $type {
90            #[inline]
91            fn deserialize_with_mode<R: Read>(
92                mut reader: R,
93                _compress: Compress,
94                _validate: Validate,
95            ) -> Result<Self, SerializationError> {
96                let mut bytes = [0u8; core::mem::size_of::<$type>()];
97                reader.read_exact(&mut bytes)?;
98                Ok(<$type>::from_le_bytes(bytes))
99            }
100        }
101    };
102}
103
104impl_uint!(u8);
105impl_uint!(u16);
106impl_uint!(u32);
107impl_uint!(u64);
108
109impl CanonicalSerialize for usize {
110    #[inline]
111    fn serialize_with_mode<W: Write>(
112        &self,
113        mut writer: W,
114        _compress: Compress,
115    ) -> Result<(), SerializationError> {
116        Ok(writer.write_all(&(*self as u64).to_le_bytes())?)
117    }
118
119    #[inline]
120    fn serialized_size(&self, _compress: Compress) -> usize {
121        core::mem::size_of::<u64>()
122    }
123}
124
125impl Valid for usize {
126    #[inline]
127    fn check(&self) -> Result<(), SerializationError> {
128        Ok(())
129    }
130
131    #[inline]
132    fn batch_check<'a>(_batch: impl Iterator<Item = &'a Self>) -> Result<(), SerializationError>
133    where
134        Self: 'a,
135    {
136        Ok(())
137    }
138}
139
140impl CanonicalDeserialize for usize {
141    #[inline]
142    fn deserialize_with_mode<R: Read>(
143        mut reader: R,
144        _compress: Compress,
145        _validate: Validate,
146    ) -> Result<Self, SerializationError> {
147        let mut bytes = [0u8; core::mem::size_of::<u64>()];
148        reader.read_exact(&mut bytes)?;
149        Ok(<u64>::from_le_bytes(bytes) as usize)
150    }
151}
152
153impl CanonicalSerialize for BigUint {
154    #[inline]
155    fn serialize_with_mode<W: Write>(
156        &self,
157        writer: W,
158        compress: Compress,
159    ) -> Result<(), SerializationError> {
160        self.to_bytes_le().serialize_with_mode(writer, compress)
161    }
162
163    #[inline]
164    fn serialized_size(&self, compress: Compress) -> usize {
165        self.to_bytes_le().serialized_size(compress)
166    }
167}
168
169impl CanonicalDeserialize for BigUint {
170    #[inline]
171    fn deserialize_with_mode<R: Read>(
172        reader: R,
173        compress: Compress,
174        validate: Validate,
175    ) -> Result<Self, SerializationError> {
176        Ok(BigUint::from_bytes_le(&Vec::<u8>::deserialize_with_mode(
177            reader, compress, validate,
178        )?))
179    }
180}
181
182impl Valid for BigUint {
183    #[inline]
184    fn check(&self) -> Result<(), SerializationError> {
185        Ok(())
186    }
187
188    #[inline]
189    fn batch_check<'a>(_batch: impl Iterator<Item = &'a Self>) -> Result<(), SerializationError>
190    where
191        Self: 'a,
192    {
193        Ok(())
194    }
195}
196
197impl<T: CanonicalSerialize> CanonicalSerialize for Option<T> {
198    #[inline]
199    fn serialize_with_mode<W: Write>(
200        &self,
201        mut writer: W,
202        compress: Compress,
203    ) -> Result<(), SerializationError> {
204        self.is_some().serialize_with_mode(&mut writer, compress)?;
205        if let Some(item) = self {
206            item.serialize_with_mode(&mut writer, compress)?;
207        }
208
209        Ok(())
210    }
211
212    #[inline]
213    fn serialized_size(&self, compress: Compress) -> usize {
214        1 + self
215            .as_ref()
216            .map(|s| s.serialized_size(compress))
217            .unwrap_or(0)
218    }
219}
220
221impl<T: Valid> Valid for Option<T> {
222    #[inline]
223    fn check(&self) -> Result<(), SerializationError> {
224        match self {
225            Some(v) => v.check(),
226            None => Ok(()),
227        }
228    }
229
230    #[inline]
231    fn batch_check<'a>(
232        batch: impl Iterator<Item = &'a Self> + Send,
233    ) -> Result<(), SerializationError>
234    where
235        Self: 'a,
236    {
237        T::batch_check(batch.map(Option::as_ref).filter(Option::is_some).flatten())
238    }
239}
240
241impl<T: CanonicalDeserialize> CanonicalDeserialize for Option<T> {
242    #[inline]
243    fn deserialize_with_mode<R: Read>(
244        mut reader: R,
245        compress: Compress,
246        validate: Validate,
247    ) -> Result<Self, SerializationError> {
248        let is_some = bool::deserialize_with_mode(&mut reader, compress, validate)?;
249        let data = if is_some {
250            Some(T::deserialize_with_mode(&mut reader, compress, validate)?)
251        } else {
252            None
253        };
254
255        Ok(data)
256    }
257}
258
259// No-op
260impl<T> CanonicalSerialize for PhantomData<T> {
261    #[inline]
262    fn serialize_with_mode<W: Write>(
263        &self,
264        _writer: W,
265        _compress: Compress,
266    ) -> Result<(), SerializationError> {
267        Ok(())
268    }
269
270    #[inline]
271    fn serialized_size(&self, _compress: Compress) -> usize {
272        0
273    }
274}
275
276impl<T: Sync> Valid for PhantomData<T> {
277    #[inline]
278    fn check(&self) -> Result<(), SerializationError> {
279        Ok(())
280    }
281}
282
283impl<T: Send + Sync> CanonicalDeserialize for PhantomData<T> {
284    #[inline]
285    fn deserialize_with_mode<R: Read>(
286        _reader: R,
287        _compress: Compress,
288        _validate: Validate,
289    ) -> Result<Self, SerializationError> {
290        Ok(PhantomData)
291    }
292}
293
294impl<T: CanonicalSerialize + ToOwned> CanonicalSerialize for Rc<T> {
295    #[inline]
296    fn serialize_with_mode<W: Write>(
297        &self,
298        mut writer: W,
299        compress: Compress,
300    ) -> Result<(), SerializationError> {
301        self.as_ref().serialize_with_mode(&mut writer, compress)
302    }
303
304    #[inline]
305    fn serialized_size(&self, compress: Compress) -> usize {
306        self.as_ref().serialized_size(compress)
307    }
308}
309
310#[cfg(target_has_atomic = "ptr")]
311impl<T: CanonicalSerialize + ToOwned> CanonicalSerialize for ark_std::sync::Arc<T> {
312    #[inline]
313    fn serialize_with_mode<W: Write>(
314        &self,
315        mut writer: W,
316        compress: Compress,
317    ) -> Result<(), SerializationError> {
318        self.as_ref().serialize_with_mode(&mut writer, compress)
319    }
320
321    #[inline]
322    fn serialized_size(&self, compress: Compress) -> usize {
323        self.as_ref().serialized_size(compress)
324    }
325}
326
327#[cfg(target_has_atomic = "ptr")]
328impl<T: Valid + Sync + Send> Valid for ark_std::sync::Arc<T> {
329    #[inline]
330    fn check(&self) -> Result<(), SerializationError> {
331        self.as_ref().check()
332    }
333
334    #[inline]
335
336    fn batch_check<'a>(
337        batch: impl Iterator<Item = &'a Self> + Send,
338    ) -> Result<(), SerializationError>
339    where
340        Self: 'a,
341    {
342        T::batch_check(batch.map(|v| v.as_ref()))
343    }
344}
345
346#[cfg(target_has_atomic = "ptr")]
347impl<T: CanonicalDeserialize + ToOwned + Sync + Send> CanonicalDeserialize
348    for ark_std::sync::Arc<T>
349{
350    #[inline]
351    fn deserialize_with_mode<R: Read>(
352        reader: R,
353        compress: Compress,
354        validate: Validate,
355    ) -> Result<Self, SerializationError> {
356        Ok(ark_std::sync::Arc::new(T::deserialize_with_mode(
357            reader, compress, validate,
358        )?))
359    }
360}
361
362impl<'a, T: CanonicalSerialize + ToOwned> CanonicalSerialize for Cow<'a, T> {
363    #[inline]
364    fn serialize_with_mode<W: Write>(
365        &self,
366        mut writer: W,
367        compress: Compress,
368    ) -> Result<(), SerializationError> {
369        self.as_ref().serialize_with_mode(&mut writer, compress)
370    }
371
372    #[inline]
373    fn serialized_size(&self, compress: Compress) -> usize {
374        self.as_ref().serialized_size(compress)
375    }
376}
377
378impl<'b, T> Valid for Cow<'b, T>
379where
380    T: ToOwned + Sync + Valid + Send,
381    <T as ToOwned>::Owned: CanonicalDeserialize + Send,
382{
383    #[inline]
384    fn check(&self) -> Result<(), SerializationError> {
385        <<T as ToOwned>::Owned>::check(&self.as_ref().to_owned())
386    }
387
388    #[inline]
389
390    fn batch_check<'a>(
391        batch: impl Iterator<Item = &'a Self> + Send,
392    ) -> Result<(), SerializationError>
393    where
394        Self: 'a,
395    {
396        let t: Vec<_> = batch.map(|v| v.as_ref().to_owned()).collect();
397        <<T as ToOwned>::Owned>::batch_check(t.iter())
398    }
399}
400
401impl<'a, T> CanonicalDeserialize for Cow<'a, T>
402where
403    T: ToOwned + Valid + Valid + Sync + Send,
404    <T as ToOwned>::Owned: CanonicalDeserialize + Valid + Send,
405{
406    #[inline]
407    fn deserialize_with_mode<R: Read>(
408        reader: R,
409        compress: Compress,
410        validate: Validate,
411    ) -> Result<Self, SerializationError> {
412        Ok(Cow::Owned(<T as ToOwned>::Owned::deserialize_with_mode(
413            reader, compress, validate,
414        )?))
415    }
416}
417
418impl<T: CanonicalSerialize, const N: usize> CanonicalSerialize for [T; N] {
419    #[inline]
420    fn serialize_with_mode<W: Write>(
421        &self,
422        mut writer: W,
423        compress: Compress,
424    ) -> Result<(), SerializationError> {
425        for item in self.iter() {
426            item.serialize_with_mode(&mut writer, compress)?;
427        }
428        Ok(())
429    }
430
431    #[inline]
432    fn serialized_size(&self, compress: Compress) -> usize {
433        self.iter()
434            .map(|item| item.serialized_size(compress))
435            .sum::<usize>()
436    }
437}
438impl<T: CanonicalDeserialize, const N: usize> Valid for [T; N] {
439    #[inline]
440    fn check(&self) -> Result<(), SerializationError> {
441        T::batch_check(self.iter())
442    }
443
444    #[inline]
445    fn batch_check<'a>(
446        batch: impl Iterator<Item = &'a Self> + Send,
447    ) -> Result<(), SerializationError>
448    where
449        Self: 'a,
450    {
451        T::batch_check(batch.flat_map(|v| v.iter()))
452    }
453}
454
455impl<T: CanonicalDeserialize, const N: usize> CanonicalDeserialize for [T; N] {
456    #[inline]
457    fn deserialize_with_mode<R: Read>(
458        mut reader: R,
459        compress: Compress,
460        validate: Validate,
461    ) -> Result<Self, SerializationError> {
462        let mut array = ArrayVec::<T, N>::new();
463        for _ in 0..N {
464            array.push(T::deserialize_with_mode(
465                &mut reader,
466                compress,
467                Validate::No,
468            )?);
469        }
470        if let Validate::Yes = validate {
471            T::batch_check(array.iter())?
472        }
473        Ok(array.into_inner().ok().unwrap())
474    }
475}
476
477impl<T: CanonicalSerialize> CanonicalSerialize for Vec<T> {
478    #[inline]
479    fn serialize_with_mode<W: Write>(
480        &self,
481        mut writer: W,
482        compress: Compress,
483    ) -> Result<(), SerializationError> {
484        self.as_slice().serialize_with_mode(&mut writer, compress)
485    }
486
487    #[inline]
488    fn serialized_size(&self, compress: Compress) -> usize {
489        self.as_slice().serialized_size(compress)
490    }
491}
492
493impl<T: Valid> Valid for Vec<T> {
494    #[inline]
495    fn check(&self) -> Result<(), SerializationError> {
496        T::batch_check(self.iter())
497    }
498
499    #[inline]
500    fn batch_check<'a>(
501        batch: impl Iterator<Item = &'a Self> + Send,
502    ) -> Result<(), SerializationError>
503    where
504        Self: 'a,
505    {
506        T::batch_check(batch.flat_map(|v| v.iter()))
507    }
508}
509
510impl<T: CanonicalDeserialize> CanonicalDeserialize for Vec<T> {
511    #[inline]
512    fn deserialize_with_mode<R: Read>(
513        mut reader: R,
514        compress: Compress,
515        validate: Validate,
516    ) -> Result<Self, SerializationError> {
517        let len = u64::deserialize_with_mode(&mut reader, compress, validate)?
518            .try_into()
519            .map_err(|_| SerializationError::NotEnoughSpace)?;
520        let mut values = Vec::with_capacity(len);
521        for _ in 0..len {
522            values.push(T::deserialize_with_mode(
523                &mut reader,
524                compress,
525                Validate::No,
526            )?);
527        }
528
529        if let Validate::Yes = validate {
530            T::batch_check(values.iter())?
531        }
532        Ok(values)
533    }
534}
535
536// Helper function. Serializes any sequential data type to the format
537//     n as u64 || data[0].serialize() || ... || data[n].serialize()
538#[inline]
539fn serialize_seq<T, B, W>(
540    seq: impl ExactSizeIterator<Item = B>,
541    mut writer: W,
542    compress: Compress,
543) -> Result<(), SerializationError>
544where
545    T: CanonicalSerialize,
546    B: Borrow<T>,
547    W: Write,
548{
549    let len = seq.len() as u64;
550    len.serialize_with_mode(&mut writer, compress)?;
551    for item in seq {
552        item.borrow().serialize_with_mode(&mut writer, compress)?;
553    }
554    Ok(())
555}
556
557// Helper function. Describes the size of any data serialized using the above function
558#[inline]
559fn get_serialized_size_of_seq<T, B>(
560    seq: impl ExactSizeIterator<Item = B>,
561    compress: Compress,
562) -> usize
563where
564    T: CanonicalSerialize,
565    B: Borrow<T>,
566{
567    8 + seq
568        .map(|item| item.borrow().serialized_size(compress))
569        .sum::<usize>()
570}
571
572impl<T: CanonicalSerialize> CanonicalSerialize for VecDeque<T> {
573    #[inline]
574    fn serialize_with_mode<W: Write>(
575        &self,
576        writer: W,
577        compress: Compress,
578    ) -> Result<(), SerializationError> {
579        serialize_seq::<T, _, _>(self.iter(), writer, compress)
580    }
581
582    #[inline]
583    fn serialized_size(&self, compress: Compress) -> usize {
584        get_serialized_size_of_seq::<T, _>(self.iter(), compress)
585    }
586}
587
588// Identical to Valid for Vec<T>
589impl<T: Valid> Valid for VecDeque<T> {
590    #[inline]
591    fn check(&self) -> Result<(), SerializationError> {
592        T::batch_check(self.iter())
593    }
594
595    #[inline]
596    fn batch_check<'a>(
597        batch: impl Iterator<Item = &'a Self> + Send,
598    ) -> Result<(), SerializationError>
599    where
600        Self: 'a,
601    {
602        T::batch_check(batch.flat_map(|v| v.iter()))
603    }
604}
605
606// Identical to CanonicalSerialize for Vec<T>, except using the push_back() method
607impl<T: CanonicalDeserialize> CanonicalDeserialize for VecDeque<T> {
608    #[inline]
609    fn deserialize_with_mode<R: Read>(
610        mut reader: R,
611        compress: Compress,
612        validate: Validate,
613    ) -> Result<Self, SerializationError> {
614        let len = u64::deserialize_with_mode(&mut reader, compress, validate)?
615            .try_into()
616            .map_err(|_| SerializationError::NotEnoughSpace)?;
617        let mut values = VecDeque::with_capacity(len);
618        for _ in 0..len {
619            values.push_back(T::deserialize_with_mode(
620                &mut reader,
621                compress,
622                Validate::No,
623            )?);
624        }
625
626        if let Validate::Yes = validate {
627            T::batch_check(values.iter())?
628        }
629        Ok(values)
630    }
631}
632
633impl<T: CanonicalSerialize> CanonicalSerialize for LinkedList<T> {
634    #[inline]
635    fn serialize_with_mode<W: Write>(
636        &self,
637        writer: W,
638        compress: Compress,
639    ) -> Result<(), SerializationError> {
640        serialize_seq::<T, _, _>(self.iter(), writer, compress)
641    }
642
643    #[inline]
644    fn serialized_size(&self, compress: Compress) -> usize {
645        get_serialized_size_of_seq::<T, _>(self.iter(), compress)
646    }
647}
648
649// Identical to Valid for Vec<T>
650impl<T: Valid> Valid for LinkedList<T> {
651    #[inline]
652    fn check(&self) -> Result<(), SerializationError> {
653        T::batch_check(self.iter())
654    }
655
656    #[inline]
657    fn batch_check<'a>(
658        batch: impl Iterator<Item = &'a Self> + Send,
659    ) -> Result<(), SerializationError>
660    where
661        Self: 'a,
662    {
663        T::batch_check(batch.flat_map(|v| v.iter()))
664    }
665}
666
667// Identical to CanonicalSerialize for Vec<T>, except using the push_back() method, and the new()
668// constructor.
669impl<T: CanonicalDeserialize> CanonicalDeserialize for LinkedList<T> {
670    #[inline]
671    fn deserialize_with_mode<R: Read>(
672        mut reader: R,
673        compress: Compress,
674        validate: Validate,
675    ) -> Result<Self, SerializationError> {
676        let len = u64::deserialize_with_mode(&mut reader, compress, validate)?
677            .try_into()
678            .map_err(|_| SerializationError::NotEnoughSpace)?;
679        let mut values = LinkedList::new();
680        for _ in 0..len {
681            values.push_back(T::deserialize_with_mode(
682                &mut reader,
683                compress,
684                Validate::No,
685            )?);
686        }
687
688        if let Validate::Yes = validate {
689            T::batch_check(values.iter())?
690        }
691        Ok(values)
692    }
693}
694
695impl<T: CanonicalSerialize> CanonicalSerialize for [T] {
696    #[inline]
697    fn serialize_with_mode<W: Write>(
698        &self,
699        writer: W,
700        compress: Compress,
701    ) -> Result<(), SerializationError> {
702        serialize_seq::<T, _, _>(self.iter(), writer, compress)
703    }
704
705    #[inline]
706    fn serialized_size(&self, compress: Compress) -> usize {
707        get_serialized_size_of_seq::<T, _>(self.iter(), compress)
708    }
709}
710
711impl<'a, T: CanonicalSerialize> CanonicalSerialize for &'a [T] {
712    #[inline]
713    fn serialize_with_mode<W: Write>(
714        &self,
715        mut writer: W,
716        compress: Compress,
717    ) -> Result<(), SerializationError> {
718        (*self).serialize_with_mode(&mut writer, compress)
719    }
720
721    #[inline]
722    fn serialized_size(&self, compress: Compress) -> usize {
723        (*self).serialized_size(compress)
724    }
725}
726
727impl CanonicalSerialize for String {
728    #[inline]
729    fn serialize_with_mode<W: Write>(
730        &self,
731        mut writer: W,
732        compress: Compress,
733    ) -> Result<(), SerializationError> {
734        self.as_bytes().serialize_with_mode(&mut writer, compress)
735    }
736
737    #[inline]
738    fn serialized_size(&self, compress: Compress) -> usize {
739        self.as_bytes().serialized_size(compress)
740    }
741}
742
743impl Valid for String {
744    #[inline]
745    fn check(&self) -> Result<(), SerializationError> {
746        Ok(())
747    }
748}
749
750impl CanonicalDeserialize for String {
751    #[inline]
752    fn deserialize_with_mode<R: Read>(
753        reader: R,
754        compress: Compress,
755        validate: Validate,
756    ) -> Result<Self, SerializationError> {
757        let bytes = <Vec<u8>>::deserialize_with_mode(reader, compress, validate)?;
758        String::from_utf8(bytes).map_err(|_| SerializationError::InvalidData)
759    }
760}
761
762// Implement Serialization for tuples
763macro_rules! impl_tuple {
764    ($( $ty: ident : $no: tt, )*) => {
765        impl<$($ty, )*> Valid for ($($ty,)*) where
766            $($ty: Valid,)*
767        {
768            #[inline]
769            fn check(&self) -> Result<(), SerializationError> {
770                $(self.$no.check()?;)*
771                Ok(())
772            }
773        }
774
775        #[allow(unused)]
776        impl<$($ty, )*> CanonicalSerialize for ($($ty,)*) where
777            $($ty: CanonicalSerialize,)*
778        {
779            #[inline]
780            fn serialize_with_mode<W: Write>(&self, mut writer: W, compress: Compress) -> Result<(), SerializationError> {
781                $(self.$no.serialize_with_mode(&mut writer, compress)?;)*
782                Ok(())
783            }
784
785            #[inline]
786            fn serialized_size(&self, compress: Compress) -> usize {
787                [$(
788                    self.$no.serialized_size(compress),
789                )*].iter().sum()
790            }
791        }
792
793        impl<$($ty, )*> CanonicalDeserialize for ($($ty,)*) where
794            $($ty: CanonicalDeserialize,)*
795        {
796            #[inline]
797            #[allow(unused)]
798            fn deserialize_with_mode<R: Read>(mut reader: R, compress: Compress, validate: Validate) -> Result<Self, SerializationError> {
799                Ok(($(
800                    $ty::deserialize_with_mode(&mut reader, compress, validate)?,
801                )*))
802            }
803        }
804    }
805}
806
807impl_tuple!();
808impl_tuple!(A:0,);
809impl_tuple!(A:0, B:1,);
810impl_tuple!(A:0, B:1, C:2,);
811impl_tuple!(A:0, B:1, C:2, D:3,);
812impl_tuple!(A:0, B:1, C:2, D:3, E:4,);
813
814impl<K, V> CanonicalSerialize for BTreeMap<K, V>
815where
816    K: CanonicalSerialize,
817    V: CanonicalSerialize,
818{
819    /// Serializes a `BTreeMap` as `len(map) || key 1 || value 1 || ... || key n || value n`.
820    fn serialize_with_mode<W: Write>(
821        &self,
822        mut writer: W,
823        compress: Compress,
824    ) -> Result<(), SerializationError> {
825        let len = self.len() as u64;
826        len.serialize_with_mode(&mut writer, compress)?;
827        for (k, v) in self.iter() {
828            k.serialize_with_mode(&mut writer, compress)?;
829            v.serialize_with_mode(&mut writer, compress)?;
830        }
831        Ok(())
832    }
833
834    fn serialized_size(&self, compress: Compress) -> usize {
835        8 + self
836            .iter()
837            .map(|(k, v)| k.serialized_size(compress) + v.serialized_size(compress))
838            .sum::<usize>()
839    }
840}
841
842impl<K: Valid, V: Valid> Valid for BTreeMap<K, V> {
843    #[inline]
844    fn check(&self) -> Result<(), SerializationError> {
845        K::batch_check(self.keys())?;
846        V::batch_check(self.values())
847    }
848
849    #[inline]
850    fn batch_check<'a>(batch: impl Iterator<Item = &'a Self>) -> Result<(), SerializationError>
851    where
852        Self: 'a,
853    {
854        let (keys, values): (Vec<_>, Vec<_>) = batch.map(|b| (b.keys(), b.values())).unzip();
855        K::batch_check(keys.into_iter().flatten())?;
856        V::batch_check(values.into_iter().flatten())
857    }
858}
859
860impl<K, V> CanonicalDeserialize for BTreeMap<K, V>
861where
862    K: Ord + CanonicalDeserialize,
863    V: CanonicalDeserialize,
864{
865    /// Deserializes a `BTreeMap` from `len(map) || key 1 || value 1 || ... || key n || value n`.
866    fn deserialize_with_mode<R: Read>(
867        mut reader: R,
868        compress: Compress,
869        validate: Validate,
870    ) -> Result<Self, SerializationError> {
871        let len = u64::deserialize_with_mode(&mut reader, compress, validate)?;
872        (0..len)
873            .map(|_| {
874                Ok((
875                    K::deserialize_with_mode(&mut reader, compress, validate)?,
876                    V::deserialize_with_mode(&mut reader, compress, validate)?,
877                ))
878            })
879            .collect()
880    }
881}
882
883impl<V: CanonicalSerialize> CanonicalSerialize for BTreeSet<V> {
884    /// Serializes a `BTreeSet` as `len(set) || value 1 || value 2 || ... || value n`.
885    fn serialize_with_mode<W: Write>(
886        &self,
887        mut writer: W,
888        compress: Compress,
889    ) -> Result<(), SerializationError> {
890        let len = self.len() as u64;
891        len.serialize_with_mode(&mut writer, compress)?;
892        for v in self {
893            v.serialize_with_mode(&mut writer, compress)?;
894        }
895        Ok(())
896    }
897
898    fn serialized_size(&self, compress: Compress) -> usize {
899        8 + self
900            .iter()
901            .map(|v| v.serialized_size(compress))
902            .sum::<usize>()
903    }
904}
905
906impl<V: Valid> Valid for BTreeSet<V> {
907    #[inline]
908    fn check(&self) -> Result<(), SerializationError> {
909        V::batch_check(self.iter())
910    }
911
912    #[inline]
913    fn batch_check<'a>(
914        batch: impl Iterator<Item = &'a Self> + Send,
915    ) -> Result<(), SerializationError>
916    where
917        Self: 'a,
918    {
919        V::batch_check(batch.flat_map(|s| s.iter()))
920    }
921}
922
923impl<V> CanonicalDeserialize for BTreeSet<V>
924where
925    V: Ord + CanonicalDeserialize,
926{
927    /// Deserializes a `BTreeSet` from `len(map) || value 1 || ... || value n`.
928    fn deserialize_with_mode<R: Read>(
929        mut reader: R,
930        compress: Compress,
931        validate: Validate,
932    ) -> Result<Self, SerializationError> {
933        let len = u64::deserialize_with_mode(&mut reader, compress, validate)?;
934        (0..len)
935            .map(|_| V::deserialize_with_mode(&mut reader, compress, validate))
936            .collect()
937    }
938}