id_vec/
id.rs

1pub type Index = usize; // TODO make this a type parameter
2use ::vec::IdVec;
3
4/// Used as a key to access an instance inside a IdVec<T>.
5/// Internally, this is only an integer index (but with greater type safety).
6// manually implementing hash, clone, copy,
7pub 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    /// Convenience function which allows writing the index first, and the IdVec afterwards.
19    /// Example: `the_selected_entity.of(entities)`
20    /// Panics when calling on an invalid id
21    pub fn of<'s>(self, vec: &'s IdVec<T>) -> &'s T {
22        &vec[self]
23    }
24
25    /// Convenience function which allows writing the index first, and the IdVec afterwards.
26    /// Example: `the_selected_entity.of_mut(entities)`
27    /// Panics when calling on an invalid id
28    pub fn of_mut<'s>(self, vec: &'s mut IdVec<T>) -> &'s mut T {
29        &mut vec[self]
30    }
31
32    /// Convenience function which allows writing the index first, and the IdVec afterwards.
33    /// Example: `the_selected_entity.try_of(entities)`
34    pub fn try_of<'s>(self, vec: &'s IdVec<T>) -> Option<&'s T> {
35        vec.get(self)
36    }
37
38    /// Convenience function which allows writing the index first, and the IdVec afterwards.
39    /// Example: `the_selected_entity.try_of_mut(entities)`
40    pub fn try_of_mut<'s>(self, vec: &'s mut IdVec<T>) -> Option<&'s mut T> {
41        vec.get_mut(self)
42    }
43
44    /// The actual integer value for this Id.
45    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}