Skip to main content

datex_core/shared_values/
pointer_address.rs

1use crate::prelude::*;
2
3use crate::values::core_values::endpoint::Endpoint;
4use binrw::{BinRead, BinWrite};
5use core::{fmt::Display, result::Result};
6use serde::{Deserialize, Serialize};
7
8#[derive(BinWrite, BinRead, Debug, Clone, PartialEq, Eq, Hash)]
9#[brw(little)]
10pub struct SelfOwnedPointerAddress(pub [u8; 5]);
11
12#[derive(
13    BinWrite, BinRead, Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash,
14)]
15#[brw(little)]
16pub struct RemotePointerAddress(pub [u8; 26]);
17
18impl RemotePointerAddress {
19    pub fn for_endpoint(
20        endpoint: &Endpoint,
21        self_owned_pointer_address: &SelfOwnedPointerAddress,
22    ) -> Self {
23        let endpoint_slice = endpoint.to_slice();
24        let mut address = [0u8; 26];
25        address[..endpoint_slice.len()].copy_from_slice(&endpoint_slice);
26        address[endpoint_slice.len()
27            ..endpoint_slice.len() + self_owned_pointer_address.0.len()]
28            .copy_from_slice(&self_owned_pointer_address.0);
29        RemotePointerAddress(address)
30    }
31
32    pub fn to_address_string(&self) -> String {
33        hex::encode(self.0)
34    }
35
36    /// Returns the endpoint part of the remote pointer address
37    pub fn endpoint(&self) -> Endpoint {
38        let mut endpoint = [0u8; 21];
39        endpoint.copy_from_slice(&self.0[0..21]);
40        Endpoint::from_slice(endpoint).unwrap()
41    }
42
43    /// Normalizes the pointer address to a self-owned address if it is a
44    /// remote address with the same endpoint as the provided local endpoint.
45    pub fn normalize(self, local_endpoint: &Endpoint) -> PointerAddress {
46        if &self.endpoint() == local_endpoint {
47            let mut id = [0u8; 5];
48            id.copy_from_slice(&self.0[21..26]);
49            PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(id))
50        } else {
51            PointerAddress::Remote(self)
52        }
53    }
54}
55
56impl Display for RemotePointerAddress {
57    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58        core::write!(f, "${}", self.to_address_string())
59    }
60}
61
62impl SelfOwnedPointerAddress {
63    pub fn new(address: [u8; 5]) -> Self {
64        SelfOwnedPointerAddress(address)
65    }
66
67    pub fn to_address_string(&self) -> String {
68        hex::encode(self.0)
69    }
70}
71
72impl TryFrom<String> for SelfOwnedPointerAddress {
73    type Error = &'static str;
74    fn try_from(s: String) -> Result<Self, Self::Error> {
75        let hex_str = if let Some(stripped) = s.strip_prefix('$') {
76            stripped
77        } else {
78            &s
79        };
80
81        hex::decode(hex_str)
82            .map_err(|_| "Invalid hex string for SelfOwnedPointerAddress")
83            .and_then(|bytes| {
84                if bytes.len() == 5 {
85                    let mut arr = [0u8; 5];
86                    arr.copy_from_slice(&bytes);
87                    Ok(SelfOwnedPointerAddress::new(arr))
88                } else {
89                    Err("SelfOwnedPointerAddress must be 5 bytes long")
90                }
91            })
92    }
93}
94
95impl Display for SelfOwnedPointerAddress {
96    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
97        core::write!(f, "${}", self.to_address_string())
98    }
99}
100
101#[derive(BinWrite, BinRead, Debug, Clone, PartialEq, Eq, Hash)]
102#[brw(little)]
103pub enum PointerAddress {
104    // pointer with the local endpoint as origin
105    // the full pointer id consists of the local endpoint id + this local id
106    #[brw(magic = 0u8)]
107    SelfOwned(SelfOwnedPointerAddress),
108    #[brw(magic = 1u8)]
109    // pointer with a remote endpoint as origin, contains the full pointers address
110    Remote(RemotePointerAddress),
111}
112
113impl PointerAddress {
114    pub fn self_owned(address: [u8; 5]) -> Self {
115        PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(address))
116    }
117
118    pub fn remote(address: [u8; 26]) -> Self {
119        PointerAddress::Remote(RemotePointerAddress(address))
120    }
121
122    /// Normalizes the pointer address to a self-owned address if it is a
123    /// remote address with the same endpoint as the provided local endpoint.
124    pub fn normalize(self, local_endpoint: &Endpoint) -> Self {
125        match self {
126            PointerAddress::Remote(remote_address) => {
127                remote_address.normalize(local_endpoint)
128            }
129            _ => self,
130        }
131    }
132}
133
134impl TryFrom<String> for PointerAddress {
135    type Error = &'static str;
136    fn try_from(s: String) -> Result<Self, Self::Error> {
137        PointerAddress::try_from(s.as_str())
138    }
139}
140impl TryFrom<&str> for PointerAddress {
141    type Error = &'static str;
142    fn try_from(s: &str) -> Result<Self, Self::Error> {
143        let hex_str = if let Some(stripped) = s.strip_prefix('$') {
144            stripped
145        } else {
146            s
147        };
148
149        let bytes = hex::decode(hex_str).map_err(|_| "Invalid hex string")?;
150        match bytes.len() {
151            5 => {
152                let mut arr = [0u8; 5];
153                arr.copy_from_slice(&bytes);
154                Ok(PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(arr)))
155            }
156            26 => {
157                let mut arr = [0u8; 26];
158                arr.copy_from_slice(&bytes);
159                Ok(PointerAddress::Remote(RemotePointerAddress(arr)))
160            }
161            _ => Err("PointerAddress must be 5 or 26 bytes long"),
162        }
163    }
164}
165
166impl From<SelfOwnedPointerAddress> for PointerAddress {
167    fn from(owned: SelfOwnedPointerAddress) -> Self {
168        PointerAddress::SelfOwned(owned)
169    }
170}
171
172impl From<RemotePointerAddress> for PointerAddress {
173    fn from(remote: RemotePointerAddress) -> Self {
174        PointerAddress::Remote(remote)
175    }
176}
177
178impl PointerAddress {
179    pub fn to_address_string(&self) -> String {
180        match self {
181            PointerAddress::SelfOwned(local_address) => {
182                local_address.to_address_string()
183            }
184            PointerAddress::Remote(address) => address.to_address_string(),
185        }
186    }
187}
188
189impl Display for PointerAddress {
190    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
191        match self {
192            PointerAddress::SelfOwned(local_address) => {
193                core::write!(f, "{}", local_address)
194            }
195            PointerAddress::Remote(address) => {
196                core::write!(f, "{}", address)
197            }
198        }
199    }
200}
201impl Serialize for PointerAddress {
202    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
203    where
204        S: serde::Serializer,
205    {
206        let addr_str = self.to_address_string();
207        serializer.serialize_str(&addr_str)
208    }
209}
210impl<'de> Deserialize<'de> for PointerAddress {
211    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
212    where
213        D: serde::Deserializer<'de>,
214    {
215        let s = String::deserialize(deserializer)?;
216        PointerAddress::try_from(s.as_str()).map_err(|e| {
217            serde::de::Error::custom(format!(
218                "Failed to parse PointerAddress: {}",
219                e
220            ))
221        })
222    }
223}
224
225impl PointerAddress {
226    pub fn bytes(&self) -> &[u8] {
227        match self {
228            PointerAddress::SelfOwned(local_address) => &local_address.0,
229            PointerAddress::Remote(addr) => &addr.0,
230        }
231    }
232}