wasm_rgame/application/delegate/manager/
spawner.rs

1use raii_counter::Counter;
2use std::vec::Drain;
3use super::{Delegate, SpawnedDelegate, SpawnHandle, SpawnableDelegate};
4
5/// Type used to spawn / spawn_root new delegates onto the Application
6pub struct DelegateSpawner {
7    spawned_delegates: Vec<SpawnedDelegate>,
8    spawned_root_delegates: Vec<Box<Delegate>>,
9}
10
11impl DelegateSpawner {
12    pub fn new() -> DelegateSpawner {
13        DelegateSpawner {
14            spawned_delegates: Vec::new(),
15            spawned_root_delegates: Vec::new(),
16        }
17    }
18
19    /// Takes ownership of a Delegate, returns a SpawnHandle containing the
20    /// Handle type of the SpawnableDelegate
21    ///
22    /// The spawned object cannot be found by the object spawning it, therefore it
23    /// should use the Handle returned to get information
24    ///
25    /// Dropping all instances of the SpawnHandle will cause the delegate to be dropped.
26    pub fn spawn<D>(
27        &mut self,
28        mut spawnable_delegate: D
29    ) -> SpawnHandle<D::Handle>
30    where
31        D: 'static + SpawnableDelegate
32    {
33        let handle = spawnable_delegate.handle();
34        let handle_counter = Counter::new();
35
36        spawnable_delegate.on_spawn(self);
37        self.spawned_delegates.push(SpawnedDelegate {
38            inner: Box::new(spawnable_delegate),
39            handles_counter: handle_counter.clone().downgrade(),
40        });
41
42        SpawnHandle {
43            handle,
44            _counter: handle_counter,
45        }
46    }
47
48    /// Takes ownership of a Delegate, it is held for the
49    /// lifetime of the entire Application
50    pub fn spawn_root<D: 'static + Delegate>(&mut self, mut delegate: D) {
51        delegate.on_spawn(self);
52        self.spawned_root_delegates.push(Box::new(delegate));
53    }
54
55    pub(super) fn spawned_delegates(&mut self) -> Drain<SpawnedDelegate> {
56        self.spawned_delegates.drain(0..)
57    }
58
59    pub(super) fn spawned_root_delegates(&mut self) -> Drain<Box<Delegate>> {
60        self.spawned_root_delegates.drain(0..)
61    }
62}