snarkvm_console_types_integers/
serialize.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<E: Environment, I: IntegerType> Serialize for Integer<E, I> {
19    /// Serializes the integer into a string or as bytes.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => serializer.collect_str(self),
23            false => ToBytesSerializer::serialize(self, serializer),
24        }
25    }
26}
27
28impl<'de, E: Environment, I: IntegerType> Deserialize<'de> for Integer<E, I> {
29    /// Deserializes the integer from a string or bytes.
30    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
31        match deserializer.is_human_readable() {
32            true => FromStr::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom),
33            false => FromBytesDeserializer::<Self>::deserialize(deserializer, "integer", Self::size_in_bytes()),
34        }
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use snarkvm_console_network_environment::Console;
42
43    type CurrentEnvironment = Console;
44
45    const ITERATIONS: u64 = 1000;
46
47    fn check_serde_json<I: IntegerType>(rng: &mut TestRng) -> Result<()> {
48        for _ in 0..ITERATIONS {
49            // Sample a new integer.
50            let expected = Integer::<CurrentEnvironment, I>::new(Uniform::rand(rng));
51
52            // Serialize
53            let expected_string = &expected.to_string();
54            let candidate_string = serde_json::to_string(&expected)?;
55            assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
56
57            // Deserialize
58            assert_eq!(expected, Integer::from_str(expected_string)?);
59            assert_eq!(expected, serde_json::from_str(&candidate_string)?);
60        }
61        Ok(())
62    }
63
64    fn check_bincode<I: IntegerType>(rng: &mut TestRng) -> Result<()> {
65        for _ in 0..ITERATIONS {
66            // Sample a new integer.
67            let expected = Integer::<CurrentEnvironment, I>::new(Uniform::rand(rng));
68
69            // Serialize
70            let expected_bytes = expected.to_bytes_le()?;
71            assert_eq!(&expected_bytes[..], &bincode::serialize(&expected)?[..]);
72
73            // Deserialize
74            assert_eq!(expected, Integer::read_le(&expected_bytes[..])?);
75            assert_eq!(expected, bincode::deserialize(&expected_bytes[..])?);
76        }
77        Ok(())
78    }
79
80    #[test]
81    fn test_serde_json() -> Result<()> {
82        let mut rng = TestRng::default();
83
84        check_serde_json::<u8>(&mut rng)?;
85        check_serde_json::<u16>(&mut rng)?;
86        check_serde_json::<u32>(&mut rng)?;
87        check_serde_json::<u64>(&mut rng)?;
88        check_serde_json::<u128>(&mut rng)?;
89
90        check_serde_json::<i8>(&mut rng)?;
91        check_serde_json::<i16>(&mut rng)?;
92        check_serde_json::<i32>(&mut rng)?;
93        check_serde_json::<i64>(&mut rng)?;
94        check_serde_json::<i128>(&mut rng)?;
95        Ok(())
96    }
97
98    #[test]
99    fn test_bincode() -> Result<()> {
100        let mut rng = TestRng::default();
101
102        check_bincode::<u8>(&mut rng)?;
103        check_bincode::<u16>(&mut rng)?;
104        check_bincode::<u32>(&mut rng)?;
105        check_bincode::<u64>(&mut rng)?;
106        check_bincode::<u128>(&mut rng)?;
107
108        check_bincode::<i8>(&mut rng)?;
109        check_bincode::<i16>(&mut rng)?;
110        check_bincode::<i32>(&mut rng)?;
111        check_bincode::<i64>(&mut rng)?;
112        check_bincode::<i128>(&mut rng)?;
113        Ok(())
114    }
115}