1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! An implementation of [dependency injection].
//!
//! If you do not know what is dependency injection (DI), please read [this
//! discussion on StackOverflow], then come back. The only difference is that in
//! `dptree`, we inject objects into function-handlers, not into objects.
//!
//! Currently, the only container is [`DependencyMap`]. It implements the DI
//! pattern completely, but be careful: it can panic when you do not provide
//! necessary types. See more in its documentation.
//!
//! [dependency injection]: https://en.wikipedia.org/wiki/Dependency_injection
//! [this discussion on StackOverflow]: https://stackoverflow.com/questions/130794/what-is-dependency-injection
use futures::future::{ready, BoxFuture};

use std::{
    any::{Any, TypeId},
    collections::HashMap,
    fmt::{Debug, Formatter, Write},
    future::Future,
    ops::Deref,
    sync::Arc,
};

/// A DI container from which we can extract a value of a given type.
///
/// There are two possible ways to handle the situation when your container
/// cannot return a value of specified type:
///
/// 1. Do not implement [`DependencySupplier`] for the type. It often requires
/// some type-level manipulations.
/// 2. Runtime panic. Be careful in this case: check whether you add your type
/// to the container.
///
/// A concrete solution is left to a particular implementation.
pub trait DependencySupplier<Value> {
    /// Get the value.
    ///
    /// We assume that all values are stored in `Arc<_>`.
    fn get(&self) -> Arc<Value>;
}

/// A DI container with multiple dependencies.
///
/// This DI container stores types by their corresponding type identifiers. It
/// cannot prove at compile-time that a type of a requested value exists within
/// the container, so if you do not provide necessary types but they were
/// requested, it will panic.
///
/// # Examples
///
/// ```
/// # use std::sync::Arc;
/// use dptree::di::{DependencyMap, DependencySupplier};
///
/// let mut container = DependencyMap::new();
/// container.insert(5_i32);
/// container.insert("abc");
///
/// assert_eq!(container.get(), Arc::new(5_i32));
/// assert_eq!(container.get(), Arc::new("abc"));
///
/// // If a type of a value already exists within the container, it will be replaced.
/// let old_value = container.insert(10_i32).unwrap();
///
/// assert_eq!(old_value, Arc::new(5_i32));
/// assert_eq!(container.get(), Arc::new(10_i32));
/// ```
///
/// When a value is not found within the container, it will panic:
///
/// ```should_panic
/// # use std::sync::Arc;
/// use dptree::di::{DependencyMap, DependencySupplier};
/// let mut container = DependencyMap::new();
/// container.insert(10i32);
/// container.insert(true);
/// container.insert("static str");
///
/// // thread 'main' panicked at 'alloc::string::String was requested, but not provided. Available types:
/// //    &str
/// //    bool
/// //    i32
/// // ', /media/hirrolot/772CF8924BEBB279/Documents/Rust/dptree/src/di.rs:150:17
/// // note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
/// let string: Arc<String> = container.get();
/// ```
#[derive(Default, Clone)]
pub struct DependencyMap {
    map: HashMap<TypeId, Dependency>,
}

#[derive(Clone)]
struct Dependency {
    type_name: &'static str,
    inner: Arc<dyn Any + Send + Sync>,
}

impl PartialEq for DependencyMap {
    fn eq(&self, other: &Self) -> bool {
        let keys1 = self.map.keys();
        let keys2 = other.map.keys();
        keys1.zip(keys2).map(|(k1, k2)| k1 == k2).all(|x| x)
    }
}

impl DependencyMap {
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a value into the container.
    ///
    /// If the container do not has this type present, `None` is returned.
    /// Otherwise, the value is updated, and the old value is returned.
    pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {
        self.map
            .insert(
                TypeId::of::<T>(),
                Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },
            )
            .map(|dep| dep.inner.downcast().expect("Values are stored by TypeId"))
    }

    /// Inserts all dependencies from another container into itself.
    pub fn insert_container(&mut self, container: Self) {
        self.map.extend(container.map);
    }

    /// Removes a value from the container.
    ///
    /// If the container do not has this type present, `None` is returned.
    /// Otherwise, the value is removed and returned.
    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
        self.map
            .remove(&TypeId::of::<T>())
            .map(|dep| dep.inner.downcast().expect("Values are stored by TypeId"))
    }

    fn available_types(&self) -> String {
        let mut list = String::new();

        for dep in self.map.values() {
            writeln!(list, "    {}", dep.type_name).unwrap();
        }

        list
    }
}

impl Debug for DependencyMap {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("DependencyMap").finish()
    }
}

impl<V> DependencySupplier<V> for DependencyMap
where
    V: Send + Sync + 'static,
{
    fn get(&self) -> Arc<V> {
        self.map
            .get(&TypeId::of::<V>())
            .unwrap_or_else(|| {
                panic!(
                    "{} was requested, but not provided. Available types:\n{}",
                    std::any::type_name::<V>(),
                    self.available_types()
                )
            })
            .clone()
            .inner
            .downcast::<V>()
            .expect("Checked by .unwrap_or_else()")
    }
}

impl<V, S> DependencySupplier<V> for Arc<S>
where
    S: DependencySupplier<V>,
{
    fn get(&self) -> Arc<V> {
        self.deref().get()
    }
}

/// Converts functions into [`CompiledFn`].
///
/// The function must follow some rules, to be usable with DI:
///
/// 1. For each function parameter of type `T`, `Input` must satisfy
/// `DependencySupplier<T>`.
/// 2. The function must be of 0-9 arguments.
/// 3. The function must return [`Future`].
pub trait Injectable<Input, Output, FnArgs> {
    fn inject<'a>(&'a self, container: &'a Input) -> CompiledFn<'a, Output>;
}

/// A function with all dependencies satisfied.
pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;

/// Turns a synchronous function into a type that implements [`Injectable`].
pub struct Asyncify<F>(pub F);

macro_rules! impl_into_di {
    ($($generic:ident),*) => {
        impl<Func, Input, Output, Fut, $($generic),*> Injectable<Input, Output, ($($generic,)*)> for Func
        where
            Input: $(DependencySupplier<$generic> +)*,
            Input: Send + Sync,
            Func: Fn($($generic),*) -> Fut + Send + Sync + 'static,
            Fut: Future<Output = Output> + Send + 'static,
            $($generic: Clone + Send + Sync),*
        {
            #[allow(non_snake_case)]
            #[allow(unused_variables)]
            fn inject<'a>(&'a self, container: &'a Input) -> CompiledFn<'a, Output> {
                Arc::new(move || {
                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
                    let fut = self( $( $generic ),* );
                    Box::pin(fut)
                })
            }
        }

        impl<Func, Input, Output, $($generic),*> Injectable<Input, Output, ($($generic,)*)> for Asyncify<Func>
        where
            Input: $(DependencySupplier<$generic> +)*,
            Input: Send + Sync,
            Func: Fn($($generic),*) -> Output + Send + Sync + 'static,
            Output: Send + 'static,
            $($generic: Clone + Send + Sync),*
        {
            #[allow(non_snake_case)]
            #[allow(unused_variables)]
            fn inject<'a>(&'a self, container: &'a Input) -> CompiledFn<'a, Output> {
                let Asyncify(this) = self;
                Arc::new(move || {
                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
                    let out = this( $( $generic ),* );
                    Box::pin(ready(out))
                })
            }
        }
    };
}

impl_into_di!();
impl_into_di!(A);
impl_into_di!(A, B);
impl_into_di!(A, B, C);
impl_into_di!(A, B, C, D);
impl_into_di!(A, B, C, D, E);
impl_into_di!(A, B, C, D, E, F);
impl_into_di!(A, B, C, D, E, F, G);
impl_into_di!(A, B, C, D, E, F, G, H);
impl_into_di!(A, B, C, D, E, F, G, H, I);

/// Constructs [`DependencyMap`] with a list of dependencies.
///
/// # Examples
///
/// ```
/// use dptree::di::{DependencyMap, DependencySupplier};
///
/// let map = dptree::deps![123, "abc", true];
///
/// let i: i32 = *map.get();
/// let str: &str = *map.get();
/// let b: bool = *map.get();
///
/// assert!(i == 123);
/// assert!(str == "abc");
/// assert!(b == true);
/// ```
#[macro_export]
macro_rules! deps {
    ($($dep:expr),*) => {
        {
            // In the case if this macro receives zero arguments.
            #[allow(unused_mut)]
            let mut map = $crate::di::DependencyMap::new();
            $(map.insert($dep);)*
            map
        }
    }
}

/// Insert some value to a container.
pub trait Insert<Value> {
    /// Inserts `value` into itself, returning the previous value, if exists.
    fn insert(&mut self, value: Value) -> Option<Arc<Value>>;
}

impl<T: Send + Sync + 'static> Insert<T> for DependencyMap {
    fn insert(&mut self, value: T) -> Option<Arc<T>> {
        DependencyMap::insert(self, value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get() {
        let mut map = DependencyMap::new();
        map.insert(42i32);
        map.insert("hello world");
        map.insert_container(deps![true]);

        assert_eq!(map.get(), Arc::new(42i32));
        assert_eq!(map.get(), Arc::new("hello world"));
        assert_eq!(map.get(), Arc::new(true));
    }
}