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
use crate::Factory;
use atomic_immut::AtomicImmut;
use std::sync::Arc;

/// `#[cfg(feature = "swappable")]` A `Factory` that allows for swapping inner factories dynamically.
///
/// This use a lock-free data structure for swapping.
///
/// # Examples
///
/// ```
/// use factory::{CloneFactory, Factory, SwappableFactory};
///
/// let f0 = SwappableFactory::new(CloneFactory::new(32));
/// let f1 = f0.clone();
/// assert_eq!(f0.create(), 32);
/// assert_eq!(f1.create(), 32);
///
/// f0.swap(CloneFactory::new(50));
/// assert_eq!(f0.create(), 50);
/// assert_eq!(f1.create(), 50);
/// ```
#[derive(Debug, Default)]
pub struct SwappableFactory<T>(Arc<AtomicImmut<T>>);
impl<T: Factory> SwappableFactory<T> {
    /// Makes a new `SwappableFactory` with the initial inner factory.
    pub fn new(inner: T) -> Self {
        SwappableFactory(Arc::new(AtomicImmut::new(inner)))
    }

    /// Returns the currently used factory.
    pub fn get(&self) -> Arc<T> {
        self.0.load()
    }

    /// Updates inner factory by `new`, and returns old one.
    ///
    /// This operation affects all `SwappableFactory` instances cloned from the original one.
    pub fn swap(&self, new: T) -> Arc<T> {
        self.0.swap(new)
    }
}
impl<T: Factory> Factory for SwappableFactory<T> {
    type Item = T::Item;

    fn create(&self) -> Self::Item {
        self.0.load().create()
    }
}
impl<T> Clone for SwappableFactory<T> {
    fn clone(&self) -> Self {
        SwappableFactory(Arc::clone(&self.0))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{CloneFactory, DefaultFactory, Factory};

    #[test]
    fn swappable_factory_works() {
        let f = SwappableFactory::new(CloneFactory::new(32));
        assert_eq!(f.create(), 32);

        f.swap(CloneFactory::new(50));
        assert_eq!(f.create(), 50);
    }

    #[test]
    fn swappable_box_factory_works() {
        let first: Box<Factory<Item = i32> + 'static> = Box::new(CloneFactory::new(32));
        let f = SwappableFactory::new(first);
        assert_eq!(f.create(), 32);

        let second = Box::new(DefaultFactory::new());
        f.swap(second);
        assert_eq!(f.create(), 0);
    }
}