snarkvm_console_program/data_types/struct_type/
bytes.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 super::*;
17
18impl<N: Network> FromBytes for StructType<N> {
19    /// Reads a struct type from a buffer.
20    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21        // Read the name of the struct type.
22        let name = Identifier::read_le(&mut reader)?;
23
24        // Read the number of members.
25        let num_members = u16::read_le(&mut reader)?;
26        // Ensure the number of members is within the maximum limit.
27        if num_members as usize > N::MAX_STRUCT_ENTRIES {
28            return Err(error(format!(
29                "StructType exceeds size: expected <= {}, found {num_members}",
30                N::MAX_STRUCT_ENTRIES
31            )));
32        }
33        // Read the members.
34        let mut members = IndexMap::with_capacity(num_members as usize);
35        for _ in 0..num_members {
36            // Read the identifier.
37            let identifier = Identifier::read_le(&mut reader)?;
38            // Read the plaintext type.
39            let plaintext_type = PlaintextType::read_le(&mut reader)?;
40            // Insert the member, and ensure the member has no duplicate names.
41            if members.insert(identifier, plaintext_type).is_some() {
42                return Err(error(format!("Duplicate identifier in struct '{name}'")));
43            };
44        }
45
46        Ok(Self { name, members })
47    }
48}
49
50impl<N: Network> ToBytes for StructType<N> {
51    /// Writes the struct type to a buffer.
52    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
53        // Ensure the number of members is within the maximum limit.
54        if self.members.len() > N::MAX_STRUCT_ENTRIES {
55            return Err(error("Failed to serialize struct: too many members"));
56        }
57
58        // Write the name of the struct.
59        self.name.write_le(&mut writer)?;
60
61        // Write the number of members.
62        u16::try_from(self.members.len()).or_halt_with::<N>("Struct length exceeds u16").write_le(&mut writer)?;
63        // Write the members as bytes.
64        for (identifier, plaintext_type) in &self.members {
65            // Write the identifier.
66            identifier.write_le(&mut writer)?;
67            // Write the plaintext type to the buffer.
68            plaintext_type.write_le(&mut writer)?;
69        }
70        Ok(())
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use snarkvm_console_network::MainnetV0;
78
79    type CurrentNetwork = MainnetV0;
80
81    #[test]
82    fn test_bytes() -> Result<()> {
83        let expected =
84            StructType::<CurrentNetwork>::from_str("struct message:\n    first as field;\n    second as field;")?;
85        let candidate = StructType::from_bytes_le(&expected.to_bytes_le().unwrap()).unwrap();
86        assert_eq!(expected, candidate);
87        Ok(())
88    }
89}