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
use crate::{CallId, Recomposer, Slot, SlotId};
use downcast_rs::{impl_downcast, Downcast};
use log::trace;
use std::{any::Any, collections::HashMap, panic::Location, pin::Pin};

pub trait ComposeNode: Unpin + Downcast {}
impl_downcast!(ComposeNode);
impl<T: Unpin + Downcast> ComposeNode for T {}

type Tape = Vec<Slot<Pin<Box<dyn ComposeNode>>>>;

pub struct Composer {
    pub(crate) tape: Tape,
    pub(crate) slot_depth: Vec<usize>,
    pub(crate) depth: usize,
    pub(crate) cursor: usize,
    pub(crate) slot_key: Option<usize>,
    pub(crate) recycle_bin: HashMap<SlotId, Tape>,
}

impl Composer {
    pub fn new(capacity: usize) -> Self {
        Composer {
            tape: Vec::with_capacity(capacity),
            slot_depth: Vec::with_capacity(capacity),
            depth: 0,
            cursor: 0,
            slot_key: None,
            recycle_bin: HashMap::new(),
        }
    }
}

impl Composer {
    pub fn finalize(mut self) -> Recomposer {
        self.tape.truncate(self.cursor);
        self.slot_depth.truncate(self.cursor);
        self.cursor = 0;
        self.depth = 0;
        self.recycle_bin.clear();
        Recomposer { composer: self }
    }

    pub fn finalize_with<F>(mut self, func: F) -> Recomposer
    where
        F: FnOnce(&mut Self),
    {
        self.cursor = 0;
        self.depth = 0;
        func(&mut self);
        Recomposer { composer: self }
    }

    #[track_caller]
    pub fn tag<F, T>(&mut self, key: usize, func: F) -> T
    where
        F: FnOnce(&mut Composer) -> T,
    {
        // set the key of first encountered group
        self.slot_key = Some(key);
        func(self)
    }

    #[track_caller]
    pub fn state<Node>(&mut self, val: Node) -> Node
    where
        Node: ComposeNode + Clone,
    {
        self.memo(|_| val, |_| true, |_| {}, |n| n.clone())
    }

    #[track_caller]
    pub fn memo<F, Node, S, U, O, Output>(
        &mut self,
        factory: F,
        skip: S,
        update: U,
        output: O,
    ) -> Output
    where
        F: FnOnce(&mut Composer) -> Node,
        Node: ComposeNode,
        S: FnOnce(&mut Node) -> bool,
        U: FnOnce(&mut Node),
        O: FnOnce(&Node) -> Output,
    {
        self.slot(
            factory,
            false,
            |_| {},
            false,
            |_, _| {},
            skip,
            update,
            output,
        )
    }

    #[track_caller]
    pub fn group_use_children<F, Node, C, S, A, U, O, Output>(
        &mut self,
        factory: F,
        children: C,
        apply_children: A,
        skip: S,
        update: U,
        output: O,
    ) -> Output
    where
        F: FnOnce(&mut Composer) -> Node,
        Node: ComposeNode,
        C: FnOnce(&mut Composer),
        S: FnOnce(&mut Node) -> bool,
        A: FnOnce(&mut Node, Vec<&dyn ComposeNode>),
        U: FnOnce(&mut Node),
        O: FnOnce(&Node) -> Output,
    {
        self.slot(
            factory,
            true,
            children,
            true,
            apply_children,
            skip,
            update,
            output,
        )
    }

    #[track_caller]
    pub fn group<F, Node, C, S, A, U, O, Output>(
        &mut self,
        factory: F,
        children: C,
        skip: S,
        update: U,
        output: O,
    ) -> Output
    where
        F: FnOnce(&mut Composer) -> Node,
        Node: ComposeNode,
        C: FnOnce(&mut Composer),
        S: FnOnce(&mut Node) -> bool,
        A: FnOnce(&mut Node, Vec<&dyn ComposeNode>),
        U: FnOnce(&mut Node),
        O: FnOnce(&Node) -> Output,
    {
        self.slot(
            factory,
            true,
            children,
            false,
            |_, _| {},
            skip,
            update,
            output,
        )
    }

    #[track_caller]
    #[allow(clippy::too_many_arguments)]
    pub fn slot<F, Node, C, S, A, U, O, Output>(
        &mut self,
        factory: F,
        has_children: bool,
        children: C,
        use_children: bool,
        apply_children: A,
        skip: S,
        update: U,
        output: O,
    ) -> Output
    where
        F: FnOnce(&mut Composer) -> Node,
        Node: ComposeNode,
        C: FnOnce(&mut Composer),
        S: FnOnce(&mut Node) -> bool,
        A: FnOnce(&mut Node, Vec<&dyn ComposeNode>),
        U: FnOnce(&mut Node),
        O: FnOnce(&Node) -> Output,
    {
        // remember current cursor
        let cursor = self.forward_cursor();

        let curr_depth = self.depth;
        self.depth += 1;
        if let Some(d) = self.slot_depth.get_mut(cursor) {
            *d = curr_depth
        } else {
            self.slot_depth.insert(cursor, curr_depth);
        }

        // construct slot id
        let call_id = CallId::from(Location::caller());
        let key = self.slot_key.take();
        let slot_id = SlotId::new(call_id, key);

        // found in recycle_bin, restore it
        let slot_group = self.recycle_bin.remove(&slot_id);
        if let Some(group) = slot_group {
            let mut curr_idx = cursor;
            // TODO: use gap table?
            for slot in group {
                self.tape.insert(curr_idx, slot);
                curr_idx += 1;
            }
        }

        let cached = self.tape.get_mut(cursor).map(|s| {
            // `Composer` required to guarantee `content` function not able to access current slot in self.tape
            // Otherwise need to wrap self.tape with RefCell to remove this unsafe but come with cost
            let ptr = s.data.as_mut().expect("slot data").as_mut().get_mut();
            let data = Box::leak(unsafe { Box::from_raw(ptr) });
            (s.id, s.size, data)
        });

        if let Some((p_slot_id, p_size, p_data)) = cached {
            if slot_id == p_slot_id {
                if let Some(node) = p_data.as_any_mut().downcast_mut::<Node>() {
                    trace!("{: >15} {} - {:?}", "get_cached", cursor, slot_id,);
                    if skip(node) {
                        trace!(
                            "{: >15} {} - {:?} - {}",
                            "skip_slot",
                            cursor,
                            slot_id,
                            p_size
                        );
                        self.skip_slot(cursor, p_size);
                    } else {
                        if has_children {
                            children(self);
                            if use_children {
                                let c = self.children_of_slot_at(cursor);
                                apply_children(node, c);
                            }
                        }
                        update(node);
                        self.end_slot_update(cursor);
                    }
                    return output(node);
                } else {
                    // NOTE:
                    // same slot_id can only return same type as before under same root fn
                    // However, this can happen when recompose with different root fn
                    trace!(
                        "{: >15} {} - {:?} - {:?}",
                        "downcast failed",
                        cursor,
                        slot_id,
                        p_data.type_id()
                    );
                }
            }
            // move previous cached slot to recycle bin
            self.recycle_slot(cursor, p_slot_id, p_size);
        }

        self.begin_slot(cursor, slot_id);
        let mut node = factory(self);

        if has_children {
            children(self);

            if use_children {
                let c = self.children_of_slot_at(cursor);
                apply_children(&mut node, c);
            }
        }

        let out = output(&node);
        // NOTE: expect node.into() will not change what node is
        let data = Box::pin(node);
        self.end_slot(cursor, data);
        out
    }

    fn children_of_slot_at(&mut self, cursor: usize) -> Vec<&dyn ComposeNode> {
        let child_start = cursor + 1;
        let children = self.slot_depth[child_start..self.cursor]
            .iter()
            .cloned()
            .enumerate()
            .filter_map(|(i, v)| {
                if v == self.depth {
                    Some(child_start + i)
                } else {
                    None
                }
            })
            .filter_map(|c| {
                self.tape
                    .get(c)
                    .map(|s| s.data.as_ref().expect("slot data").as_ref().get_ref())
            })
            .collect();
        children
    }

    fn begin_slot(&mut self, cursor: usize, slot_id: SlotId) {
        let slot = Slot::placeholder(slot_id);
        self.tape.insert(cursor, slot);
        trace!("{: >15} {} - {:?}", "begin_slot", cursor, slot_id);
    }

    fn end_slot(&mut self, cursor: usize, data: Pin<Box<dyn ComposeNode>>) {
        self.depth -= 1;
        let curr_cursor = self.current_cursor();
        if let Some(slot) = self.tape.get_mut(cursor) {
            slot.data = Some(data);
            slot.size = curr_cursor - cursor;
            trace!("{: >15} {} - {:?}", "end_slot", cursor, slot.id);
        }
    }

    fn end_slot_update(&mut self, cursor: usize) {
        self.depth -= 1;
        let curr_cursor = self.current_cursor();
        if let Some(slot) = self.tape.get_mut(cursor) {
            slot.size = curr_cursor - cursor;
            trace!("{: >15} {} - {:?}", "end_slot_update", cursor, slot.id);
        }
    }

    fn skip_slot(&mut self, cursor: usize, size: usize) {
        self.depth -= 1;
        self.cursor = cursor + size;
    }

    #[inline]
    fn current_cursor(&mut self) -> usize {
        self.cursor
    }

    #[inline]
    fn forward_cursor(&mut self) -> usize {
        let cursor = self.current_cursor();
        self.cursor = cursor + 1;
        cursor
    }

    fn recycle_slot(&mut self, cursor: usize, slot_id: SlotId, size: usize) {
        let slots = self.tape.drain(cursor..cursor + size).collect();
        self.recycle_bin.insert(slot_id, slots);
    }
}