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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use std::borrow::Borrow;
use std::cell::{Cell, OnceCell};
use std::ops::Deref;
use std::rc::Rc;

use super::{guard::Guard, refs::Ref};

/// A wrapper type for accessing dependencies
pub struct Dependency<T: 'static> {
    inner: OnceCell<Rc<T>>,
}

impl<T> Default for Dependency<T> {
    fn default() -> Self {
        let cell = OnceCell::new();

        if let Some(inner) = Guard::get() {
            cell.set(inner).ok();
        }

        Self { inner: cell }
    }
}

/// - The methods of `Dependency` are very similar to those of [`std::option::Option`], as
///   dependencies are *optionally* present.
/// - However, a `Dependency` on a type with a [`DependencyDefault`] also implements the
///   [`AsRef`], [`Deref`] and [`Borrow`] traits. Event if a value has not been explicitly
///   registered for it, the `Dependency` will still be able to [`as_ref`], [`deref`] and
///   [`borrow`] this default value.
///
///  [`std::option::Option`]: std::option
///  [`as_ref`]: Dependency::as_ref
///  [`deref`]: Dependency::deref
///  [`borrow`]: Dependency::borrow
impl<T> Dependency<T> {
    /// Creates a optional reference to the dependency of type `T`.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns `true` if the dependency is a [`Some`] value.
    #[inline(always)]
    pub fn is_some(&self) -> bool {
        self.inner.get().is_some()
    }

    /// Returns `true` if the dependency is a [`Some`] and the value inside of it matches a predicate.
    #[inline(always)]
    pub fn is_some_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
        self.as_deref().filter(|inner| f(*inner)).is_some()
    }

    /// Returns `true` if the dependency is a [`None`] value.
    #[inline(always)]
    pub fn is_none(&self) -> bool {
        self.inner.get().is_none()
    }

    /// Returns a slice of the dependency value, if any. If this is [`None`], an empty slice is returned.
    #[inline(always)]
    pub fn as_slice(&self) -> &[T] {
        self.as_deref().map_or(&[], std::slice::from_ref)
    }

    /// Returns an iterator over the dependency value, if any.
    #[inline(always)]
    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.as_slice().iter()
    }

    /// Returns the dependency [`Some`] value.
    ///
    /// # Panics
    /// Panics if the dependency is a [`None`] with a custom panic message provided by `msg`.
    #[inline(always)]
    pub fn expect(&self, msg: &str) -> &T {
        self.as_deref().expect(msg)
    }

    /// Returns the contained [`Some`] value.
    ///
    /// # Panics
    /// Panics if the dependency value equals [`None`].
    #[inline(always)]
    pub fn unwrap(&self) -> &T {
        self.as_deref().unwrap()
    }

    /// Returns the dependency [`Some`] value or a provided default.
    #[inline(always)]
    pub fn unwrap_or(&self, default: T) -> Ref<'_, T> {
        self.as_deref()
            .map(Ref::Borrowed)
            .unwrap_or(Ref::Owned(default))
    }

    /// Returns the dependency [`Some`] value or computes it from a closure.
    #[inline]
    pub fn unwrap_or_else<F>(&self, f: F) -> Ref<'_, T>
    where
        F: FnOnce() -> T,
    {
        self.as_deref()
            .map(Ref::Borrowed)
            .unwrap_or_else(|| Ref::Owned(f()))
    }

    /// Returns the dependency [`Some`] value or a default.
    #[inline(always)]
    pub fn unwrap_or_default(&self) -> Ref<'_, T>
    where
        T: Default,
    {
        self.as_deref()
            .map(Ref::Borrowed)
            .unwrap_or_else(|| Ref::Owned(T::default()))
    }

    /// Maps to [`Option<U>`] by applying a function to a dependency value (if [`Some`])
    /// or returns [`None`] (if [`None`]).
    #[inline]
    pub fn map<U, F>(&self, f: F) -> Option<U>
    where
        F: FnOnce(&T) -> U,
    {
        self.as_deref().map(f)
    }

    /// Calls the provided closure with a reference to the dependency value (if [`Some`]).
    #[inline]
    pub fn inspect<F>(&self, f: F) -> Option<&T>
    where
        F: FnOnce(&T),
    {
        self.as_deref().inspect(|inner| f(*inner))
    }

    /// Returns the provided default result (if [`None`]),
    /// or applies a function to the dependency value (if [`Some`]).
    #[inline]
    pub fn map_or<U, F>(&self, default: U, f: F) -> U
    where
        F: FnOnce(&T) -> U,
    {
        self.as_deref().map_or(default, f)
    }

    /// Computes a default function result (if [`None`]), or
    /// applies a different function to the dependency value (if [`Some`]).
    #[inline]
    pub fn map_or_else<U, D, F>(&self, default: D, f: F) -> U
    where
        D: FnOnce() -> U,
        F: FnOnce(&T) -> U,
    {
        self.as_deref().map_or_else(default, f)
    }

    /// Transforms into a [`Result<&T, E>`], mapping [`Some`] to
    /// [`Ok`] and [`None`] to [`Err`].
    #[inline(always)]
    pub fn ok_or<E>(&self, err: E) -> Result<&T, E> {
        self.as_deref().ok_or(err)
    }

    /// Transforms into a [`Result<&T, E>`], mapping [`Some`] to
    /// [`Ok`] and [`None`] to [`Err`].
    #[inline(always)]
    pub fn ok_or_else<E, F>(&self, err: F) -> Result<&T, E>
    where
        F: FnOnce() -> E,
    {
        self.as_deref().ok_or_else(err)
    }

    /// Converts into a [`Option<&T>`].
    ///
    /// # Note
    /// This is the preferred method for producing an [`Option`] to use with the
    /// [question mark operator][`?`].[^try]
    ///
    /// [`?`]: https://doc.rust-lang.org/nightly/core/option/index.html#the-question-mark-operator-
    /// [^try]: Once the [Try trait](https://github.com/rust-lang/rust/issues/84277) is stabilized
    ///         it will be implemented for `Dependency`.
    #[inline]
    pub fn as_deref(&self) -> Option<&T> {
        self.inner.get().map(|inner| inner.deref())
    }

    /// Returns [`None`] if the dependency is [`None`], otherwise returns `rhs`.
    #[inline(always)]
    pub fn and<U>(&self, rhs: Option<U>) -> Option<U> {
        self.as_deref().and(rhs)
    }

    /// Returns [`None`] if the dependency is [`None`], otherwise calls `f` with the
    /// dependency value and returns the result.
    #[inline]
    pub fn and_then<U, F: FnOnce(&T) -> Option<U>>(&self, f: F) -> Option<U> {
        self.as_deref().and_then(f)
    }

    /// Returns [`None`] if the dependency is [`None`], otherwise calls `predicate`
    /// with the dependency value and returns:
    #[inline]
    pub fn filter<P>(&self, predicate: P) -> Option<&T>
    where
        P: FnOnce(&T) -> bool,
    {
        self.as_deref().filter(|inner| predicate(*inner))
    }

    /// Returns the dependency if it is [`Some`], otherwise returns `rhs`.
    #[inline(always)]
    pub fn or(&self, rhs: Option<T>) -> Option<Ref<'_, T>> {
        self.as_deref().map(Ref::Borrowed).or(rhs.map(Ref::Owned))
    }

    /// Returns the dependency if it is [`Some`], otherwise calls `f` and returns the result.
    #[inline]
    pub fn or_else<F>(&self, f: F) -> Option<Ref<'_, T>>
    where
        F: FnOnce() -> Option<T>,
    {
        self.as_deref()
            .map(Ref::Borrowed)
            .or_else(|| f().map(Ref::Owned))
    }

    /// Returns [`Some`] if only one of
    /// - the dependency, or
    /// - `rhs`
    ///
    /// is [`Some`], otherwise returns [`None`].
    #[inline(always)]
    pub fn xor(&self, rhs: Option<T>) -> Option<Ref<'_, T>> {
        self.as_deref().map(Ref::Borrowed).xor(rhs.map(Ref::Owned))
    }

    /// Maps the dependency to an [`Option<T>`] by **copying** the contents of the option.
    #[inline(always)]
    pub fn copied(&self) -> Option<T>
    where
        T: Copy,
    {
        self.as_deref().copied()
    }

    /// Maps the dependency to an [`Option<T>`] by **cloning** the contents of the option.
    #[inline(always)]
    pub fn cloned(&self) -> Option<T>
    where
        T: Clone,
    {
        self.as_deref().cloned()
    }
}

/// The default value for a dependency.
///
/// There may be many different versions of dependencies for testing but there is often just
/// a single default implementation for use in the the actual application.
///
/// Implementing this trait for a type ensures that a [`Dependency`] on it will always have
/// a value. If the `DependencyDefault` value has not been [overridden][`super::with_dependencies`]
/// it will be returned.
///
/// <div class="warning">
/// Attempting to use this default behavior in a unit test <em>will fail the test</em>,
/// as tests are <u>required</u> to explicitly supply all of their dependencies.
/// </div>
///
/// # Note
/// `DependencyDefault`s are only created as needed. When its first [`Dependency`] is
///  created, [`default`][`Default::default`] will be called once and the returned value will
///  be cached.
pub trait DependencyDefault: Default {}

impl<T: DependencyDefault> Dependency<T> {
    #[track_caller]
    #[inline(never)]
    fn get_or_insert_default(&self) -> &T {
        self.as_deref().unwrap_or_else(|| {
            if cfg!(test) {
                let detailed_explanation = r#".

DependencyDefault types are not allowed to use their default implementation within units tests.
Either register the dependency on the TestStore or use with_dependency(…) within the test itself.
"#;
                panic!(
                    "Dependency<{0}> was constructed during a test,\nbut {0} was not registered{1}",
                    std::any::type_name::<T>(),
                    detailed_explanation
                );
            }

            let guard = Guard::new(T::default());
            std::mem::forget(guard);

            self.inner.set(Guard::get().unwrap()).ok();
            self.as_deref().unwrap()
        })
    }

    /// ## SAFETY
    /// A `DependencyDefault`, once fetched, will last for the life of the process.
    ///
    /// Holding this reference is not advised as it will not reflect further overrides of this dependency.
    #[inline(always)]
    pub fn static_ref() -> &'static T {
        #[allow(unsafe_code)]
        unsafe {
            std::mem::transmute(Self::default().get_or_insert_default())
        }
    }
}

impl<T: DependencyDefault> Deref for Dependency<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.get_or_insert_default()
    }
}

impl<T: DependencyDefault> AsRef<T> for Dependency<T> {
    #[inline(always)]
    fn as_ref(&self) -> &T {
        self.get_or_insert_default()
    }
}

impl<T: DependencyDefault> Borrow<T> for Dependency<T> {
    #[inline(always)]
    fn borrow(&self) -> &T {
        self.get_or_insert_default()
    }
}

impl<T: DependencyDefault> DependencyDefault for Cell<T> {}