dptree/handler/description/interest_set.rs
1use crate::HandlerDescription;
2
3use std::{
4 collections::HashSet,
5 hash::{BuildHasher, Hash, RandomState},
6};
7
8/// Description for a handler that describes what event kinds are interesting to
9/// the handler.
10///
11/// This can be useful if you can filter events before they are passed to
12/// `dptree`. In this case you should keep updates that are in the `observed`
13/// set.
14#[derive(Debug, Clone)]
15pub struct InterestSet<K, S = RandomState> {
16 /// Event kinds that are of interested for a given handler.
17 ///
18 /// I.e. the ones that can cause meaningful side-effects.
19 pub observed: HashSet<K, S>,
20
21 /// Event kinds that can be observed by handlers chained to this one.
22 pub filtered: HashSet<K, S>,
23}
24
25/// An event kind that can be used with [`InterestSet`].
26///
27/// Usually this would be implemented by a field-less enumeration of all update
28/// kinds.
29pub trait EventKind<S = RandomState>: Sized {
30 /// Set of all event kinds.
31 fn full_set() -> HashSet<Self, S>;
32
33 /// An empty set.
34 fn empty_set() -> HashSet<Self, S>;
35}
36
37impl<K: EventKind<S>, S> InterestSet<K, S> {
38 /// Constructs an [`InterestSet`] for a filter that allows to pass through
39 /// it only updates with kinds in the `filtered` set.
40 ///
41 /// Note that the filter should not have observable side-effects, for
42 /// example:
43 /// ```
44 /// use dptree::{description::{InterestSet, EventKind}, filter_with_description};
45 /// use std::collections::HashSet;
46 ///
47 /// # enum K {} impl EventKind for K { fn full_set() -> HashSet<Self> { HashSet::default() } fn empty_set() -> HashSet<Self> { HashSet::default() } }
48 /// # let _: dptree::Handler<(), InterestSet<K>> =
49 /// filter_with_description(InterestSet::new_filter(HashSet::new()), || {
50 /// println!("Filter called!"); // <-- bad
51 ///
52 /// false
53 /// });
54 ///
55 /// # #[derive(Clone)] struct Db; impl Db { fn fetch_enabled(&self) -> bool { false } }
56 /// # let _: dptree::Handler<(), InterestSet<K>> =
57 /// filter_with_description(InterestSet::new_filter(HashSet::new()), |db: Db| {
58 /// let pass = db.fetch_enabled(); // <-- fine
59 ///
60 /// pass
61 /// });
62 /// ```
63 pub fn new_filter(filtered: HashSet<K, S>) -> Self {
64 // We assume that well behaved filters don't observe anything (filters should
65 // only filter!).
66 Self { observed: K::empty_set(), filtered }
67 }
68}
69
70impl<T, S> HandlerDescription for InterestSet<T, S>
71where
72 T: EventKind<S> + Eq + Hash + Clone,
73 S: BuildHasher + Clone,
74 T: Send + Sync + 'static,
75 S: Send + Sync + 'static,
76{
77 fn entry() -> Self {
78 // Entry does not observe anything and allows everything.
79 Self { observed: T::empty_set(), filtered: T::full_set() }
80 }
81
82 fn user_defined() -> Self {
83 // We don't know what user defined code does, so we assume the most forgiving
84 // case: it observes everything and allows everything.
85 //
86 // Were we to choose anything else, there would be user code that would be
87 // broken.
88 Self { observed: T::full_set(), filtered: T::full_set() }
89 }
90
91 fn endpoint() -> Self {
92 // Endpoint observes everything (again, as per the same reasoning as
93 // `user_defined`), but does not allow anything to pass through (it's
94 // the last handler).
95 Self { observed: T::full_set(), filtered: T::empty_set() }
96 }
97
98 fn merge_chain(&self, other: &Self) -> Self {
99 let Self { observed: l_obs, filtered: l_flt } = self;
100 let Self { observed: r_obs, filtered: r_flt } = other;
101
102 // Second handler can only observe things that were passed through by the first
103 // one.
104 let observed = {
105 let hasher = l_obs.hasher().clone();
106 let mut tmp = HashSet::with_hasher(hasher);
107
108 tmp.extend(l_obs.iter().cloned());
109 tmp.extend(l_flt.intersection(r_obs).cloned());
110 tmp
111 };
112
113 // If we chain two filters together, we are only passing through events that can
114 // pass both of them.
115 let filtered = {
116 let hasher = l_flt.hasher().clone();
117 let mut tmp = HashSet::with_hasher(hasher);
118
119 tmp.extend(l_flt.intersection(r_flt).cloned());
120 tmp
121 };
122
123 Self { filtered, observed }
124 }
125
126 fn merge_branch(&self, other: &Self) -> Self {
127 let Self { observed: l_obs, filtered: l_flt } = self;
128 let Self { observed: r_obs, filtered: _ } = other;
129
130 // Second handler can only observe things that were passed through by the first
131 // one.
132 let observed = {
133 let hasher = l_obs.hasher().clone();
134 let mut tmp = HashSet::with_hasher(hasher);
135
136 tmp.extend(l_obs.iter().cloned());
137 tmp.extend(l_flt.intersection(r_obs).cloned());
138 tmp
139 };
140
141 // Even if second filter did not pass something through, the execution still
142 // continues.
143 let filtered = l_flt.clone();
144
145 Self { observed, filtered }
146 }
147}
148
149impl<K: Hash + Eq, S: BuildHasher> Eq for InterestSet<K, S> {}
150
151impl<K: Hash + Eq, S: BuildHasher> PartialEq for InterestSet<K, S> {
152 fn eq(&self, other: &Self) -> bool {
153 let Self { observed: l_obs, filtered: l_flt } = self;
154 let Self { observed: r_obs, filtered: r_flt } = other;
155
156 l_obs == r_obs && l_flt == r_flt
157 }
158}