Skip to main content

datex_core/runtime/
pointer_address_provider.rs

1use crate::{
2    shared_values::{
3        PointerAddress, RemotePointerAddress, SelfOwnedPointerAddress,
4    },
5    values::core_values::endpoint::Endpoint,
6};
7
8#[derive(Default, Debug)]
9pub struct SelfOwnedPointerAddressProvider {
10    local_endpoint: Endpoint,
11    /// Counter for local pointer ids
12    local_counter: u64,
13    /// Last timestamp used for a new local pointer id
14    last_timestamp: u64,
15}
16
17impl SelfOwnedPointerAddressProvider {
18    /// Creates a new, [SelfOwnedPointerAddressProvider] instance
19    pub const fn new(endpoint: Endpoint) -> Self {
20        Self {
21            local_endpoint: endpoint,
22            local_counter: 0,
23            last_timestamp: 0,
24        }
25    }
26
27    /// Takes a [RemotePointerAddress] and converts it to a [PointerAddress::Local] or [PointerAddress::Remote],
28    /// depending on whether the pointer origin id matches the local endpoint.
29    pub fn normalize_address(
30        &self,
31        raw_address: RemotePointerAddress,
32    ) -> PointerAddress {
33        raw_address.normalize_for_local(&self.local_endpoint)
34    }
35
36    pub fn get_new_self_owned_address(&mut self) -> SelfOwnedPointerAddress {
37        let timestamp = crate::time::now_ms();
38        // new timestamp, reset counter
39        if timestamp != self.last_timestamp {
40            self.last_timestamp = timestamp;
41            self.local_counter = 0;
42        }
43        // same timestamp as last time, increment counter to prevent collision
44        else {
45            self.local_counter += 1;
46        }
47        self.local_counter += 1;
48
49        // create id: 4 bytes timestamp + 1 byte counter
50        let id: [u8; 5] = [
51            (timestamp >> 24) as u8,
52            (timestamp >> 16) as u8,
53            (timestamp >> 8) as u8,
54            timestamp as u8,
55            (self.local_counter & 0xFF) as u8,
56        ];
57
58        SelfOwnedPointerAddress::new(id)
59    }
60}