snarkvm_console_program/data/plaintext/
serialize.rs

1// Copyright 2024-2025 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
16use super::*;
17
18impl<N: Network> Serialize for Plaintext<N> {
19    /// Serializes the plaintext 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_with_size_encoding(self, serializer),
24        }
25    }
26}
27
28impl<'de, N: Network> Deserialize<'de> for Plaintext<N> {
29    /// Deserializes the plaintext 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_with_size_encoding(deserializer, "plaintext"),
34        }
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use snarkvm_console_network::MainnetV0;
42
43    type CurrentNetwork = MainnetV0;
44
45    const ITERATIONS: u64 = 2;
46
47    #[test]
48    fn test_serde_json() -> Result<()> {
49        fn run_test(expected: Plaintext<CurrentNetwork>) {
50            for _ in 0..ITERATIONS {
51                // Serialize
52                let expected_string = &expected.to_string();
53                let candidate_string = serde_json::to_string(&expected).unwrap();
54                assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string).unwrap().as_str().unwrap());
55
56                // Deserialize
57                assert_eq!(expected, Plaintext::from_str(expected_string).unwrap());
58                assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
59            }
60        }
61
62        // Test struct.
63        run_test(Plaintext::<CurrentNetwork>::from_str(
64            "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah, token_amount: 100u64 }",
65        )?);
66
67        // Test array.
68        run_test(Plaintext::<CurrentNetwork>::from_str("[ 0field, 1field, 2field, 3field, 4field ]")?);
69
70        Ok(())
71    }
72
73    #[test]
74    fn test_bincode() -> Result<()> {
75        fn run_test(expected: Plaintext<CurrentNetwork>) {
76            for _ in 0..ITERATIONS {
77                // Serialize
78                let expected_bytes = expected.to_bytes_le().unwrap();
79                let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
80                assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
81
82                // Deserialize
83                assert_eq!(expected, Plaintext::read_le(&expected_bytes[..]).unwrap());
84                assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
85            }
86        }
87
88        // Test struct.
89        run_test(Plaintext::<CurrentNetwork>::from_str(
90            "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah, token_amount: 100u64 }",
91        )?);
92
93        // Test array.
94        run_test(Plaintext::<CurrentNetwork>::from_str("[ 0field, 1field, 2field, 3field, 4field ]")?);
95
96        Ok(())
97    }
98}