use super::*;
use snarkvm_utilities::DeserializeExt;
impl<N: Network> Serialize for Request<N> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match serializer.is_human_readable() {
true => {
let mut transition = serializer.serialize_struct("Request", 10)?;
transition.serialize_field("signer", &self.signer)?;
transition.serialize_field("network", &self.network_id)?;
transition.serialize_field("program", &self.program_id)?;
transition.serialize_field("function", &self.function_name)?;
transition.serialize_field("input_ids", &self.input_ids)?;
transition.serialize_field("inputs", &self.inputs)?;
transition.serialize_field("signature", &self.signature)?;
transition.serialize_field("sk_tag", &self.sk_tag)?;
transition.serialize_field("tvk", &self.tvk)?;
transition.serialize_field("tcm", &self.tcm)?;
transition.end()
}
false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
}
}
}
impl<'de, N: Network> Deserialize<'de> for Request<N> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
match deserializer.is_human_readable() {
true => {
let mut request = serde_json::Value::deserialize(deserializer)?;
Ok(Self::from((
DeserializeExt::take_from_value::<D>(&mut request, "signer")?,
DeserializeExt::take_from_value::<D>(&mut request, "network")?,
DeserializeExt::take_from_value::<D>(&mut request, "program")?,
DeserializeExt::take_from_value::<D>(&mut request, "function")?,
DeserializeExt::take_from_value::<D>(&mut request, "input_ids")?,
DeserializeExt::take_from_value::<D>(&mut request, "inputs")?,
DeserializeExt::take_from_value::<D>(&mut request, "signature")?,
DeserializeExt::take_from_value::<D>(&mut request, "sk_tag")?,
DeserializeExt::take_from_value::<D>(&mut request, "tvk")?,
DeserializeExt::take_from_value::<D>(&mut request, "tcm")?,
)))
}
false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "request"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_serde_json() -> Result<()> {
let mut rng = TestRng::default();
for expected in test_helpers::sample_requests(&mut rng).into_iter() {
let expected_string = &expected.to_string();
let candidate_string = serde_json::to_string(&expected)?;
assert_eq!(expected, Request::from_str(expected_string)?);
assert_eq!(expected, serde_json::from_str(&candidate_string)?);
}
Ok(())
}
#[test]
fn test_bincode() {
let mut rng = TestRng::default();
for expected in test_helpers::sample_requests(&mut rng).into_iter() {
let expected_bytes = expected.to_bytes_le().unwrap();
let expected_bytes_with_size_encoding = bincode::serialize(&expected).unwrap();
assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
assert_eq!(expected, Request::read_le(&expected_bytes[..]).unwrap());
assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding).unwrap());
}
}
}