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
use std::collections::HashMap;
use std::fmt;

use crate::{generate_next_id, ComponentId, EventEntry, Scheduler, State};

pub trait ProcessEventEntry {
    fn process_event_entry(&self, entry: EventEntry, scheduler: &mut Scheduler, state: &mut State);
}

/// Interface of a simulation component.
pub trait Component: ProcessEventEntry {
    /// Type of event the component reacts to.
    type Event: fmt::Debug + 'static;

    /// Reacts to `event`. A component has access to the following elements of the simulation:
    /// - `self_id`: This is the ID of this component. This is used to schedule events to itself.
    ///              This is passed for convenience, as the ID is only known after the component
    ///              has been already constructed and passed to the simulation.
    /// - `event`: The occurring event.
    /// - `scheduler`: The scheduler used to access time and schedule new events.
    /// - `state`: The state is used to access queues and values in the value store.
    fn process_event(
        &self,
        self_id: ComponentId<Self::Event>,
        event: &Self::Event,
        scheduler: &mut Scheduler,
        state: &mut State,
    );
}

impl<E, C> ProcessEventEntry for C
where
    E: fmt::Debug + 'static,
    C: Component<Event = E>,
{
    fn process_event_entry(&self, entry: EventEntry, scheduler: &mut Scheduler, state: &mut State) {
        let entry = entry
            .downcast::<E>()
            .expect("Failed to downcast event entry.");
        self.process_event(entry.component_id, entry.event, scheduler, state);
    }
}

/// Container holding type-erased components.
#[derive(Default)]
pub struct Components {
    components: HashMap<usize, Box<dyn ::std::any::Any>>,
}

impl Components {
    #[allow(clippy::missing_panics_doc)]
    /// Process the event on the component given by the event entry.
    pub fn process_event_entry(
        &self,
        entry: EventEntry,
        scheduler: &mut Scheduler,
        state: &mut State,
    ) {
        self.components
            .get(&entry.component_idx())
            .unwrap()
            .downcast_ref::<Box<dyn ProcessEventEntry>>()
            .expect("Failed to downcast component.")
            .process_event_entry(entry, scheduler, state);
    }

    /// Registers a new component and returns its ID.
    #[must_use]
    pub fn add_component<E: fmt::Debug + 'static, C: Component<Event = E> + 'static>(
        &mut self,
        component: C,
    ) -> ComponentId<E> {
        let id = generate_next_id();
        let component: Box<dyn ProcessEventEntry> = Box::new(component);
        self.components.insert(id, Box::new(component));
        ComponentId::new(id)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    struct TestComponent(Rc<RefCell<String>>);

    impl Component for TestComponent {
        type Event = String;

        fn process_event(
            &self,
            _self_id: ComponentId<Self::Event>,
            event: &Self::Event,
            _scheduler: &mut Scheduler,
            _state: &mut State,
        ) {
            *self.0.borrow_mut() = event.clone();
        }
    }

    struct RcTestComponent(String);

    impl Component for Rc<RefCell<RcTestComponent>> {
        type Event = String;

        fn process_event(
            &self,
            _self_id: ComponentId<Self::Event>,
            event: &Self::Event,
            _scheduler: &mut Scheduler,
            _state: &mut State,
        ) {
            self.borrow_mut().0 = event.clone();
        }
    }

    #[test]
    fn test_add_and_get_component() {
        let mut scheduler = Scheduler::default();
        let mut state = State::default();
        let mut components = Components::default();
        assert_eq!(components.components.len(), 0);

        let text = Rc::new(RefCell::new(String::from("")));

        let comp: ComponentId<String> = components.add_component(TestComponent(Rc::clone(&text)));
        assert_eq!(components.components.len(), 1);

        components.process_event_entry(
            EventEntry::new(
                std::time::Duration::default(),
                comp,
                String::from("Modified"),
            ),
            &mut scheduler,
            &mut state,
        );

        assert_eq!(*text.borrow(), "Modified");
    }

    #[test]
    fn test_rc_ref_cell() {
        let mut scheduler = Scheduler::default();
        let mut state = State::default();

        let component = Rc::new(RefCell::new(RcTestComponent(String::from(""))));
        let mut components = Components::default();
        let comp: ComponentId<String> = components.add_component(Rc::clone(&component));

        components.process_event_entry(
            EventEntry::new(
                std::time::Duration::default(),
                comp,
                String::from("Modified"),
            ),
            &mut scheduler,
            &mut state,
        );

        assert_eq!(component.borrow().0, "Modified");
    }
}