tty_form/
dependency.rs

1use std::{
2    collections::HashMap,
3    sync::atomic::{AtomicUsize, Ordering},
4};
5
6/// A unique identifier.
7#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
8pub struct DependencyId(usize);
9
10/// The greatest dependency identifier provisioned thus far.
11static ID_VALUE: AtomicUsize = AtomicUsize::new(0);
12
13impl DependencyId {
14    /// Create a new, unique dependency identifier.
15    pub(crate) fn new() -> Self {
16        Self(ID_VALUE.fetch_add(1, Ordering::Relaxed))
17    }
18}
19
20/// An evaluation to apply to the source of a dependency.
21#[derive(Clone)]
22pub enum Evaluation {
23    /// Evaluates true if the source is empty.
24    IsEmpty,
25    /// Evaluates true if the source's value matches the evaluation parameter.
26    Equal(String),
27    /// Evaluates true if the source's value is different from the evaluation parameter.
28    NotEqual(String),
29}
30
31/// An action to apply to the target if the source evaluates true.
32#[derive(Clone, Copy, Eq, PartialEq)]
33pub enum Action {
34    /// If the evaluation is true for the source, the target is hidden, otherwise it is shown.
35    Hide,
36    /// If the evaluation is false for the source, the target is shown, otherwise it is hidden.
37    Show,
38}
39
40pub struct DependencyState {
41    /// The latest evaluation value for each dependency.
42    evaluation_states: HashMap<DependencyId, bool>,
43    /// Maps a dependency to its source (step, control) indices.
44    evaluation_sources: HashMap<DependencyId, (usize, usize)>,
45}
46
47impl DependencyState {
48    pub(crate) fn new() -> Self {
49        Self {
50            evaluation_states: HashMap::new(),
51            evaluation_sources: HashMap::new(),
52        }
53    }
54
55    pub(crate) fn register_evaluation(&mut self, id: &DependencyId, step: usize, control: usize) {
56        self.evaluation_sources.insert(*id, (step, control));
57    }
58
59    pub(crate) fn get_source(&self, id: &DependencyId) -> (usize, usize) {
60        *self.evaluation_sources.get(id).unwrap()
61    }
62
63    pub(crate) fn update_evaluation(&mut self, id: &DependencyId, value: bool) {
64        self.evaluation_states.insert(*id, value);
65    }
66
67    pub(crate) fn get_evaluation(&self, id: &DependencyId) -> bool {
68        *self.evaluation_states.get(id).unwrap_or(&false)
69    }
70}