ark_serialize_zypher/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![warn(
3    unused,
4    future_incompatible,
5    nonstandard_style,
6    rust_2018_idioms,
7    rust_2021_compatibility
8)]
9#![forbid(unsafe_code)]
10#![doc = include_str!("../README.md")]
11mod error;
12mod flags;
13mod impls;
14
15pub use ark_std::io::{Read, Write};
16
17pub use error::*;
18pub use flags::*;
19
20#[cfg(test)]
21mod test;
22
23#[cfg(feature = "derive")]
24#[doc(hidden)]
25pub use ark_serialize_derive::*;
26
27use digest::{generic_array::GenericArray, Digest, OutputSizeUser};
28
29/// Serializes the given `CanonicalSerialize` items in sequence. `serialize_to_vec![a, b, c, d, e]`
30/// is identical to the value of `buf` after `(a, b, c, d, e).serialize_compressed(&mut buf)`.
31#[macro_export]
32macro_rules! serialize_to_vec {
33    ($($x:expr),*) => ({
34        let mut buf = ::ark_std::vec![];
35        {$crate::serialize_to_vec!(@inner buf, $($x),*)}.map(|_| buf)
36    });
37
38    (@inner $buf:expr, $y:expr, $($x:expr),*) => ({
39        {
40            $crate::CanonicalSerialize::serialize_uncompressed(&$y, &mut $buf)
41        }.and({$crate::serialize_to_vec!(@inner $buf, $($x),*)})
42    });
43
44    (@inner $buf:expr, $x:expr) => ({
45        $crate::CanonicalSerialize::serialize_uncompressed(&$x, &mut $buf)
46    });
47}
48
49/// Whether to use a compressed version of the serialization algorithm. Specific behavior depends
50/// on implementation. If no compressed version exists (e.g. on `Fp`), mode is ignored.
51#[derive(Copy, Clone, PartialEq, Eq)]
52pub enum Compress {
53    Yes,
54    No,
55}
56
57/// Whether to validate the element after deserializing it. Specific behavior depends on
58/// implementation. If no validation algorithm exists (e.g. on `Fp`), mode is ignored.
59#[derive(Copy, Clone, PartialEq, Eq)]
60pub enum Validate {
61    Yes,
62    No,
63}
64
65pub trait Valid: Sized {
66    fn check(&self) -> Result<(), SerializationError>;
67
68    fn batch_check<'a>(batch: impl Iterator<Item = &'a Self>) -> Result<(), SerializationError>
69    where
70        Self: 'a,
71    {
72        #[cfg(feature = "parallel")]
73        {
74            use rayon::{iter::ParallelBridge, prelude::ParallelIterator};
75            batch.par_bridge().try_for_each(|e| e.check())?;
76        }
77        #[cfg(not(feature = "parallel"))]
78        {
79            for item in batch {
80                item.check()?;
81            }
82        }
83        Ok(())
84    }
85}
86
87/// Serializer in little endian format.
88/// This trait can be derived if all fields of a struct implement
89/// `CanonicalSerialize` and the `derive` feature is enabled.
90///
91/// # Example
92/// ```
93/// // The `derive` feature must be set for the derivation to work.
94/// use ark_serialize::*;
95///
96/// # #[cfg(feature = "derive")]
97/// #[derive(CanonicalSerialize)]
98/// struct TestStruct {
99///     a: u64,
100///     b: (u64, (u64, u64)),
101/// }
102/// ```
103pub trait CanonicalSerialize {
104    /// The general serialize method that takes in customization flags.
105    fn serialize_with_mode<W: Write>(
106        &self,
107        writer: W,
108        compress: Compress,
109    ) -> Result<(), SerializationError>;
110
111    fn serialized_size(&self, compress: Compress) -> usize;
112
113    fn serialize_compressed<W: Write>(&self, writer: W) -> Result<(), SerializationError> {
114        self.serialize_with_mode(writer, Compress::Yes)
115    }
116
117    fn compressed_size(&self) -> usize {
118        self.serialized_size(Compress::Yes)
119    }
120
121    fn serialize_uncompressed<W: Write>(&self, writer: W) -> Result<(), SerializationError> {
122        self.serialize_with_mode(writer, Compress::No)
123    }
124
125    fn uncompressed_size(&self) -> usize {
126        self.serialized_size(Compress::No)
127    }
128}
129
130/// Deserializer in little endian format.
131/// This trait can be derived if all fields of a struct implement
132/// `CanonicalDeserialize` and the `derive` feature is enabled.
133///
134/// # Example
135/// ```
136/// // The `derive` feature must be set for the derivation to work.
137/// use ark_serialize::*;
138///
139/// # #[cfg(feature = "derive")]
140/// #[derive(CanonicalDeserialize)]
141/// struct TestStruct {
142///     a: u64,
143///     b: (u64, (u64, u64)),
144/// }
145/// ```
146pub trait CanonicalDeserialize: Valid {
147    /// The general deserialize method that takes in customization flags.
148    fn deserialize_with_mode<R: Read>(
149        reader: R,
150        compress: Compress,
151        validate: Validate,
152    ) -> Result<Self, SerializationError>;
153
154    fn deserialize_compressed<R: Read>(reader: R) -> Result<Self, SerializationError> {
155        Self::deserialize_with_mode(reader, Compress::Yes, Validate::Yes)
156    }
157
158    fn deserialize_compressed_unchecked<R: Read>(reader: R) -> Result<Self, SerializationError> {
159        Self::deserialize_with_mode(reader, Compress::Yes, Validate::No)
160    }
161
162    fn deserialize_uncompressed<R: Read>(reader: R) -> Result<Self, SerializationError> {
163        Self::deserialize_with_mode(reader, Compress::No, Validate::Yes)
164    }
165
166    fn deserialize_uncompressed_unchecked<R: Read>(reader: R) -> Result<Self, SerializationError> {
167        Self::deserialize_with_mode(reader, Compress::No, Validate::No)
168    }
169}
170
171/// Serializer in little endian format allowing to encode flags.
172pub trait CanonicalSerializeWithFlags: CanonicalSerialize {
173    /// Serializes `self` and `flags` into `writer`.
174    fn serialize_with_flags<W: Write, F: Flags>(
175        &self,
176        writer: W,
177        flags: F,
178    ) -> Result<(), SerializationError>;
179
180    /// Serializes `self` and `flags` into `writer`.
181    fn serialized_size_with_flags<F: Flags>(&self) -> usize;
182}
183
184/// Deserializer in little endian format allowing flags to be encoded.
185pub trait CanonicalDeserializeWithFlags: Sized {
186    /// Reads `Self` and `Flags` from `reader`.
187    /// Returns empty flags by default.
188    fn deserialize_with_flags<R: Read, F: Flags>(
189        reader: R,
190    ) -> Result<(Self, F), SerializationError>;
191}
192
193// This private struct works around Serialize taking the pre-existing
194// std::io::Write instance of most digest::Digest implementations by value
195struct HashMarshaller<'a, H: Digest>(&'a mut H);
196
197impl<'a, H: Digest> ark_std::io::Write for HashMarshaller<'a, H> {
198    #[inline]
199    fn write(&mut self, buf: &[u8]) -> ark_std::io::Result<usize> {
200        Digest::update(self.0, buf);
201        Ok(buf.len())
202    }
203
204    #[inline]
205    fn flush(&mut self) -> ark_std::io::Result<()> {
206        Ok(())
207    }
208}
209
210/// The CanonicalSerialize induces a natural way to hash the
211/// corresponding value, of which this is the convenience trait.
212pub trait CanonicalSerializeHashExt: CanonicalSerialize {
213    fn hash<H: Digest>(&self) -> GenericArray<u8, <H as OutputSizeUser>::OutputSize> {
214        let mut hasher = H::new();
215        self.serialize_compressed(HashMarshaller(&mut hasher))
216            .expect("HashMarshaller::flush should be infaillible!");
217        hasher.finalize()
218    }
219
220    fn hash_uncompressed<H: Digest>(&self) -> GenericArray<u8, <H as OutputSizeUser>::OutputSize> {
221        let mut hasher = H::new();
222        self.serialize_uncompressed(HashMarshaller(&mut hasher))
223            .expect("HashMarshaller::flush should be infaillible!");
224        hasher.finalize()
225    }
226}
227
228/// CanonicalSerializeHashExt is a (blanket) extension trait of
229/// CanonicalSerialize
230impl<T: CanonicalSerialize> CanonicalSerializeHashExt for T {}
231
232#[inline]
233pub fn buffer_bit_byte_size(modulus_bits: usize) -> (usize, usize) {
234    let byte_size = buffer_byte_size(modulus_bits);
235    ((byte_size * 8), byte_size)
236}
237
238/// Converts the number of bits required to represent a number
239/// into the number of bytes required to represent it.
240#[inline]
241pub const fn buffer_byte_size(modulus_bits: usize) -> usize {
242    (modulus_bits + 7) / 8
243}