acme_core/id/kinds/
atomic.rs

1/*
2    Appellation: atomic <mod>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5//! # Atomic Id
6//!
7//!
8use crate::id::Identifier;
9#[cfg(feature = "serde")]
10use serde::{Deserialize, Serialize};
11use std::ops::{Deref, DerefMut};
12use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
13
14#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15#[cfg_attr(feature = "serde", derive(Deserialize, Serialize,))]
16#[repr(C)]
17pub struct AtomicId(usize);
18
19impl AtomicId {
20    pub fn new() -> Self {
21        static COUNTER: AtomicUsize = AtomicUsize::new(1);
22        Self(COUNTER.fetch_add(1, Relaxed))
23    }
24
25    pub fn next(&self) -> Self {
26        Self::new()
27    }
28
29    pub fn set(&mut self, id: usize) {
30        self.0 = id;
31    }
32
33    pub const fn get(&self) -> usize {
34        self.0
35    }
36
37    pub fn into_inner(self) -> usize {
38        self.0
39    }
40}
41
42impl AsRef<usize> for AtomicId {
43    fn as_ref(&self) -> &usize {
44        &self.0
45    }
46}
47
48impl AsMut<usize> for AtomicId {
49    fn as_mut(&mut self) -> &mut usize {
50        &mut self.0
51    }
52}
53
54impl Default for AtomicId {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl Deref for AtomicId {
61    type Target = usize;
62
63    fn deref(&self) -> &Self::Target {
64        &self.0
65    }
66}
67
68impl DerefMut for AtomicId {
69    fn deref_mut(&mut self) -> &mut Self::Target {
70        &mut self.0
71    }
72}
73
74impl Identifier for AtomicId {}
75
76impl core::fmt::Display for AtomicId {
77    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
78        write!(f, "{}", self.0)
79    }
80}
81
82impl From<usize> for AtomicId {
83    fn from(id: usize) -> Self {
84        Self(id)
85    }
86}
87
88impl From<AtomicId> for usize {
89    fn from(id: AtomicId) -> Self {
90        id.0
91    }
92}