Skip to main content

datex_core/runtime/
pointer_address_provider.rs

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