1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
pub type Index = usize;
use ::vec::IdVec;
pub struct Id<T> {
index: Index,
_marker: ::std::marker::PhantomData<T>,
}
impl<T> Id<T> {
pub fn from_index(index: Index) -> Self {
Id { index, _marker: ::std::marker::PhantomData, }
}
pub fn of<'s>(self, vec: &'s IdVec<T>) -> &'s T {
&vec[self]
}
pub fn of_mut<'s>(self, vec: &'s mut IdVec<T>) -> &'s mut T {
&mut vec[self]
}
pub fn try_of<'s>(self, vec: &'s IdVec<T>) -> Option<&'s T> {
vec.get(self)
}
pub fn try_of_mut<'s>(self, vec: &'s mut IdVec<T>) -> Option<&'s mut T> {
vec.get_mut(self)
}
pub fn index_value(self) -> Index {
self.index
}
}
impl<T> Eq for Id<T> {}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Id<T>) -> bool {
self.index == other.index
}
}
impl<T> Copy for Id<T> {}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> ::std::hash::Hash for Id<T> {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
state.write_usize(self.index);
}
}
impl<T> ::std::fmt::Debug for Id<T> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
write!(f, "Id#{:?}", self.index)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn internal_index(){
for index in 0..32 {
let id : Id<f32> = Id::from_index(index);
let eq_id : Id<f32> = Id::from_index(index);
let non_eq_id : Id<f32> = Id::from_index(index + 1);
assert_eq!(id, eq_id);
assert_ne!(id, non_eq_id);
assert_eq!(id.index_value(), index);
}
}
}