1use futures::future::ready;
17
18use crate::send::{BoxFuture, MaybeSend, MaybeSync};
19
20use std::{
21 any::{Any, TypeId},
22 collections::{BTreeMap, BTreeSet},
23 fmt::{Debug, Formatter, Write},
24 future::Future,
25 iter::FromIterator,
26 panic::Location,
27 sync::Arc,
28};
29
30use crate::Type;
31
32#[derive(Default, Clone, Debug)]
97pub struct DependencyMap {
98 pub(crate) map: BTreeMap<TypeId, Dependency>,
99}
100
101#[derive(Clone)]
102pub(crate) struct Dependency {
103 pub(crate) type_name: &'static str,
104 inner: Arc<dyn Any + Send + Sync>,
105}
106
107impl Debug for Dependency {
108 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
109 f.debug_struct("Dependency").field("type_name", &self.type_name).finish_non_exhaustive()
110 }
111}
112
113impl PartialEq for DependencyMap {
114 fn eq(&self, other: &Self) -> bool {
115 let keys1 = self.map.keys();
116 let keys2 = other.map.keys();
117 keys1.len() == keys2.len() && keys1.zip(keys2).all(|(k1, k2)| k1 == k2)
118 }
119}
120
121impl DependencyMap {
122 pub fn new() -> Self {
123 Self::default()
124 }
125
126 pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {
131 self.map
132 .insert(
133 TypeId::of::<T>(),
134 Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },
135 )
136 .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
137 }
138
139 pub fn insert_container(&mut self, container: Self) {
141 self.map.extend(container.map);
142 }
143
144 pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
149 self.map
150 .remove(&TypeId::of::<T>())
151 .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
152 }
153
154 pub fn get<V>(&self) -> Arc<V>
160 where
161 V: Send + Sync + 'static,
162 {
163 self.map
164 .get(&TypeId::of::<V>())
165 .unwrap_or_else(|| {
166 panic!(
167 "`{}` was requested, but not provided. Available types:\n{}",
168 std::any::type_name::<V>(),
169 self.available_types()
170 )
171 })
172 .clone()
173 .inner
174 .downcast::<V>()
175 .expect("Checked by `unwrap_or_else`")
176 }
177
178 pub fn try_get<V: Send + Sync + 'static>(&self) -> Option<Arc<V>> {
180 self.map
181 .get(&TypeId::of::<V>())
182 .cloned()
183 .map(|v| v.inner.downcast().expect("Values are stored by `TypeId`"))
184 }
185
186 fn available_types(&self) -> String {
187 let mut list = String::new();
188
189 for dep in self.map.values() {
190 writeln!(list, " `{}`", dep.type_name).unwrap();
191 }
192
193 list
194 }
195}
196
197pub trait Injectable<Output, FnArgs>
202where
203 Output: 'static,
204{
205 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output>;
206
207 fn input_types() -> BTreeSet<Type>;
210
211 #[track_caller]
218 fn obligations() -> BTreeMap<Type, &'static Location<'static>> {
219 let location = Location::caller();
220 Self::input_types().into_iter().map(|ty| (ty, location)).collect()
221 }
222}
223
224#[cfg(not(target_arch = "wasm32"))]
226pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;
227#[cfg(target_arch = "wasm32")]
228pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + 'a>;
229
230pub struct Asyncify<F>(pub F);
232
233macro_rules! impl_into_di {
234 ($($generic:ident),*) => {
235 impl<Func, Output, Fut, $($generic),*> Injectable<Output, ($($generic,)*)> for Func
236 where
237 Func: Fn($($generic),*) -> Fut + MaybeSend + MaybeSync + 'static,
238 Fut: Future<Output = Output> + MaybeSend + 'static,
239 Output: 'static,
240 $($generic: Clone + Send + Sync + 'static),*
241 {
242 #[allow(non_snake_case)]
243 #[allow(unused_variables)]
244 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
245 Arc::new(move || {
246 $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
247 let fut = self( $( $generic ),* );
248 Box::pin(fut)
249 })
250 }
251
252 fn input_types() -> BTreeSet<Type> {
253 BTreeSet::from_iter(vec![
254 $(Type::of::<$generic>()),*
255 ])
256 }
257 }
258
259 impl<Func, Output, $($generic),*> Injectable<Output, ($($generic,)*)> for Asyncify<Func>
260 where
261 Func: Fn($($generic),*) -> Output + MaybeSend + MaybeSync + 'static,
262 Output: MaybeSend + 'static,
263 $($generic: Clone + Send + Sync + 'static),*
264 {
265 #[allow(non_snake_case)]
266 #[allow(unused_variables)]
267 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
268 let Asyncify(this) = self;
269 Arc::new(move || {
270 $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
271 let out = this( $( $generic ),* );
272 Box::pin(ready(out))
273 })
274 }
275
276 fn input_types() -> BTreeSet<Type> {
277 BTreeSet::from_iter(vec![
278 $(Type::of::<$generic>()),*
279 ])
280 }
281 }
282 };
283}
284
285impl_into_di!();
286impl_into_di!(T1);
287impl_into_di!(T1, T2);
288impl_into_di!(T1, T2, T3);
289impl_into_di!(T1, T2, T3, T4);
290impl_into_di!(T1, T2, T3, T4, T5);
291impl_into_di!(T1, T2, T3, T4, T5, T6);
292impl_into_di!(T1, T2, T3, T4, T5, T6, T7);
293impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8);
294impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
295impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
296impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
297impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
298
299#[macro_export]
317macro_rules! deps {
318 ($($dep:expr),* $(,)?) => {
319 {
320 #[allow(unused_mut)]
322 let mut map = $crate::di::DependencyMap::new();
323 $(map.insert($dep);)*
324 map
325 }
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 crate::cross_test! {
334 fn get() {
335 let mut map = DependencyMap::new();
336 map.insert(42i32);
337 map.insert("hello world");
338 map.insert_container(deps![true]);
339
340 assert_eq!(map.get(), Arc::new(42i32));
341 assert_eq!(map.get(), Arc::new("hello world"));
342 assert_eq!(map.get(), Arc::new(true));
343 }
344
345 fn try_get() {
346 let mut map = DependencyMap::new();
347 assert_eq!(map.try_get::<i32>(), None);
348 map.insert(42i32);
349 assert_eq!(map.try_get(), Some(Arc::new(42i32)));
350 assert_eq!(map.try_get::<f32>(), None);
351 }
352
353 fn same_keys() {
354 let mut map_bool1 = DependencyMap::new();
355 let mut map_bool2 = DependencyMap::new();
356 let map_empty = DependencyMap::new();
357
358 map_bool1.insert(false);
359 map_bool2.insert(true);
360
361 assert_eq!(map_bool1, map_bool2);
362 assert_ne!(map_bool1, map_empty);
363 assert_ne!(map_bool2, map_empty);
364 }
365 }
366}