datex_core/dif/pointer_address/
serde_dif.rs1use crate::{
2 alloc::string::ToString, dif::pointer_address::PointerAddressWithOwnership,
3};
4
5use alloc::string::String;
6use serde::{Deserialize, Serialize, de::Error};
7impl Serialize for PointerAddressWithOwnership {
8 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
9 where
10 S: serde::Serializer,
11 {
12 self.to_string().serialize(serializer)
13 }
14}
15
16impl<'de> Deserialize<'de> for PointerAddressWithOwnership {
17 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
18 where
19 D: serde::Deserializer<'de>,
20 {
21 let s = String::deserialize(deserializer)?;
22 s.as_str().try_into().map_err(D::Error::custom)
23 }
24}
25
26#[cfg(test)]
27mod test {
28 use crate::{
29 alloc::format,
30 dif::pointer_address::PointerAddressWithOwnership,
31 runtime::pointer_address_provider::SelfOwnedPointerAddressProvider,
32 shared_values::{
33 PointerAddress, ReferenceMutability, SharedContainerOwnership,
34 },
35 };
36 use test_case::test_case;
37
38 #[test_case(SharedContainerOwnership::Referenced(ReferenceMutability::Mutable), "'mut" ; "mutable")]
39 #[test_case(SharedContainerOwnership::Referenced(ReferenceMutability::Immutable), "'" ; "immutable")]
40 #[test_case(SharedContainerOwnership::Owned, "" ; "owned")]
41 fn serde(ownership: SharedContainerOwnership, expected_prefix: &str) {
42 let mut pointer_address_provider =
43 SelfOwnedPointerAddressProvider::default();
44 let pointer_address =
45 pointer_address_provider.get_new_self_owned_address();
46 let address = PointerAddress::SelfOwned(pointer_address);
47 let pointer_with_ownership = PointerAddressWithOwnership {
48 address: address.clone(),
49 ownership,
50 };
51 let serialized =
52 serde_json::to_string(&pointer_with_ownership).unwrap();
53 assert_eq!(serialized, format!("\"{expected_prefix}{address}\""));
54 let deserialized: PointerAddressWithOwnership =
55 serde_json::from_str(&serialized).unwrap();
56 assert_eq!(deserialized, pointer_with_ownership);
57 }
58}