|
| 1 | +use std::any::{Any, TypeId}; |
| 2 | +use std::collections::HashMap; |
| 3 | +use std::sync::Arc; |
| 4 | + |
1 | 5 | /// Pipeline execution context.
|
2 |
| -#[derive(Clone, Debug, Default)] |
| 6 | +#[derive(Clone, Debug)] |
3 | 7 | pub struct Context {
|
4 |
| - _priv: (), |
| 8 | + type_map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>, |
| 9 | +} |
| 10 | + |
| 11 | +impl Default for Context { |
| 12 | + fn default() -> Self { |
| 13 | + Self::new() |
| 14 | + } |
5 | 15 | }
|
6 | 16 |
|
7 | 17 | impl Context {
|
| 18 | + /// Creates a new, empty Context. |
8 | 19 | pub fn new() -> Self {
|
9 |
| - Self::default() |
| 20 | + Self { |
| 21 | + type_map: HashMap::new(), |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + /// Inserts or replaces an entity in the type map. If an entity with the same type was displaced |
| 26 | + /// by the insert, it will be returned to the caller. |
| 27 | + pub fn insert_or_replace<E>(&mut self, entity: E) -> Option<Arc<E>> |
| 28 | + where |
| 29 | + E: Send + Sync + 'static, |
| 30 | + { |
| 31 | + // we make sure that for every TypeId of E as key we ALWAYS retrieve an Option<Arc<E>>. That's why |
| 32 | + // the `unwrap` below is safe. |
| 33 | + self.type_map |
| 34 | + .insert(TypeId::of::<E>(), Arc::new(entity)) |
| 35 | + .map(|displaced| displaced.downcast().unwrap()) |
| 36 | + } |
| 37 | + |
| 38 | + /// Inserts an entity in the type map. If the an entity with the same type signature is |
| 39 | + /// already present it will be silently dropped. This function returns a mutable reference to |
| 40 | + /// the same Context so it can be chained to itself. |
| 41 | + pub fn insert<E>(&mut self, entity: E) -> &mut Self |
| 42 | + where |
| 43 | + E: Send + Sync + 'static, |
| 44 | + { |
| 45 | + self.type_map.insert(TypeId::of::<E>(), Arc::new(entity)); |
| 46 | + |
| 47 | + self |
| 48 | + } |
| 49 | + |
| 50 | + /// Removes an entity from the type map. If present, the entity will be returned. |
| 51 | + pub fn remove<E>(&mut self) -> Option<Arc<E>> |
| 52 | + where |
| 53 | + E: Send + Sync + 'static, |
| 54 | + { |
| 55 | + self.type_map |
| 56 | + .remove(&TypeId::of::<E>()) |
| 57 | + .map(|removed| removed.downcast().unwrap()) |
| 58 | + } |
| 59 | + |
| 60 | + /// Returns a reference of the entity of the specified type signature, if it exists. |
| 61 | + /// |
| 62 | + /// If there is no entity with the specific type signature, `None` is returned instead. |
| 63 | + pub fn get<E>(&self) -> Option<&E> |
| 64 | + where |
| 65 | + E: Send + Sync + 'static, |
| 66 | + { |
| 67 | + self.type_map |
| 68 | + .get(&TypeId::of::<E>()) |
| 69 | + .map(|item| item.downcast_ref()) |
| 70 | + .flatten() |
| 71 | + } |
| 72 | + |
| 73 | + /// Returns the number of entities in the type map. |
| 74 | + pub fn len(&self) -> usize { |
| 75 | + self.type_map.len() |
| 76 | + } |
| 77 | + |
| 78 | + /// Returns `true` if the type map is empty, `false` otherwise. |
| 79 | + pub fn is_empty(&self) -> bool { |
| 80 | + self.type_map.is_empty() |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + use std::sync::Mutex; |
| 88 | + |
| 89 | + #[test] |
| 90 | + fn insert_get_string() { |
| 91 | + let mut context = Context::new(); |
| 92 | + context.insert_or_replace("pollo".to_string()); |
| 93 | + assert_eq!(Some(&"pollo".to_string()), context.get()); |
| 94 | + } |
| 95 | + |
| 96 | + #[test] |
| 97 | + fn insert_get_custom_structs() { |
| 98 | + #[derive(Debug, PartialEq, Eq)] |
| 99 | + struct S1 {} |
| 100 | + #[derive(Debug, PartialEq, Eq)] |
| 101 | + struct S2 {} |
| 102 | + |
| 103 | + let mut context = Context::new(); |
| 104 | + context.insert_or_replace(S1 {}); |
| 105 | + context.insert_or_replace(S2 {}); |
| 106 | + |
| 107 | + assert_eq!(Some(Arc::new(S1 {})), context.insert_or_replace(S1 {})); |
| 108 | + assert_eq!(Some(Arc::new(S2 {})), context.insert_or_replace(S2 {})); |
| 109 | + |
| 110 | + assert_eq!(Some(&S1 {}), context.get()); |
| 111 | + assert_eq!(Some(&S2 {}), context.get()); |
| 112 | + } |
| 113 | + |
| 114 | + #[test] |
| 115 | + fn insert_fluent_syntax() { |
| 116 | + #[derive(Debug, PartialEq, Eq, Default)] |
| 117 | + struct S1 {} |
| 118 | + #[derive(Debug, PartialEq, Eq, Default)] |
| 119 | + struct S2 {} |
| 120 | + |
| 121 | + let mut context = Context::new(); |
| 122 | + |
| 123 | + context |
| 124 | + .insert("static str") |
| 125 | + .insert("a String".to_string()) |
| 126 | + .insert(S1::default()) |
| 127 | + .insert(S1::default()) // notice we are REPLACING S1. This call will *not* increment the counter |
| 128 | + .insert(S2::default()); |
| 129 | + |
| 130 | + assert_eq!(4, context.len()); |
| 131 | + assert_eq!(Some(&"static str"), context.get()); |
| 132 | + } |
| 133 | + |
| 134 | + fn require_send_sync<T: Send + Sync>(_: &T) {} |
| 135 | + |
| 136 | + #[test] |
| 137 | + fn test_require_send_sync() { |
| 138 | + // this won't compile if Context as a whole is not Send + Sync |
| 139 | + require_send_sync(&Context::new()) |
| 140 | + } |
| 141 | + |
| 142 | + #[test] |
| 143 | + fn mutability() { |
| 144 | + #[derive(Debug, PartialEq, Eq, Default)] |
| 145 | + struct S1 { |
| 146 | + num: u8, |
| 147 | + } |
| 148 | + let mut context = Context::new(); |
| 149 | + context.insert_or_replace(Mutex::new(S1::default())); |
| 150 | + |
| 151 | + // the stored value is 0. |
| 152 | + assert_eq!(0, context.get::<Mutex<S1>>().unwrap().lock().unwrap().num); |
| 153 | + |
| 154 | + // we change the number to 42 in a thread safe manner. |
| 155 | + context.get::<Mutex<S1>>().unwrap().lock().unwrap().num = 42; |
| 156 | + |
| 157 | + // now the number is 42. |
| 158 | + assert_eq!(42, context.get::<Mutex<S1>>().unwrap().lock().unwrap().num); |
| 159 | + |
| 160 | + // we replace the struct with a new one. |
| 161 | + let displaced = context |
| 162 | + .insert_or_replace(Mutex::new(S1::default())) |
| 163 | + .unwrap(); |
| 164 | + |
| 165 | + // the displaced struct still holds 42 as number |
| 166 | + assert_eq!(42, displaced.lock().unwrap().num); |
| 167 | + |
| 168 | + // the new struct has 0 has number. |
| 169 | + assert_eq!(0, context.get::<Mutex<S1>>().unwrap().lock().unwrap().num); |
| 170 | + |
| 171 | + context.insert_or_replace(Mutex::new(33u32)); |
| 172 | + *context.get::<Mutex<u32>>().unwrap().lock().unwrap() = 42; |
| 173 | + assert_eq!(42, *context.get::<Mutex<u32>>().unwrap().lock().unwrap()); |
10 | 174 | }
|
11 | 175 | }
|
0 commit comments