/ console / program / src / data / value / serialize.rs
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  impl<N: Network> Serialize for Value<N> {
 19      /// Serializes the value into string or 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  
 28  impl<'de, N: Network> Deserialize<'de> for Value<N> {
 29      /// Deserializes the value 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, "value"),
 34          }
 35      }
 36  }
 37  
 38  #[cfg(test)]
 39  mod tests {
 40      use super::*;
 41      use alphavm_console_network::MainnetV0;
 42  
 43      type CurrentNetwork = MainnetV0;
 44  
 45      #[test]
 46      fn test_serde_json() -> Result<()> {
 47          {
 48              // Prepare the plaintext string.
 49              let string = r"{
 50    owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w,
 51    token_amount: 100u64
 52  }";
 53              // Construct a new plaintext value.
 54              let expected = Value::<CurrentNetwork>::from_str(string).unwrap();
 55              assert!(matches!(expected, Value::Plaintext(..)));
 56  
 57              // Serialize
 58              let expected_string = &expected.to_string();
 59              let candidate_string = serde_json::to_string(&expected)?;
 60              assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
 61  
 62              // Deserialize
 63              assert_eq!(expected, Value::from_str(expected_string)?);
 64              assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 65          }
 66          {
 67              // Prepare the record string.
 68              let string = r"{
 69    owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.private,
 70    token_amount: 100u64.private,
 71    _nonce: 6122363155094913586073041054293642159180066699840940609722305038224296461351group.public
 72  }";
 73              // Construct a new record value.
 74              let expected = Value::<CurrentNetwork>::from_str(string).unwrap();
 75              assert!(matches!(expected, Value::Record(..)));
 76  
 77              // Serialize
 78              let expected_string = &expected.to_string();
 79              let candidate_string = serde_json::to_string(&expected)?;
 80              assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
 81  
 82              // Deserialize
 83              assert_eq!(expected, Value::from_str(expected_string)?);
 84              assert_eq!(expected, serde_json::from_str(&candidate_string)?);
 85          }
 86          Ok(())
 87      }
 88  
 89      #[test]
 90      fn test_bincode() -> Result<()> {
 91          {
 92              // Prepare the plaintext string.
 93              let string = r"{
 94    owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w,
 95    token_amount: 100u64
 96  }";
 97              // Construct a new plaintext value.
 98              let expected = Value::<CurrentNetwork>::from_str(string).unwrap();
 99              assert!(matches!(expected, Value::Plaintext(..)));
100  
101              // Serialize
102              let expected_bytes = expected.to_bytes_le()?;
103              let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
104              assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
105  
106              // Deserialize
107              assert_eq!(expected, Value::read_le(&expected_bytes[..])?);
108              assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
109          }
110          {
111              // Prepare the record string.
112              let string = r"{
113    owner: ax150w2lvhdzychwvzu54ys5zas7tm5s0ycdyw563pms83g9u0vucgqe5fs5w.private,
114    token_amount: 100u64.private,
115    _nonce: 6122363155094913586073041054293642159180066699840940609722305038224296461351group.public
116  }";
117              // Construct a new record value.
118              let expected = Value::<CurrentNetwork>::from_str(string).unwrap();
119              assert!(matches!(expected, Value::Record(..)));
120  
121              // Serialize
122              let expected_bytes = expected.to_bytes_le()?;
123              let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
124              assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
125  
126              // Deserialize
127              assert_eq!(expected, Value::read_le(&expected_bytes[..])?);
128              assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
129          }
130          Ok(())
131      }
132  }