scsys_core/id/impls/
impl_id_repr.rs

1/*
2    appellation: impl_id_repr <module>
3    authors: @FL03
4*/
5use crate::id::Id;
6
7use core::sync::atomic::{AtomicUsize, Ordering::Relaxed};
8#[cfg(feature = "uuid")]
9use uuid::Uuid;
10/// the static counter used for the [`Id<usize>`] representation
11static COUNTER: AtomicUsize = AtomicUsize::new(0);
12
13impl<T> Id<&T> {
14    /// returns a new identifier with a cloned inner value
15    pub fn cloned(&self) -> Id<T>
16    where
17        T: Clone,
18    {
19        Id(self.0.clone())
20    }
21    /// returns a new identifier with the inner value copied
22    pub fn copied(&self) -> Id<T>
23    where
24        T: Copy,
25    {
26        Id(*self.0)
27    }
28}
29
30impl<T> Id<&mut T> {
31    /// returns a new identifier with a cloned inner value
32    pub fn cloned(&self) -> Id<T>
33    where
34        T: Clone,
35    {
36        Id(self.0.clone())
37    }
38    /// returns a new identifier with the inner value copied
39    pub fn copied(&self) -> Id<T>
40    where
41        T: Copy,
42    {
43        Id(*self.0)
44    }
45}
46
47impl Id<usize> {
48    /// initializes a new identifie depending on the available features; more specifically,
49    /// whenever the `rand` feature is enabled, it will create a random identifier, otherwise
50    /// it will default to an atomic counter.
51    pub fn create() -> Self {
52        let value: usize;
53        #[cfg(feature = "rand")]
54        {
55            value = rand::random::<u128>() as usize;
56        }
57        #[cfg(not(feature = "rand"))]
58        {
59            value = COUNTER.fetch_add(1, Relaxed);
60        }
61        Id::new(value)
62    }
63    pub fn atomic() -> Self {
64        Self::new(COUNTER.fetch_add(1, Relaxed))
65    }
66    /// replaces the current id with the atomic-ally next value and returns the previous value.
67    /// see [`step`](Id::step) for more information
68    pub fn atomic_step(&mut self) -> usize {
69        self.replace(COUNTER.fetch_add(1, Relaxed))
70    }
71}
72
73#[cfg(feature = "uuid")]
74impl Id<Uuid> {
75    pub fn v3(namespace: &Uuid, name: &[u8]) -> Self {
76        let id = Uuid::new_v3(namespace, name);
77        Self::new(id)
78    }
79
80    #[cfg(all(feature = "rng", feature = "uuid"))]
81    pub fn v4() -> Self {
82        let id = Uuid::new_v4();
83        Self::new(id)
84    }
85}