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
use std::rc::Rc;

use crate::sources::EventDispatcher;
use crate::token::TokenInner;

pub(crate) struct SourceEntry<'l, Data> {
    pub(crate) token: TokenInner,
    pub(crate) source: Option<Rc<dyn EventDispatcher<Data> + 'l>>,
}

pub(crate) struct SourceList<'l, Data> {
    sources: Vec<SourceEntry<'l, Data>>,
}

impl<'l, Data> SourceList<'l, Data> {
    pub(crate) fn new() -> Self {
        SourceList {
            sources: Vec::new(),
        }
    }

    pub(crate) fn vacant_entry(&mut self) -> &mut SourceEntry<'l, Data> {
        let opt_id = self.sources.iter().position(|slot| slot.source.is_none());
        match opt_id {
            Some(id) => {
                // we are reusing a slot
                let slot = &mut self.sources[id];
                // increment the slot version
                slot.token = slot.token.increment_version();
                slot
            }
            None => {
                // we are inserting a new slot
                let next_id = self.sources.len();
                self.sources.push(SourceEntry {
                    token: TokenInner::new(self.sources.len())
                        .expect("Trying to insert too many sources in an event loop."),
                    source: None,
                });
                &mut self.sources[next_id]
            }
        }
    }

    pub(crate) fn get(&self, token: TokenInner) -> crate::Result<&SourceEntry<'l, Data>> {
        let entry = self
            .sources
            .get(token.get_id())
            .ok_or(crate::Error::InvalidToken)?;
        if entry.token.same_source_as(token) {
            Ok(entry)
        } else {
            Err(crate::Error::InvalidToken)
        }
    }

    pub(crate) fn get_mut(
        &mut self,
        token: TokenInner,
    ) -> crate::Result<&mut SourceEntry<'l, Data>> {
        let entry = self
            .sources
            .get_mut(token.get_id())
            .ok_or(crate::Error::InvalidToken)?;
        if entry.token.same_source_as(token) {
            Ok(entry)
        } else {
            Err(crate::Error::InvalidToken)
        }
    }
}