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)]
78pub struct DependencyMap {
79 pub(crate) map: BTreeMap<TypeId, Dependency>,
80}
81
82#[derive(Clone)]
83pub(crate) struct Dependency {
84 pub(crate) type_name: &'static str,
85 inner: Arc<dyn Any + Send + Sync>,
86}
87
88impl Debug for Dependency {
89 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("Dependency").field("type_name", &self.type_name).finish_non_exhaustive()
91 }
92}
93
94impl PartialEq for DependencyMap {
95 fn eq(&self, other: &Self) -> bool {
96 let keys1 = self.map.keys();
97 let keys2 = other.map.keys();
98 keys1.len() == keys2.len() && keys1.zip(keys2).all(|(k1, k2)| k1 == k2)
99 }
100}
101
102impl DependencyMap {
103 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {
112 self.map
113 .insert(
114 TypeId::of::<T>(),
115 Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },
116 )
117 .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
118 }
119
120 pub fn insert_container(&mut self, container: Self) {
122 self.map.extend(container.map);
123 }
124
125 pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
130 self.map
131 .remove(&TypeId::of::<T>())
132 .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
133 }
134
135 pub fn get<V>(&self) -> Arc<V>
141 where
142 V: Send + Sync + 'static,
143 {
144 self.map
145 .get(&TypeId::of::<V>())
146 .unwrap_or_else(|| {
147 panic!(
148 "`{}` was requested, but not provided. Available types:\n{}",
149 std::any::type_name::<V>(),
150 self.available_types()
151 )
152 })
153 .clone()
154 .inner
155 .downcast::<V>()
156 .expect("Checked by `unwrap_or_else`")
157 }
158
159 pub fn try_get<V: Send + Sync + 'static>(&self) -> Option<Arc<V>> {
161 self.map
162 .get(&TypeId::of::<V>())
163 .cloned()
164 .map(|v| v.inner.downcast().expect("Values are stored by `TypeId`"))
165 }
166
167 fn available_types(&self) -> String {
168 let mut list = String::new();
169
170 for dep in self.map.values() {
171 writeln!(list, " `{}`", dep.type_name).unwrap();
172 }
173
174 list
175 }
176}
177
178pub trait Injectable<Output, FnArgs>
183where
184 Output: 'static,
185{
186 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output>;
187
188 fn input_types() -> BTreeSet<Type>;
191
192 #[track_caller]
199 fn obligations() -> BTreeMap<Type, &'static Location<'static>> {
200 let location = Location::caller();
201 Self::input_types().into_iter().map(|ty| (ty, location)).collect()
202 }
203}
204
205#[cfg(not(target_arch = "wasm32"))]
207pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;
208#[cfg(target_arch = "wasm32")]
209pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + 'a>;
210
211pub struct Asyncify<F>(pub F);
213
214macro_rules! impl_into_di {
215 ($($generic:ident),*) => {
216 impl<Func, Output, Fut, $($generic),*> Injectable<Output, ($($generic,)*)> for Func
217 where
218 Func: Fn($($generic),*) -> Fut + MaybeSend + MaybeSync + 'static,
219 Fut: Future<Output = Output> + MaybeSend + 'static,
220 Output: 'static,
221 $($generic: Clone + Send + Sync + 'static),*
222 {
223 #[allow(non_snake_case)]
224 #[allow(unused_variables)]
225 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
226 Arc::new(move || {
227 $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
228 let fut = self( $( $generic ),* );
229 Box::pin(fut)
230 })
231 }
232
233 fn input_types() -> BTreeSet<Type> {
234 BTreeSet::from_iter(vec![
235 $(Type::of::<$generic>()),*
236 ])
237 }
238 }
239
240 impl<Func, Output, $($generic),*> Injectable<Output, ($($generic,)*)> for Asyncify<Func>
241 where
242 Func: Fn($($generic),*) -> Output + MaybeSend + MaybeSync + 'static,
243 Output: MaybeSend + 'static,
244 $($generic: Clone + Send + Sync + 'static),*
245 {
246 #[allow(non_snake_case)]
247 #[allow(unused_variables)]
248 fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
249 let Asyncify(this) = self;
250 Arc::new(move || {
251 $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
252 let out = this( $( $generic ),* );
253 Box::pin(ready(out))
254 })
255 }
256
257 fn input_types() -> BTreeSet<Type> {
258 BTreeSet::from_iter(vec![
259 $(Type::of::<$generic>()),*
260 ])
261 }
262 }
263 };
264}
265
266impl_into_di!();
267impl_into_di!(T1);
268impl_into_di!(T1, T2);
269impl_into_di!(T1, T2, T3);
270impl_into_di!(T1, T2, T3, T4);
271impl_into_di!(T1, T2, T3, T4, T5);
272impl_into_di!(T1, T2, T3, T4, T5, T6);
273impl_into_di!(T1, T2, T3, T4, T5, T6, T7);
274impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8);
275impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
276impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
277impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
278impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
279
280#[macro_export]
298macro_rules! deps {
299 ($($dep:expr),* $(,)?) => {
300 {
301 #[allow(unused_mut)]
303 let mut map = $crate::di::DependencyMap::new();
304 $(map.insert($dep);)*
305 map
306 }
307 }
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 crate::cross_test! {
315 fn get() {
316 let mut map = DependencyMap::new();
317 map.insert(42i32);
318 map.insert("hello world");
319 map.insert_container(deps![true]);
320
321 assert_eq!(map.get(), Arc::new(42i32));
322 assert_eq!(map.get(), Arc::new("hello world"));
323 assert_eq!(map.get(), Arc::new(true));
324 }
325
326 fn try_get() {
327 let mut map = DependencyMap::new();
328 assert_eq!(map.try_get::<i32>(), None);
329 map.insert(42i32);
330 assert_eq!(map.try_get(), Some(Arc::new(42i32)));
331 assert_eq!(map.try_get::<f32>(), None);
332 }
333
334 fn same_keys() {
335 let mut map_bool1 = DependencyMap::new();
336 let mut map_bool2 = DependencyMap::new();
337 let map_empty = DependencyMap::new();
338
339 map_bool1.insert(false);
340 map_bool2.insert(true);
341
342 assert_eq!(map_bool1, map_bool2);
343 assert_ne!(map_bool1, map_empty);
344 assert_ne!(map_bool2, map_empty);
345 }
346 }
347}