nitinol_core/
identifier.rs

1use std::fmt::{Debug, Display, Formatter};
2use std::hash::{Hash, Hasher};
3use std::sync::Arc;
4
5/// Low clone cost identifier that provides a common identification feature within Nitinol.
6/// 
7/// It is a wrapper around `Arc<str>`.
8/// 
9/// If Display is implemented, 
10/// [`ToEntityId::to_entity_id`] and [`IntoEntityId::into_entity_id`] are automatically derived.
11pub struct EntityId(Arc<str>);
12
13impl EntityId {
14    pub fn new(id: String) -> EntityId {
15        Self(id.into())
16    }
17}
18
19impl Clone for EntityId {
20    fn clone(&self) -> Self {
21        Self(Arc::clone(&self.0))
22    }
23}
24
25impl Debug for EntityId {
26    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
27        write!(f, "{}", self.0)
28    }
29}
30
31impl Display for EntityId {
32    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
33        write!(f, "{}", self.0)
34    }
35}
36
37impl AsRef<str> for EntityId {
38    fn as_ref(&self) -> &str {
39        &self.0
40    }
41}
42
43impl Eq for EntityId {}
44
45impl PartialEq<Self> for EntityId {
46    fn eq(&self, other: &Self) -> bool {
47        self.0.eq(&other.0)
48    }
49}
50
51impl Hash for EntityId {
52    fn hash<H: Hasher>(&self, state: &mut H) {
53        self.0.hash(state);
54    }
55}
56
57pub trait IntoEntityId: 'static + Sync + Send {
58    fn into_entity_id(self) -> EntityId;
59}
60
61pub trait ToEntityId: 'static + Sync + Send {
62    fn to_entity_id(&self) -> EntityId;
63}
64
65impl<T: ToString + Sync + Send + 'static> IntoEntityId for T {
66    fn into_entity_id(self) -> EntityId {
67        EntityId::new(self.to_string())
68    }
69}
70
71impl<T: ToString + Sync + Send + 'static + ?Sized> ToEntityId for T {
72    fn to_entity_id(&self) -> EntityId {
73        EntityId::new(self.to_string())
74    }
75}