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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::any::{Any, TypeId};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use constructed::{Constructed, ConstructedShared, AnyInstance};
use inceptor::{Inceptor, Destructor};
use {Result, Collection, Scope};

pub struct Deps {
    /// Ignored type ().
    empty_type: TypeId,
    /// List of functions that constructs all childs for a type
    /// and returns value wrapped in Any that must live as long as the parent type.
    isolated_constructors: HashMap<TypeId,
                                       Vec<Box<Fn(&Deps, &mut Box<Any>) -> Result<Constructed> + Send + Sync>>>,
    /// List of functions that constructs all childs for a type wrapped in Box<Arc<Mutex<T>>> as Box<Any>
    /// and returns value wrapped in Any that must live as long as the parent type.
    shared_constructors: HashMap<TypeId, Vec<Box<Fn(&Deps, &mut Box<Any>) -> Result<ConstructedShared> + Send + Sync>>>,
    /// List of callbacks to invoke after a value and all its dependencies were created.
    type_scope_created: HashMap<TypeId,
                                Vec<Box<Fn(&Deps, &mut AnyInstance) -> Result<()> + Send + Sync>>>,
    /// List of inceptors that manage shared dependency bridge creation for type pairs.
    inceptors: HashMap<(TypeId, TypeId), Box<Any>>,
}

fn to_shared<T: Any>(not_shared: Box<Any>) -> Box<Any> {
    let parent: T = *not_shared.downcast::<T>()
        .expect("expected downcast to P when \
                 changing to shared P");
    Box::new(Arc::new(Mutex::new(parent)))
}

impl Deps {
    pub fn new() -> Deps {
        Deps {
            empty_type: TypeId::of::<()>(),
            isolated_constructors: HashMap::new(),
            shared_constructors: HashMap::new(),
            type_scope_created: HashMap::new(),
            inceptors: HashMap::new(),
        }
    }

    /// Create dependencies for specified `obj` and return a wrapper `Scope` object.
    ///
    /// The wrapper `Scope` keeps ownership of all children together with parent object.
    pub fn create<P: Any>(&self, obj: P) -> Result<Scope<P>> {
        let (parent, deps) =
            try!(self.create_deps_for_any_parent(TypeId::of::<P>(), Box::new(obj), to_shared::<P>));
        Ok(Scope::from_any_instance(parent, deps))
    }

    /// Collect all the items registered as `collectable` into a `Collection` of that type.
    pub fn collect<C: Any>(&self) -> Result<Collection<C>> {
        self.create(Collection::new()).map(|v| v.explode())
    }

    pub fn when_ready<T, F>(&mut self, action: F)
        where T: 'static + Any,
              F: for<'r> Fn(&Deps, &mut T) -> Result<()> + 'static + Send + Sync
    {
        match self.type_scope_created.entry(TypeId::of::<T>()) {
            Entry::Occupied(mut list) => {
                list.get_mut().push(into_action_with_deps(action));
            }
            Entry::Vacant(e) => {
                e.insert(vec![into_action_with_deps(action)]);
            }
        };
    }

    /// Single dependency on a parent.
    pub fn attach<P, C, F>(&mut self, constructor: F)
        where P: 'static + Any, // Parent
              C: 'static + Any, // Child
              F: for<'r> Fn(&Deps, &mut P) -> Result<C> + 'static + Send + Sync
    {
        if TypeId::of::<C>() == self.empty_type {
            self.register_isolated_constructor::<P>(into_isolated_constructor_with_ignored_child_deps(constructor));
        } else {
            self.register_isolated_constructor::<P>(into_isolated_constructor_with_child_deps(constructor));
        }
    }

    /// Single dependency on multiple parents.
    pub fn bridge<P1, P2, C, F>(&mut self, constructor: F)
        where P1: 'static + Any + Send + Sync, // Parent 1
              P2: 'static + Any + Send + Sync, // Parent 2
              C: 'static + Any, // Child
              F: for<'r> Fn(&mut P1, &mut P2) -> Result<C> + 'static + Send + Sync
    {
        // Get or insert inceptor that is used to manage P1 and P2 instances.
        let inceptor_1 = match self.inceptors
            .entry((TypeId::of::<P1>(), TypeId::of::<P2>())) {
            Entry::Occupied(entry) => {
                entry.get()
                    .downcast_ref::<Arc<Mutex<Inceptor<P1, P2>>>>()
                    .expect("expected to find Inceptor of correct type in map")
                    .clone()
            }
            Entry::Vacant(entry) => {
                let arc = Arc::new(Mutex::new(if TypeId::of::<C>() == self.empty_type {
                    Inceptor::new_with_ignored_return_val(constructor)
                } else {
                    Inceptor::new_with_return_val(constructor)
                }));
                entry.insert(Box::new(arc.clone()));
                arc
            }
        };

        // Create inceptor clone for P2 instances
        let inceptor_2 = inceptor_1.clone();

        self.register_shared_constructor::<P1>(
            into_shared_constructor::<P1, P2, C>(
                inceptor_1,
                Box::new(|inceptor: &Arc<Mutex<Inceptor<P1, P2>>>, parent: &mut Box<Any>|
                {
                    let parent_for_inceptor = parent.downcast_mut::<Arc<Mutex<P1>>>()
                        .expect("expected downcast P1")
                        .clone();
                    inceptor.lock()
                        .expect("failed to lock ic1")
                        .incept_1(parent_for_inceptor)
                }),
                1
            )
        );
        self.register_shared_constructor::<P2>(
            into_shared_constructor::<P1, P2, C>(
                inceptor_2,
                Box::new(|inceptor: &Arc<Mutex<Inceptor<P1, P2>>>, parent: &mut Box<Any>|
                {
                    let parent_for_inceptor = parent.downcast_mut::<Arc<Mutex<P2>>>()
                        .expect("expected downcast P2")
                        .clone();
                    inceptor.lock()
                        .expect("failed to lock ic2")
                        .incept_2(parent_for_inceptor)
                }),
                2
            )
        );
    }

    pub fn collectable<C, F>(&mut self, constructor: F)
        where C: 'static + Any,
              F: for<'r> Fn(&Deps) -> C + 'static + Send + Sync
    {
        self.register_isolated_constructor::<Collection<C>>(
            into_isolated_constructor_without_child_deps(move |deps: &Deps, parent: &mut Collection<C>| {
                parent.push(constructor(deps))
            })
        );
    }

    fn create_deps_for_any_parent<F>(&self,
                                     type_id: TypeId,
                                     mut parent_not_shared: Box<Any>,
                                     to_shared: F)
                                     -> Result<(AnyInstance, Vec<Box<Any>>)>
        where F: Fn(Box<Any>) -> Box<Any>
    {
        let mut deps = Vec::new();

        // First, construct any instances that do not need parent wrapped in mutex

        match self.isolated_constructors.get(&type_id) {
            Some(isolated_list) => {
                for any_constructor in isolated_list {
                    match any_constructor(&self, &mut parent_not_shared) {
                        Ok(Constructed { children }) => deps.extend(children),
                        Err(any_err) => return Err(any_err),
                    };
                }
            }
            None => (),
        }

        // Then, check if there are shared constructors, and if so, wrap value in mutex
        // and return it in AnyInstance::Shared, otherwise, return it in AnyInstance::Isolated.

        let mut parent_result = match self.shared_constructors.get(&type_id) {
            Some(shared_list) => {
                let mut parent_shared = to_shared(parent_not_shared);

                for any_constructor in shared_list {
                    match any_constructor(&self, &mut parent_shared) {
                        Ok(ConstructedShared { children }) => deps.extend(children),
                        Err(any_err) => return Err(any_err),
                    };
                }

                AnyInstance::Shared(parent_shared)
            }
            None => AnyInstance::Isolated(parent_not_shared),
        };

        // Execute post create actions for the value

        if let Some(actions) = self.type_scope_created.get(&type_id) {
            for action in actions {
                try!(action(&self, &mut parent_result));
            }
        }

        Ok((parent_result, deps))
    }

    /// Register child constructor that will be invoked when the parent `P` type is
    /// created.
    fn register_isolated_constructor<P: Any>(&mut self,
                                             any_constructor: Box<Fn(&Deps, &mut Box<Any>)
                                                                     -> Result<Constructed> + Send + Sync>) {
        match self.isolated_constructors.entry(TypeId::of::<P>()) {
            Entry::Occupied(mut list) => {
                list.get_mut().push(any_constructor);
            }
            Entry::Vacant(e) => {
                e.insert(vec![any_constructor]);
            }
        };
    }

    /// Register child constructor that will be invoked when the parent `P` type is
    /// created.
    fn register_shared_constructor<P: Any>(&mut self,
                                           any_constructor: Box<Fn(&Deps, &mut Box<Any>)
                                                                   -> Result<ConstructedShared> + Send + Sync>) {
        match self.shared_constructors.entry(TypeId::of::<P>()) {
            Entry::Occupied(mut list) => {
                list.get_mut().push(any_constructor);
            }
            Entry::Vacant(e) => {
                e.insert(vec![any_constructor]);
            }
        };
    }
}

unsafe impl Send for Deps {}
unsafe impl Sync for Deps {}

fn into_action_with_deps<P, F>(action: F)
                               -> Box<Fn(&Deps, &mut AnyInstance) -> Result<()> + Send + Sync>
    where F: for<'r> Fn(&Deps, &mut P) -> Result<()> + 'static + Send + Sync,
          P: 'static + Any
{
    Box::new(move |deps: &Deps, parent: &mut AnyInstance| -> Result<()> {
        match *parent {
            AnyInstance::Isolated(ref mut value) => {
                try!(action(deps,
                            &mut value.downcast_mut::<P>()
                                .expect("expected to downcast type in post create action")))
            }
            AnyInstance::Shared(ref mut value) => {
                try!(action(deps,
                            &mut value.downcast_mut::<Arc<Mutex<P>>>()
                                .expect("expected to downcast type in post create action")
                                .lock()
                                .expect("expected to lock value for AnyInstance::Shared action")))
            }
        };
        Ok(())
    })
}

fn into_shared_constructor<P1, P2, C>
    (
        inceptor: Arc<Mutex<Inceptor<P1, P2>>>,
        incept_fun: Box<Fn(&Arc<Mutex<Inceptor<P1, P2>>>, &mut Box<Any>) -> Result<(usize, Vec<Box<Any>>)> + Send + Sync>,
        index: usize
    )
     -> Box<Fn(&Deps, &mut Box<Any>) -> Result<ConstructedShared> + Send + Sync>
    where P1: 'static + Any + Send + Sync, // Parent 1
          P2: 'static + Any + Send + Sync, // Parent 2
          C: 'static + Any // Child
{
    Box::new(move |deps: &Deps, parent: &mut Box<Any>| -> Result<ConstructedShared> {
        let (id, instances) = try!(incept_fun(&inceptor, parent));

        let mut children: Vec<Box<Any>> = Vec::with_capacity(instances.len() + 1);

        for instance in instances {
            let instance_artifacts =
                try!(deps.create_deps_for_any_parent(TypeId::of::<C>(), instance, to_shared::<C>));
            children.push(Box::new(instance_artifacts));
        }

        children.push(Box::new(Destructor::new(inceptor.clone(), index, id)));

        Ok(ConstructedShared { children: children })
    })
}

fn into_isolated_constructor_with_child_deps<P, C, F>
    (constructor: F)
     -> Box<Fn(&Deps, &mut Box<Any>) -> Result<Constructed> + Send + Sync>
    where F: for<'r> Fn(&Deps, &mut P) -> Result<C> + 'static + Send + Sync,
          P: 'static + Any,
          C: 'static + Any
{
    Box::new(move |deps: &Deps, parent: &mut Box<Any>| -> Result<Constructed> {
        let child = {
            let concrete_parent = parent.downcast_mut::<P>()
                .expect("expected to downcast type in into_isolated_constructor_with_child_deps");
            try!(deps.create(try!(constructor(deps, concrete_parent))))
        };
        Ok(Constructed { children: vec![Box::new(child)] })
    })
}

fn into_isolated_constructor_with_ignored_child_deps<P, C, F>
    (constructor: F)
     -> Box<Fn(&Deps, &mut Box<Any>) -> Result<Constructed> + Send + Sync>
    where F: for<'r> Fn(&Deps, &mut P) -> Result<C> + 'static + Send + Sync,
          P: 'static + Any,
          C: 'static + Any
{
    Box::new(move |deps: &Deps, parent: &mut Box<Any>| -> Result<Constructed> {
        try!(constructor(deps,
                         parent.downcast_mut::<P>()
                             .expect("expected to downcast type in \
                                      into_isolated_constructor_with_ignored_child_deps")));
        Ok(Constructed { children: vec![] })
    })
}

fn into_isolated_constructor_without_child_deps<P, F>
    (constructor: F)
     -> Box<Fn(&Deps, &mut Box<Any>) -> Result<Constructed> + Send + Sync>
    where F: for<'r> Fn(&Deps, &mut P) + 'static + Send + Sync,
          P: 'static + Any
{
    Box::new(move |deps: &Deps, parent: &mut Box<Any>| -> Result<Constructed> {
        constructor(deps,
                    parent.downcast_mut::<P>()
                        .expect("expected to downcast type in \
                                 into_isolated_constructor_without_child_deps"));
        Ok(Constructed { children: vec![] })
    })
}

#[cfg(test)]
mod test {
    use Deps;
    use std::thread;
    use std::sync::{Arc, Mutex};

    #[derive(Clone, Debug, Eq, PartialEq)]
    struct A(String);

    #[derive(Clone, Debug, Eq, PartialEq)]
    struct B(String);

    #[derive(Clone, Debug, Eq, PartialEq)]
    struct C(String);

    #[test]
    fn creates_dependency() {
        let mut deps = Deps::new();

        // here we want to know what is the state of dependency in closure, hence
        // shared mutable reference to it
        let created_b_ref = Arc::new(Mutex::new(None));

        deps.attach({
            let created_b_ref = created_b_ref.clone();
            move |_: &Deps, a: &mut A| {
                let b = B([&a.0[..], "+B"].concat());
                *created_b_ref.lock().unwrap() = Some(b.clone());
                Ok(b)
            }
        });

        deps.create(A("Hello".into())).unwrap();

        assert_eq!("Hello+B",
                   (*created_b_ref.lock().unwrap()).clone().unwrap().0);
    }

    #[test]
    fn creates_dependency_of_dependency() {
        let mut deps = Deps::new();

        // here we want to know what is the state of dependency in closure, hence
        // shared mutable reference to it
        let created_c_ref = Arc::new(Mutex::new(None));

        deps.attach(|_: &Deps, a: &mut A| Ok(B([&a.0[..], "+B"].concat())));

        deps.attach({
            let created_c_ref = created_c_ref.clone();
            move |_: &Deps, b: &mut B| {
                let c = C([&b.0[..], "+C"].concat());
                *created_c_ref.lock().unwrap() = Some(c.clone());
                Ok(c)
            }
        });

        deps.create(A("Hello".into())).unwrap();

        assert_eq!("Hello+B+C",
                   (*created_c_ref.lock().unwrap()).clone().unwrap().0);
    }

    #[test]
    fn creates_mutable_dependency() {
        let mut deps = Deps::new();

        deps.attach(|_: &Deps, a: &mut A| {
            *a = A("Hi!".into());
            Ok(())
        });

        let mut a = deps.create(A("Hello".into())).unwrap();
        let al = a.lock().unwrap();

        assert_eq!("Hi!", al.0);
    }

    #[test]
    fn should_work_accross_threads() {
        let mut deps = Deps::new();

        deps.attach(|_: &Deps, _: &mut A| Ok(B("b".into())));
        deps.attach(|_: &Deps, _: &mut B| Ok(C("c".into())));

        let dep_refs = Arc::new(deps);

        let a = thread::spawn({
            let a_deps = dep_refs.clone();
            move || a_deps.create(A("a".into())).unwrap()
        });

        let b = thread::spawn({
            let b_deps = dep_refs.clone();
            move || b_deps.create(B("b".into())).unwrap()
        });

        assert_eq!(b.join().unwrap().explode(), B("b".into()));
        assert_eq!(a.join().unwrap().explode(), A("a".into()));
    }

    #[test]
    fn can_create_bridge_dependency() {
        let mut deps = Deps::new();

        let created_bridge = Arc::new(Mutex::new(None));
        let created_bridge_clone = created_bridge.clone(); // so we can modify this from inside the closure

        deps.bridge(|a: &mut A, b: &mut B| Ok(vec![a.0.clone(), b.0.clone()]));

        // Use this to copy created Vec<String> value from bridge to mutex protected clone
        deps.when_ready(move |_: &Deps, parent: &mut Vec<String>| {
            *created_bridge_clone.lock().unwrap() = Some(parent.clone());
            Ok(())
        });

        // Bind to created A and modify the value from "Hello" to "Hi"
        deps.attach(|_: &Deps, a: &mut A| {
            *a = A("Hi".into());
            Ok(5)
        });

        // Attach to any type Vec<String> and append "Nice" to last element
        deps.attach(|_: &Deps, created_bridge_result: &mut Vec<String>| {
            created_bridge_result.push("Nice".to_string());
            Ok(())
        });

        // Create both instigators and result should appear
        let mut a = deps.create(A("Hello".into())).unwrap();
        let mut b = deps.create(B("World".into())).unwrap();

        {
            let al = a.lock().unwrap();
            let bl = b.lock().unwrap();

            assert_eq!("Hi", al.0);
            assert_eq!("World", bl.0);
        }

        {
            let val = created_bridge.lock()
                .unwrap();
            assert_eq!("HiWorldNice",
                       val.as_ref().expect("expected bridge val to be created").concat());
        }

        let mut c = deps.create(B("Rust".into())).unwrap();

        {
            let cl = c.lock().unwrap();

            assert_eq!("Rust", cl.0);
        }

        {
            let val = created_bridge.lock()
                .unwrap();
            assert_eq!("HiRustNice",
                       val.as_ref().expect("expected bridge val to be created").concat());
        }

        assert_eq!(c.explode(), B("Rust".into()));
        assert_eq!(a.explode(), A("Hi".into()));
        assert_eq!(b.explode(), B("World".into()));
    }
}