diff --git a/src/res.rs b/src/res.rs index 51f63c40f..a53f36734 100644 --- a/src/res.rs +++ b/src/res.rs @@ -208,7 +208,9 @@ impl Resources { /// let mut res = Resources::new(); /// res.add(MyRes(5)); /// ``` - pub fn add(&mut self, r: R) where R: Resource { + pub fn add(&mut self, r: R) + where R: Resource + { self.add_with_id(r, 0) } @@ -293,3 +295,95 @@ impl Resources { .expect("No resource with the given id") } } + +#[cfg(test)] +mod tests { + use super::*; + + struct Res; + + #[test] + fn res_id() { + assert_eq!(ResourceId::new::(), ResourceId::new_with_id::(0)); + assert_eq!(ResourceId::new_with_id::(5), + ResourceId(TypeId::of::(), 5)); + } + + #[test] + fn fetch_aspects() { + assert_eq!(unsafe { Fetch::::reads(4) }, + vec![ResourceId::new_with_id::(4)]); + assert_eq!(unsafe { Fetch::::writes(8) }, vec![]); + + let mut res = Resources::new(); + res.add_with_id(Res, 56); + Fetch::::fetch(&res, 56); + } + + #[test] + fn fetch_mut_aspects() { + assert_eq!(unsafe { FetchMut::::reads(4) }, vec![]); + assert_eq!(unsafe { FetchMut::::writes(8) }, + vec![ResourceId::new_with_id::(8)]); + + let mut res = Resources::new(); + res.add_with_id(Res, 56); + FetchMut::::fetch(&res, 56); + } + + #[test] + fn add() { + let mut res = Resources::new(); + res.add(Res); + + assert!(res.has_value(ResourceId::new::())); + assert!(!res.has_value(ResourceId::new_with_id::(1))); + assert!(!res.has_value(ResourceId::new_with_id::(1))); + } + + #[allow(unused)] + #[test] + #[should_panic(expected = "Already borrowed")] + fn read_write_fails() { + + let mut res = Resources::new(); + res.add(Res); + + let read = res.fetch::(0); + let write = res.fetch_mut::(0); + } + + #[allow(unused)] + #[test] + #[should_panic(expected = "Already borrowed mutably")] + fn write_read_fails() { + + let mut res = Resources::new(); + res.add(Res); + + let write = res.fetch_mut::(0); + let read = res.fetch::(0); + } + + #[test] + fn fetch_uses_id() { + let mut res = Resources::new(); + res.add_with_id(5i32, 1); + res.add_with_id(50i32, 2); + + { + assert_eq!(*res.fetch::(1), 5); + assert_eq!(*res.fetch::(2), 50); + } + + { + *res.fetch_mut::(1) *= 2; + *res.fetch_mut::(2) *= 2; + } + + { + assert_eq!(*res.fetch::(1), 10); + assert_eq!(*res.fetch::(2), 100); + } + } +}