serialize.rs
  1  // Copyright (c) 2025 ADnet Contributors
  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  impl<N: Network> Serialize for FinalizeOperation<N> {
 19      /// Serializes the finalize operations 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                  // Serialize the components.
 24                  match self {
 25                      Self::InitializeMapping(mapping_id) => {
 26                          let mut operation = serializer.serialize_struct("FinalizeOperation", 2)?;
 27                          operation.serialize_field("type", "initialize_mapping")?;
 28                          operation.serialize_field("mapping_id", mapping_id)?;
 29                          operation.end()
 30                      }
 31                      Self::InsertKeyValue(mapping_id, key_id, value_id) => {
 32                          let mut operation = serializer.serialize_struct("FinalizeOperation", 4)?;
 33                          operation.serialize_field("type", "insert_key_value")?;
 34                          operation.serialize_field("mapping_id", mapping_id)?;
 35                          operation.serialize_field("key_id", key_id)?;
 36                          operation.serialize_field("value_id", value_id)?;
 37                          operation.end()
 38                      }
 39                      Self::UpdateKeyValue(mapping_id, key_id, value_id) => {
 40                          let mut operation = serializer.serialize_struct("FinalizeOperation", 4)?;
 41                          operation.serialize_field("type", "update_key_value")?;
 42                          operation.serialize_field("mapping_id", mapping_id)?;
 43                          operation.serialize_field("key_id", key_id)?;
 44                          operation.serialize_field("value_id", value_id)?;
 45                          operation.end()
 46                      }
 47                      Self::RemoveKeyValue(mapping_id, key_id) => {
 48                          let mut operation = serializer.serialize_struct("FinalizeOperation", 3)?;
 49                          operation.serialize_field("type", "remove_key_value")?;
 50                          operation.serialize_field("mapping_id", mapping_id)?;
 51                          operation.serialize_field("key_id", key_id)?;
 52                          operation.end()
 53                      }
 54                      Self::ReplaceMapping(mapping_id) => {
 55                          let mut operation = serializer.serialize_struct("FinalizeOperation", 2)?;
 56                          operation.serialize_field("type", "replace_mapping")?;
 57                          operation.serialize_field("mapping_id", mapping_id)?;
 58                          operation.end()
 59                      }
 60                      Self::RemoveMapping(mapping_id) => {
 61                          let mut operation = serializer.serialize_struct("FinalizeOperation", 2)?;
 62                          operation.serialize_field("type", "remove_mapping")?;
 63                          operation.serialize_field("mapping_id", mapping_id)?;
 64                          operation.end()
 65                      }
 66                  }
 67              }
 68              false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
 69          }
 70      }
 71  }
 72  
 73  impl<'de, N: Network> Deserialize<'de> for FinalizeOperation<N> {
 74      /// Deserializes the finalize operations from a JSON-string or buffer.
 75      fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
 76          match deserializer.is_human_readable() {
 77              true => {
 78                  let mut operation = serde_json::Value::deserialize(deserializer)?;
 79                  // Recover the operation.
 80                  let finalize_operation = match operation.get("type").and_then(|t| t.as_str()) {
 81                      Some("initialize_mapping") => {
 82                          // Deserialize the mapping ID.
 83                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
 84                          // Return the operation.
 85                          Self::InitializeMapping(mapping_id)
 86                      }
 87                      Some("insert_key_value") => {
 88                          // Deserialize the mapping ID.
 89                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
 90                          // Deserialize the key ID.
 91                          let key_id = DeserializeExt::take_from_value::<D>(&mut operation, "key_id")?;
 92                          // Deserialize the value ID.
 93                          let value_id = DeserializeExt::take_from_value::<D>(&mut operation, "value_id")?;
 94                          // Return the operation.
 95                          Self::InsertKeyValue(mapping_id, key_id, value_id)
 96                      }
 97                      Some("update_key_value") => {
 98                          // Deserialize the mapping ID.
 99                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
100                          // Deserialize the key ID.
101                          let key_id = DeserializeExt::take_from_value::<D>(&mut operation, "key_id")?;
102                          // Deserialize the value ID.
103                          let value_id = DeserializeExt::take_from_value::<D>(&mut operation, "value_id")?;
104                          // Return the operation.
105                          Self::UpdateKeyValue(mapping_id, key_id, value_id)
106                      }
107                      Some("remove_key_value") => {
108                          // Deserialize the mapping ID.
109                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
110                          // Deserialize the key ID.
111                          let key_id = DeserializeExt::take_from_value::<D>(&mut operation, "key_id")?;
112                          // Return the operation.
113                          Self::RemoveKeyValue(mapping_id, key_id)
114                      }
115                      Some("replace_mapping") => {
116                          // Deserialize the mapping ID.
117                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
118                          // Return the operation.
119                          Self::ReplaceMapping(mapping_id)
120                      }
121                      Some("remove_mapping") => {
122                          // Deserialize the mapping ID.
123                          let mapping_id = DeserializeExt::take_from_value::<D>(&mut operation, "mapping_id")?;
124                          // Return the operation.
125                          Self::RemoveMapping(mapping_id)
126                      }
127                      _ => return Err(de::Error::custom("Invalid finalize operation type")),
128                  };
129                  // Return the operation.
130                  Ok(finalize_operation)
131              }
132              false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "finalize operations"),
133          }
134      }
135  }
136  
137  #[cfg(test)]
138  mod tests {
139      use super::*;
140  
141      fn check_serde_json<
142          T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
143      >(
144          expected: T,
145      ) {
146          // Serialize
147          let expected_string = expected.to_string();
148          let candidate_string = serde_json::to_string(&expected).unwrap();
149          let candidate = serde_json::from_str::<T>(&candidate_string).unwrap();
150          assert_eq!(expected, candidate);
151          assert_eq!(expected_string, candidate_string);
152          assert_eq!(expected_string, candidate.to_string());
153  
154          // Deserialize
155          assert_eq!(expected, T::from_str(&expected_string).unwrap_or_else(|_| panic!("FromStr: {expected_string}")));
156          assert_eq!(expected, serde_json::from_str(&candidate_string).unwrap());
157      }
158  
159      fn check_bincode<
160          T: Serialize + for<'a> Deserialize<'a> + Debug + Display + PartialEq + Eq + FromStr + ToBytes + FromBytes,
161      >(
162          expected: T,
163      ) {
164          // Serialize
165          let expected_bytes = expected.to_bytes_le().unwrap();
166          let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
167          assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
168  
169          // Deserialize
170          assert_eq!(expected, T::read_le(&expected_bytes[..]).unwrap());
171          assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..]).unwrap());
172      }
173  
174      #[test]
175      fn test_serde_json() {
176          for finalize in crate::logic::finalize_operation::test_helpers::sample_finalize_operations() {
177              check_serde_json(finalize);
178          }
179      }
180  
181      #[test]
182      fn test_bincode() {
183          for finalize in crate::logic::finalize_operation::test_helpers::sample_finalize_operations() {
184              check_bincode(finalize);
185          }
186      }
187  }