Skip to main content

nifty_runtime/
state.rs

1//! Which app state a part of the UI reads, so it can be shown again when that state changes.
2
3/// One `state` declaration of the app, numbered in the order they are declared.
4#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub struct StateId(pub usize);
6
7/// States read by a dynamic part of the UI, sorted and without duplicates.
8#[derive(Clone, Debug, Default, PartialEq, Eq)]
9pub struct StateSet(Vec<StateId>);
10
11impl StateSet {
12    pub fn insert(&mut self, state: StateId) {
13        if let Err(position) = self.0.binary_search(&state) {
14            self.0.insert(position, state);
15        }
16    }
17
18    pub fn extend(&mut self, other: &Self) {
19        for state in &other.0 {
20            self.insert(*state);
21        }
22    }
23
24    #[must_use]
25    pub fn contains(&self, state: StateId) -> bool {
26        self.0.binary_search(&state).is_ok()
27    }
28
29    #[must_use]
30    pub fn intersects(&self, other: &Self) -> bool {
31        self.0.iter().any(|state| other.contains(*state))
32    }
33
34    #[must_use]
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    pub fn iter(&self) -> impl Iterator<Item = StateId> + '_ {
40        self.0.iter().copied()
41    }
42}