serialize.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the alphavm 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  
16  use super::*;
17  
18  use alphavm_utilities::DeserializeExt;
19  
20  impl<N: Network> Serialize for TransactionLeaf<N> {
21      /// Serializes the leaf into string or bytes.
22      fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
23          match serializer.is_human_readable() {
24              true => {
25                  let mut leaf = serializer.serialize_struct("TransactionLeaf", 3)?;
26                  leaf.serialize_field("variant", &self.variant)?;
27                  leaf.serialize_field("index", &self.index)?;
28                  leaf.serialize_field("id", &self.id)?;
29                  leaf.end()
30              }
31              false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
32          }
33      }
34  }
35  
36  impl<'de, N: Network> Deserialize<'de> for TransactionLeaf<N> {
37      /// Deserializes the leaf from a string or bytes.
38      fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
39          match deserializer.is_human_readable() {
40              true => {
41                  // Parse the leaf from a string into a value.
42                  let mut leaf = serde_json::Value::deserialize(deserializer)?;
43                  // Recover the leaf.
44                  Ok(Self::from(
45                      // Retrieve the variant.
46                      DeserializeExt::take_from_value::<D>(&mut leaf, "variant")?,
47                      // Retrieve the index.
48                      DeserializeExt::take_from_value::<D>(&mut leaf, "index")?,
49                      // Retrieve the id.
50                      DeserializeExt::take_from_value::<D>(&mut leaf, "id")?,
51                  ))
52              }
53              false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "transaction leaf"),
54          }
55      }
56  }
57  
58  #[cfg(test)]
59  mod tests {
60      use super::*;
61  
62      #[test]
63      fn test_serde_json() -> Result<()> {
64          let mut rng = TestRng::default();
65  
66          // Sample the leaf.
67          let expected = test_helpers::sample_leaf(&mut rng);
68  
69          // Serialize
70          let expected_string = &expected.to_string();
71          let candidate_string = serde_json::to_string(&expected)?;
72          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
73  
74          // Deserialize
75          assert_eq!(expected, TransactionLeaf::from_str(expected_string)?);
76          assert_eq!(expected, serde_json::from_str(&candidate_string)?);
77  
78          Ok(())
79      }
80  
81      #[test]
82      fn test_bincode() -> Result<()> {
83          let mut rng = TestRng::default();
84  
85          // Sample the leaf.
86          let expected = test_helpers::sample_leaf(&mut rng);
87  
88          // Serialize
89          let expected_bytes = expected.to_bytes_le()?;
90          let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
91          assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
92  
93          // Deserialize
94          assert_eq!(expected, TransactionLeaf::read_le(&expected_bytes[..])?);
95          assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
96  
97          Ok(())
98      }
99  }