Skip to main content

datex_core/shared_values/
pointer_address.rs

1//! This module contains the definition of pointer addresses for shared containers.
2use crate::prelude::*;
3
4use crate::values::core_values::endpoint::Endpoint;
5use binrw::{BinRead, BinWrite};
6use core::{fmt::Display, result::Result};
7use serde::{Deserialize, Serialize};
8
9#[derive(BinWrite, BinRead, Debug, Clone, PartialEq, Eq, Hash)]
10#[brw(little)]
11pub struct SelfOwnedPointerAddress(pub [u8; 5]);
12
13#[derive(
14    BinWrite, BinRead, Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash,
15)]
16#[brw(little)]
17pub struct RemotePointerAddress(pub [u8; 26]);
18
19impl RemotePointerAddress {
20    /// A built-in pointer address used for internal DATEX runtime pointers.
21    /// The origin endpoint is the @@any endpoint
22    pub fn builtin(address: [u8; 5]) -> Self {
23        let temp_self_owned_address = SelfOwnedPointerAddress::new(address);
24        let any_endpoint = Endpoint::ANY;
25        Self::for_endpoint(&any_endpoint, &temp_self_owned_address)
26    }
27
28    /// A built-in pointer address used for internal DATEX runtime pointers.
29    /// The origin endpoint is the @@any endpoint
30    pub fn builtin_u32(address: u32) -> Self {
31        let address_bytes = address.to_le_bytes();
32        let mut address_array = [0u8; 5];
33        address_array[..4].copy_from_slice(&address_bytes);
34        address_array[4] = 255; // Remaining byte set to 255 (TODO)
35        Self::builtin(address_array)
36    }
37
38    /// Returns a [RemotePointerAddress] for the given endpoint and self-owned pointer address.
39    pub fn for_endpoint(
40        endpoint: &Endpoint,
41        self_owned_pointer_address: &SelfOwnedPointerAddress,
42    ) -> Self {
43        let endpoint_slice = endpoint.to_slice();
44        let mut address = [0u8; 26];
45        address[..endpoint_slice.len()].copy_from_slice(&endpoint_slice);
46        address[endpoint_slice.len()
47            ..endpoint_slice.len() + self_owned_pointer_address.0.len()]
48            .copy_from_slice(&self_owned_pointer_address.0);
49        RemotePointerAddress(address)
50    }
51
52    pub fn to_address_string(&self) -> String {
53        hex::encode(self.0)
54    }
55
56    /// Returns the endpoint part of the remote pointer address
57    pub fn endpoint(&self) -> Endpoint {
58        let mut endpoint = [0u8; 21];
59        endpoint.copy_from_slice(&self.0[0..21]);
60        Endpoint::from_slice(endpoint).unwrap()
61    }
62
63    /// Returns true if the remote pointer address is a builtin address (origin endpoint is @@any)
64    pub fn is_builtin(&self) -> bool {
65        self.endpoint() == Endpoint::ANY
66    }
67
68    /// Normalizes the pointer address to a self-owned address if it is a
69    /// remote address with the same endpoint as the provided local endpoint.
70    pub fn normalize_for_local(
71        &self,
72        local_endpoint: &Endpoint,
73    ) -> PointerAddress {
74        if self.endpoint().is_local_or_equals_endpoint(local_endpoint) {
75            let mut id = [0u8; 5];
76            id.copy_from_slice(&self.0[21..26]);
77            PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(id))
78        } else {
79            PointerAddress::Remote(self.clone())
80        }
81    }
82}
83
84impl Display for RemotePointerAddress {
85    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
86        core::write!(f, "${}", self.to_address_string())
87    }
88}
89
90const HASH_SEED: u32 = 0;
91
92impl SelfOwnedPointerAddress {
93    pub fn new(address: [u8; 5]) -> Self {
94        SelfOwnedPointerAddress(address)
95    }
96
97    /// # Safety
98    /// Calling this function multiple times with the same name is not allowed.
99    /// Hash collisions might also occur for different names (TODO)
100    pub unsafe fn new_static_from_name(name: &str) -> Self {
101        let hash = twox_hash::XxHash32::oneshot(HASH_SEED, name.as_bytes());
102        let hash_bytes = hash.to_le_bytes();
103        SelfOwnedPointerAddress([
104            hash_bytes[0],
105            hash_bytes[1],
106            hash_bytes[2],
107            hash_bytes[3],
108            255,
109        ])
110    }
111
112    pub fn to_address_string(&self) -> String {
113        hex::encode(self.0)
114    }
115
116    /// Returns a [RemotePointerAddress] for the given endpoint and his self-owned pointer address.
117    pub fn remote_for_endpoint(
118        &self,
119        endpoint: &Endpoint,
120    ) -> RemotePointerAddress {
121        RemotePointerAddress::for_endpoint(endpoint, self)
122    }
123}
124
125impl TryFrom<String> for SelfOwnedPointerAddress {
126    type Error = &'static str;
127    fn try_from(s: String) -> Result<Self, Self::Error> {
128        let hex_str = if let Some(stripped) = s.strip_prefix('$') {
129            stripped
130        } else {
131            &s
132        };
133
134        hex::decode(hex_str)
135            .map_err(|_| "Invalid hex string for SelfOwnedPointerAddress")
136            .and_then(|bytes| {
137                if bytes.len() == 5 {
138                    let mut arr = [0u8; 5];
139                    arr.copy_from_slice(&bytes);
140                    Ok(SelfOwnedPointerAddress::new(arr))
141                } else {
142                    Err("SelfOwnedPointerAddress must be 5 bytes long")
143                }
144            })
145    }
146}
147
148impl Display for SelfOwnedPointerAddress {
149    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
150        core::write!(f, "${}", self.to_address_string())
151    }
152}
153
154#[derive(BinWrite, BinRead, Debug, Clone, PartialEq, Eq, Hash)]
155#[brw(little)]
156pub enum PointerAddress {
157    // pointer with the local endpoint as origin
158    // the full pointer id consists of the local endpoint id + this local id
159    #[brw(magic = 0u8)]
160    SelfOwned(SelfOwnedPointerAddress),
161    #[brw(magic = 1u8)]
162    // pointer with a remote endpoint as origin, contains the full pointers address
163    Remote(RemotePointerAddress),
164}
165
166impl PointerAddress {
167    pub fn self_owned(address: [u8; 5]) -> Self {
168        PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(address))
169    }
170
171    pub fn remote(address: [u8; 26]) -> Self {
172        PointerAddress::Remote(RemotePointerAddress(address))
173    }
174
175    /// Normalizes the pointer address to a self-owned address if it is a
176    /// remote address with the same endpoint as the provided local endpoint.
177    pub fn normalize_for_local(self, local_endpoint: &Endpoint) -> Self {
178        match self {
179            PointerAddress::Remote(remote_address) => {
180                remote_address.normalize_for_local(local_endpoint)
181            }
182            _ => self,
183        }
184    }
185
186    /// Returns the endpoint part of the remote pointer address
187    /// or @@local for self owned pointer addresses
188    pub fn endpoint(&self) -> Endpoint {
189        match self {
190            PointerAddress::SelfOwned(_) => Endpoint::LOCAL,
191            PointerAddress::Remote(remote_address) => remote_address.endpoint(),
192        }
193    }
194}
195
196impl TryFrom<String> for PointerAddress {
197    type Error = String;
198    fn try_from(s: String) -> Result<Self, Self::Error> {
199        PointerAddress::try_from(s.as_str())
200    }
201}
202impl TryFrom<&str> for PointerAddress {
203    type Error = String;
204    fn try_from(s: &str) -> Result<Self, Self::Error> {
205        let hex_str = if let Some(stripped) = s.strip_prefix('$') {
206            stripped
207        } else {
208            s
209        };
210
211        let bytes = hex::decode(hex_str)
212            .map_err(|_| format!("Invalid hex string: {s}"))?;
213        match bytes.len() {
214            5 => {
215                let mut arr = [0u8; 5];
216                arr.copy_from_slice(&bytes);
217                Ok(PointerAddress::SelfOwned(SelfOwnedPointerAddress::new(arr)))
218            }
219            26 => {
220                let mut arr = [0u8; 26];
221                arr.copy_from_slice(&bytes);
222                Ok(PointerAddress::Remote(RemotePointerAddress(arr)))
223            }
224            _ => Err("PointerAddress must be 5 or 26 bytes long".to_string()),
225        }
226    }
227}
228
229impl From<SelfOwnedPointerAddress> for PointerAddress {
230    fn from(owned: SelfOwnedPointerAddress) -> Self {
231        PointerAddress::SelfOwned(owned)
232    }
233}
234
235impl From<RemotePointerAddress> for PointerAddress {
236    fn from(remote: RemotePointerAddress) -> Self {
237        PointerAddress::Remote(remote)
238    }
239}
240
241impl PointerAddress {
242    pub fn to_address_string(&self) -> String {
243        match self {
244            PointerAddress::SelfOwned(local_address) => {
245                local_address.to_address_string()
246            }
247            PointerAddress::Remote(address) => address.to_address_string(),
248        }
249    }
250}
251
252impl Display for PointerAddress {
253    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
254        match self {
255            PointerAddress::SelfOwned(local_address) => {
256                core::write!(f, "{}", local_address)
257            }
258            PointerAddress::Remote(address) => {
259                core::write!(f, "{}", address)
260            }
261        }
262    }
263}
264impl Serialize for PointerAddress {
265    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
266    where
267        S: serde::Serializer,
268    {
269        let addr_str = self.to_address_string();
270        serializer.serialize_str(&addr_str)
271    }
272}
273impl<'de> Deserialize<'de> for PointerAddress {
274    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275    where
276        D: serde::Deserializer<'de>,
277    {
278        let s = String::deserialize(deserializer)?;
279        PointerAddress::try_from(s.as_str()).map_err(|e| {
280            serde::de::Error::custom(format!(
281                "Failed to parse PointerAddress: {}",
282                e
283            ))
284        })
285    }
286}
287
288impl PointerAddress {
289    pub fn bytes(&self) -> &[u8] {
290        match self {
291            PointerAddress::SelfOwned(local_address) => &local_address.0,
292            PointerAddress::Remote(addr) => &addr.0,
293        }
294    }
295}