gc_sequence/
sequence_fn.rs

1use gc_arena::{Collect, MutationContext, StaticCollect};
2
3use crate::Sequence;
4
5pub fn from_fn<'gc, F, R>(f: F) -> SequenceFn<F>
6where
7    F: 'static + FnOnce(MutationContext<'gc, '_>) -> R,
8{
9    SequenceFn::new(f)
10}
11
12#[must_use = "sequences do nothing unless stepped"]
13#[derive(Debug, Collect)]
14#[collect(no_drop)]
15pub struct SequenceFn<F>(Option<StaticCollect<F>>);
16
17impl<F> SequenceFn<F> {
18    pub fn new(f: F) -> SequenceFn<F> {
19        SequenceFn(Some(StaticCollect(f)))
20    }
21}
22
23impl<'gc, F, R> Sequence<'gc> for SequenceFn<F>
24where
25    F: 'static + FnOnce(MutationContext<'gc, '_>) -> R,
26{
27    type Output = R;
28
29    fn step(&mut self, mc: MutationContext<'gc, '_>) -> Option<Self::Output> {
30        Some(self.0.take().expect("cannot step a finished sequence").0(
31            mc,
32        ))
33    }
34}
35
36pub fn from_fn_with<'gc, C, F, R>(c: C, f: F) -> SequenceFnWith<C, F>
37where
38    C: Collect,
39    F: 'static + FnOnce(MutationContext<'gc, '_>, C) -> R,
40{
41    SequenceFnWith::new(c, f)
42}
43
44#[must_use = "sequences do nothing unless stepped"]
45#[derive(Debug, Collect)]
46#[collect(no_drop)]
47pub struct SequenceFnWith<C, F>(Option<(C, StaticCollect<F>)>);
48
49impl<C, F> SequenceFnWith<C, F> {
50    pub fn new(c: C, f: F) -> SequenceFnWith<C, F> {
51        SequenceFnWith(Some((c, StaticCollect(f))))
52    }
53}
54
55impl<'gc, C, F, R> Sequence<'gc> for SequenceFnWith<C, F>
56where
57    F: 'static + FnOnce(MutationContext<'gc, '_>, C) -> R,
58    C: Collect,
59{
60    type Output = R;
61
62    fn step(&mut self, mc: MutationContext<'gc, '_>) -> Option<Self::Output> {
63        let (c, StaticCollect(f)) = self.0.take().expect("cannot step a finished sequence");
64        Some(f(mc, c))
65    }
66}