snarkvm_utilities/serialize/
helpers.rs

1// Copyright (c) 2019-2025 Provable Inc.
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
16use std::io::{Read, Write};
17
18pub use crate::{FromBytes, ToBytes};
19use crate::{SerializationError, serialize::traits::*};
20
21/// Serialize a Vector's elements without serializing the Vector's length
22/// If you want to serialize the full Vector, use `CanonicalSerialize for Vec<T>`
23pub fn serialize_vec_without_len<'a>(
24    src: impl Iterator<Item = &'a (impl CanonicalSerialize + 'a)>,
25    mut writer: impl Write,
26    compress: Compress,
27) -> Result<(), SerializationError> {
28    for elem in src {
29        CanonicalSerialize::serialize_with_mode(elem, &mut writer, compress)?;
30    }
31    Ok(())
32}
33
34/// Serialize a Vector's element sizes without serializing the Vector's length
35/// If you want to serialize the full Vector, use `CanonicalSerialize for Vec<T>`
36pub fn serialized_vec_size_without_len(src: &[impl CanonicalSerialize], compress: Compress) -> usize {
37    if src.is_empty() { 0 } else { src.len() * CanonicalSerialize::serialized_size(&src[0], compress) }
38}
39
40/// Deserialize a Vector's elements without deserializing the Vector's length
41/// If you want to deserialize the full Vector, use `CanonicalDeserialize for Vec<T>`
42pub fn deserialize_vec_without_len<T: CanonicalDeserialize>(
43    mut reader: impl Read,
44    compress: Compress,
45    validate: Validate,
46    len: usize,
47) -> Result<Vec<T>, SerializationError> {
48    (0..len).map(|_| CanonicalDeserialize::deserialize_with_mode(&mut reader, compress, validate)).collect()
49}