1use super::*;
3use std::cell::Cell;
4use std::hash::{BuildHasher, Hash, RandomState};
5
6struct Channel<K> {
7 id: u64,
8 owner: Key,
9 key: K,
10 value: Cage<bool>,
11 selected: Cell<bool>,
12}
13struct Control<K: 'static> {
14 source: Cage<Option<K>>,
15 owner: OwnerHandle,
16 hash: RandomState,
17 next: Cell<u64>,
18 channels: RefCell<HashMap<u64, Vec<Rc<Channel<K>>>>>,
19 read_ahead: RefCell<BTreeMap<u64, Weak<Channel<K>>>>,
22 previous: RefCell<Rc<Option<K>>>,
23}
24
25pub struct Selector<K: 'static> {
47 control: Cage<Rc<Control<K>>>,
48}
49pub struct Selected<K: 'static> {
53 control: Weak<Control<K>>,
54 channel: Weak<Channel<K>>,
55}
56impl<K> Clone for Selected<K> {
57 fn clone(&self) -> Self {
58 Self {
59 control: self.control.clone(),
60 channel: self.channel.clone(),
61 }
62 }
63}
64impl<K: Eq + 'static> Selected<K> {
65 pub fn get(&self) -> bool {
66 self.try_get().expect("read a live selection channel")
67 }
68 pub fn try_get(&self) -> Result<bool, AccessError> {
69 let control = self.control.upgrade().ok_or(AccessError::Disposed)?;
70 let channel = self.channel.upgrade().ok_or(AccessError::Disposed)?;
71 channel.value.try_with(|_| ())?;
74 let selected = control.source.try_with_untracked(|selected| {
75 fields::project(|| Ok(selected.as_ref() == Some(&channel.key)))
76 })??;
77 if !channel.value.is_alive() {
78 return Err(AccessError::Disposed);
79 }
80 if selected != channel.selected.get() {
81 control
82 .read_ahead
83 .borrow_mut()
84 .entry(channel.id)
85 .or_insert_with(|| Rc::downgrade(&channel));
86 }
87 Ok(selected)
88 }
89}
90impl<K> Copy for Selector<K> {}
91impl<K> Clone for Selector<K> {
92 fn clone(&self) -> Self {
93 *self
94 }
95}
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub struct SelectorStats {
98 pub buckets: usize,
99 pub channels: usize,
100 pub read_ahead: usize,
101}
102impl Owner {
103 pub fn selector<K: Clone + Eq + Hash + 'static>(
104 &self,
105 source: Cage<Option<K>>,
106 ) -> Result<Selector<K>, AccessError> {
107 self.check_write()?;
108 if source.runtime() != self.runtime {
109 return Err(AccessError::WrongRuntime);
110 }
111 let previous = Rc::new(source.try_with_untracked(Clone::clone)?);
112 self.check_write()?;
113 let control = Rc::new(Control {
114 source,
115 owner: self.handle(),
116 hash: RandomState::new(),
117 next: Cell::new(0),
118 channels: RefCell::new(HashMap::new()),
119 read_ahead: RefCell::new(BTreeMap::new()),
120 previous: RefCell::new(previous),
121 });
122 let selector = Selector {
123 control: self.cage(control.clone()),
124 };
125 let weak = Rc::downgrade(&control);
126 self.on_cleanup(move || {
127 if let Some(control) = weak.upgrade() {
128 let channels = std::mem::take(&mut *control.channels.borrow_mut());
129 control.read_ahead.borrow_mut().clear();
130 let previous = control.previous.replace(Rc::new(None));
131 for channel in channels.values().flatten() {
132 BindingId {
133 runtime: channel.value.handle.runtime,
134 key: channel.value.handle.key,
135 local: PhantomData,
136 }
137 .dispose();
138 }
139 drop((channels, previous));
140 }
141 })?;
142 self.structural(move || {
143 let Ok(next) = control.source.try_with(Clone::clone) else {
144 return;
145 };
146 control.publish(next).expect("pure selector key");
147 });
148 Ok(selector)
149 }
150}
151impl<K: Clone + Eq + Hash + 'static> Control<K> {
152 fn publish(&self, next: Option<K>) -> Result<(), AccessError> {
153 let previous = self.previous.borrow().clone();
154 let same = fields::project(|| Ok(*previous == next))?;
155 let next = if same {
156 previous.clone()
157 } else {
158 Rc::new(next)
159 };
160 let mut candidates: Vec<(Rc<Channel<K>>, bool, bool)> = Vec::new();
161 let mut positions = HashMap::new();
162 if !same {
163 self.previous.replace(next.clone());
164 for (key, selected) in [
165 (previous.as_ref().as_ref(), false),
166 (next.as_ref().as_ref(), true),
167 ] {
168 let Some(key) = key else { continue };
169 for channel in self.matches(key)? {
170 positions.insert(channel.id, candidates.len());
171 candidates.push((channel, selected, false));
172 }
173 }
174 }
175 let pending = std::mem::take(&mut *self.read_ahead.borrow_mut());
179 for (id, weak) in pending {
180 let Some(channel) = weak.upgrade() else {
181 continue;
182 };
183 if let Some(&position) = positions.get(&id) {
184 candidates[position].2 = true;
185 } else {
186 let selected =
187 fields::project(|| Ok(next.as_ref().as_ref() == Some(&channel.key)))?;
188 positions.insert(id, candidates.len());
189 candidates.push((channel, selected, true));
190 }
191 }
192 for (channel, selected, force) in candidates {
193 if channel.value.is_alive()
194 && (force || channel.selected.get() != selected)
195 && channel.value.try_revise(|value| *value = selected).is_ok()
196 {
197 channel.selected.set(selected);
198 }
199 }
200 Ok(())
201 }
202 fn hash(&self, key: &K) -> Result<u64, AccessError> {
203 fields::project(|| Ok(self.hash.hash_one(key)))
204 }
205 fn matches(&self, key: &K) -> Result<Vec<Rc<Channel<K>>>, AccessError> {
206 let hash = self.hash(key)?;
207 let candidates = self
208 .channels
209 .borrow()
210 .get(&hash)
211 .cloned()
212 .unwrap_or_default();
213 candidates
214 .into_iter()
215 .filter_map(
216 |channel| match fields::project(|| Ok(channel.key == *key)) {
217 Ok(true) => Some(Ok(channel)),
218 Ok(false) => None,
219 Err(error) => Some(Err(error)),
220 },
221 )
222 .collect()
223 }
224 fn remove(&self, hash: u64, id: u64) {
225 self.read_ahead.borrow_mut().remove(&id);
226 let removed = {
227 let mut channels = self.channels.borrow_mut();
228 let Some(bucket) = channels.get_mut(&hash) else {
229 return;
230 };
231 let Some(index) = bucket.iter().position(|channel| channel.id == id) else {
232 return;
233 };
234 let removed = bucket.swap_remove(index);
235 if bucket.is_empty() {
236 channels.remove(&hash);
237 }
238 removed
239 };
240 drop(removed);
241 }
242}
243impl<K: Clone + Eq + Hash + 'static> Selector<K> {
244 pub fn selected(self, key: K) -> Selected<K> {
245 self.try_selected(key)
246 .expect("select a key under a live non-pure Owner")
247 }
248 pub fn try_selected(self, key: K) -> Result<Selected<K>, AccessError> {
249 allow_creation()?;
250 let control = self.control.try_with_untracked(Rc::clone)?;
251 let owner = CONSTRUCTING.with_borrow(|stack| {
252 stack
253 .last()
254 .copied()
255 .map(|(runtime, key)| OwnerHandle { runtime, key })
256 .unwrap_or(control.owner)
257 });
258 if owner.runtime != control.owner.runtime {
259 return Err(AccessError::WrongRuntime);
260 }
261 let hash = control.hash(&key)?;
262 let matches = control.matches(&key)?;
263 let state = lookup(owner.runtime)?;
266 if !self.control.is_alive() || state.borrow().owners.get(owner.key).is_none() {
267 return Err(AccessError::Disposed);
268 }
269 if let Some(channel) = matches
270 .into_iter()
271 .find(|channel| channel.owner == owner.key)
272 {
273 return Ok(Selected {
274 control: Rc::downgrade(&control),
275 channel: Rc::downgrade(&channel),
276 });
277 }
278 control.source.try_with_untracked(|_| ())?;
279 let previous = control.previous.borrow().clone();
283 let selected = fields::project(|| Ok(previous.as_ref().as_ref() == Some(&key)))?;
284 if !self.control.is_alive() || state.borrow().owners.get(owner.key).is_none() {
285 return Err(AccessError::Disposed);
286 }
287 let id = control.next.get();
288 control
289 .next
290 .set(id.checked_add(1).expect("selector channel ids exhausted"));
291 let value = make_cage(owner.runtime, owner.key, selected)?;
292 let channel = Rc::new(Channel {
293 id,
294 owner: owner.key,
295 key,
296 value,
297 selected: Cell::new(selected),
298 });
299 control
300 .channels
301 .borrow_mut()
302 .entry(hash)
303 .or_default()
304 .push(channel.clone());
305 let weak = Rc::downgrade(&control);
306 state
307 .borrow_mut()
308 .owners
309 .get_mut(owner.key)
310 .ok_or(AccessError::Disposed)?
311 .cleanup
312 .push(Box::new(move || {
313 if let Some(control) = weak.upgrade() {
314 control.remove(hash, id);
315 }
316 }));
317 Ok(Selected {
318 control: Rc::downgrade(&control),
319 channel: Rc::downgrade(&channel),
320 })
321 }
322 pub fn stats(self) -> Result<SelectorStats, AccessError> {
324 self.control.try_with_untracked(|control| {
325 let channels = control.channels.borrow();
326 SelectorStats {
327 buckets: channels.len(),
328 channels: channels.values().map(Vec::len).sum(),
329 read_ahead: control.read_ahead.borrow().len(),
330 }
331 })
332 }
333}