snarkvm_ledger_narwhal_subdag/
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<N: Network> Serialize for Subdag<N> {
19    /// Serializes the subdag to a JSON-string or buffer.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => {
23                let mut certificate = serializer.serialize_struct("Subdag", 1)?;
24                certificate.serialize_field("subdag", &self.subdag)?;
25                certificate.end()
26            }
27            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
28        }
29    }
30}
31
32impl<'de, N: Network> Deserialize<'de> for Subdag<N> {
33    /// Deserializes the subdag from a JSON-string or buffer.
34    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
35        match deserializer.is_human_readable() {
36            true => {
37                let mut value = serde_json::Value::deserialize(deserializer)?;
38
39                Ok(Self::from(DeserializeExt::take_from_value::<D>(&mut value, "subdag")?)
40                    .map_err(de::Error::custom)?)
41            }
42            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "subdag"),
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    fn check_serde_json<
52        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
53    >(
54        expected: T,
55    ) {
56        // Serialize
57        let expected_string = expected.to_string();
58        let candidate_string = serde_json::to_string(&expected).unwrap();
59        let candidate = serde_json::from_str::<T>(&candidate_string).unwrap();
60        assert_eq!(expected, candidate);
61        assert_eq!(expected_string, candidate_string);
62        assert_eq!(expected_string, candidate.to_string());
63
64        // Deserialize
65        assert_eq!(expected, T::from_str(&expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
66        assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
67    }
68
69    fn check_bincode<
70        T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
71    >(
72        expected: T,
73    ) {
74        // Serialize
75        let expected_bytes = expected.to_bytes_le().unwrap();
76        let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
77        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
78
79        // Deserialize
80        assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
81        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
82    }
83
84    #[test]
85    fn test_serde_json() {
86        let rng = &mut TestRng::default();
87
88        for expected in crate::test_helpers::sample_subdags(rng) {
89            check_serde_json(expected);
90        }
91    }
92
93    #[test]
94    fn test_bincode() {
95        let rng = &mut TestRng::default();
96
97        for expected in crate::test_helpers::sample_subdags(rng) {
98            check_bincode(expected);
99        }
100    }
101}