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
use crate::Composer;

pub struct Recomposer {
    pub(crate) composer: Composer,
}

impl Recomposer {
    pub fn new() -> Self {
        Recomposer {
            composer: Composer::new(),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Recomposer {
            composer: Composer::with_capacity(capacity),
        }
    }

    pub fn root<R: 'static>(&self) -> Option<&R> {
        self.composer
            .tape
            .get(0)
            .and_then(|s| s.data.as_ref())
            .and_then(|n| n.as_any().downcast_ref::<R>())
    }

    pub fn root_mut<R: 'static>(&mut self) -> Option<&mut R> {
        self.composer
            .tape
            .get_mut(0)
            .and_then(|s| s.data.as_mut())
            .and_then(|n| n.as_any_mut().downcast_mut::<R>())
    }

    pub fn composer(&mut self) -> &mut Composer {
        &mut self.composer
    }

    pub fn finalize(&mut self) {
        self.composer.tape.truncate(self.composer.cursor);
        self.composer.slot_depth.truncate(self.composer.cursor);
        self.composer.cursor = 0;
        self.composer.depth = 0;
        self.composer.recycle_bin.clear();
    }
}

impl Default for Recomposer {
    fn default() -> Self {
        Self::new()
    }
}