snarkvm_synthesizer_program/mapping/
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 Mapping<N> {
19    /// Reads the mapping from a buffer.
20    #[inline]
21    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
22        // Read the mapping name.
23        let name = Identifier::<N>::read_le(&mut reader)?;
24        // Read the key statement.
25        let key = FromBytes::read_le(&mut reader)?;
26        // Read the value statement.
27        let value = FromBytes::read_le(&mut reader)?;
28        // Return the new mapping.
29        Ok(Self::new(name, key, value))
30    }
31}
32
33impl<N: Network> ToBytes for Mapping<N> {
34    /// Writes the mapping to a buffer.
35    #[inline]
36    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
37        // Write the mapping name.
38        self.name.write_le(&mut writer)?;
39        // Write the key statement.
40        self.key.write_le(&mut writer)?;
41        // Write the value statement.
42        self.value.write_le(&mut writer)
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use console::network::MainnetV0;
50
51    type CurrentNetwork = MainnetV0;
52
53    #[test]
54    fn test_mapping_bytes() -> Result<()> {
55        let mapping_string = r"
56mapping main:
57    key as field.public;
58    value as field.public;";
59
60        let expected = Mapping::<CurrentNetwork>::from_str(mapping_string)?;
61        let expected_bytes = expected.to_bytes_le()?;
62        println!("String size: {:?}, Bytecode size: {:?}", mapping_string.len(), expected_bytes.len());
63
64        let candidate = Mapping::<CurrentNetwork>::from_bytes_le(&expected_bytes)?;
65        assert_eq!(expected.to_string(), candidate.to_string());
66        assert_eq!(expected_bytes, candidate.to_bytes_le()?);
67        Ok(())
68    }
69}