snarkvm_utilities/serialize/helpers.rs
1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16pub use crate::{
17 FromBytes,
18 ToBytes,
19 Vec,
20 io::{self, Read, Write},
21};
22use crate::{SerializationError, serialize::traits::*};
23
24/// Serialize a Vector's elements without serializing the Vector's length
25/// If you want to serialize the full Vector, use `CanonicalSerialize for Vec<T>`
26pub fn serialize_vec_without_len<'a>(
27 src: impl Iterator<Item = &'a (impl CanonicalSerialize + 'a)>,
28 mut writer: impl Write,
29 compress: Compress,
30) -> Result<(), SerializationError> {
31 for elem in src {
32 CanonicalSerialize::serialize_with_mode(elem, &mut writer, compress)?;
33 }
34 Ok(())
35}
36
37/// Serialize a Vector's element sizes without serializing the Vector's length
38/// If you want to serialize the full Vector, use `CanonicalSerialize for Vec<T>`
39pub fn serialized_vec_size_without_len(src: &[impl CanonicalSerialize], compress: Compress) -> usize {
40 if src.is_empty() { 0 } else { src.len() * CanonicalSerialize::serialized_size(&src[0], compress) }
41}
42
43/// Deserialize a Vector's elements without deserializing the Vector's length
44/// If you want to deserialize the full Vector, use `CanonicalDeserialize for Vec<T>`
45pub fn deserialize_vec_without_len<T: CanonicalDeserialize>(
46 mut reader: impl Read,
47 compress: Compress,
48 validate: Validate,
49 len: usize,
50) -> Result<Vec<T>, SerializationError> {
51 (0..len).map(|_| CanonicalDeserialize::deserialize_with_mode(&mut reader, compress, validate)).collect()
52}