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