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
use crate::core::{
    context::{ContextTracker, TrackingIndex},
    dirty::ReceiveBuilder,
    pipes::CountSender,
    Op_,
};

pub struct Relation<C: Op_> {
    pub(super) context_tracker: ContextTracker,
    pub(super) tracking_index: TrackingIndex,
    pub(super) shown_index: TrackingIndex,
    pub(super) dirty: ReceiveBuilder,
    pub(super) inner: RelationInner<C>,
}

pub(super) struct RelationInner<C: ?Sized> {
    pub counter: CountSender,
    pub inner: C,
}

impl<C> RelationInner<C> {
    pub fn new(inner: C, counter: CountSender) -> Self {
        RelationInner { counter, inner }
    }
}

impl<C: Op_> RelationInner<C> {
    pub fn foreach(&mut self, f: impl FnMut(C::T)) {
        self.inner.foreach(with_counter(&mut self.counter, f))
    }
    pub fn get_vec(&mut self) -> Vec<C::T> {
        let mut result = Vec::new();
        self.foreach(|x| result.push(x));
        result
    }
}

pub(super) fn with_counter<'a, T>(
    counter: &'a mut CountSender,
    mut f: impl FnMut(T) + 'a,
) -> impl FnMut(T) + 'a {
    move |x| {
        counter.increment();
        f(x)
    }
}

impl<C: Op_> Relation<C> {
    pub fn tracking_index(&self) -> TrackingIndex {
        self.tracking_index
    }
    pub fn named(mut self, name: &str) -> Self {
        self.context_tracker
            .set_name(self.shown_index, name.to_string());
        self
    }
    pub fn type_named(mut self, type_name: &str) -> Self {
        self.context_tracker
            .set_type_name(self.shown_index, type_name.to_string());
        self
    }
    pub fn hidden(mut self) -> Self {
        self.context_tracker.set_hidden(self.shown_index);
        self.shown_index = self.context_tracker.find_shown_index(self.shown_index);
        self
    }
}