Skip to main content

euv_core/reactive/selector/
impl.rs

1use super::*;
2
3/// Core mixing helper for `SelectorFxHasher`.
4impl SelectorFxHasher {
5    /// Mixes a 64-bit word into the running FxHash state.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable hasher reference.
10    /// - `u64` - Word to fold into the hash accumulator.
11    #[inline(always)]
12    fn mix_word(&mut self, word: u64) {
13        let Self { hash } = self;
14        *hash = (hash.rotate_left(5) ^ word).wrapping_mul(FX_HASH_MULTIPLIER);
15    }
16}
17
18/// Fast non-cryptographic `Hasher` implementation for `SelectorFxHasher`.
19impl Hasher for SelectorFxHasher {
20    /// Finalizes and returns the 64-bit hash digest.
21    ///
22    /// # Arguments
23    ///
24    /// - `&Self` - Hasher reference.
25    ///
26    /// # Returns
27    ///
28    /// - `u64` - Final 64-bit FxHash digest.
29    #[inline(always)]
30    fn finish(&self) -> u64 {
31        let Self { hash } = *self;
32        hash
33    }
34
35    /// Feeds an arbitrary byte slice into the FxHash accumulator in 8/4/2/1-byte chunks.
36    ///
37    /// # Arguments
38    ///
39    /// - `&Self` - Mutable hasher reference.
40    /// - `&[u8]` - Input byte slice.
41    #[inline]
42    fn write(&mut self, mut bytes: &[u8]) {
43        while bytes.len() >= 8 {
44            let chunk: [u8; 8] = [
45                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
46            ];
47            self.mix_word(u64::from_ne_bytes(chunk));
48            bytes = &bytes[8..];
49        }
50        if bytes.len() >= 4 {
51            let chunk: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
52            self.mix_word(u64::from(u32::from_ne_bytes(chunk)));
53            bytes = &bytes[4..];
54        }
55        if bytes.len() >= 2 {
56            let chunk: [u8; 2] = [bytes[0], bytes[1]];
57            self.mix_word(u64::from(u16::from_ne_bytes(chunk)));
58            bytes = &bytes[2..];
59        }
60        if let Some(&last) = bytes.first() {
61            self.mix_word(u64::from(last));
62        }
63    }
64
65    /// Feeds a `u8` directly into the FxHash accumulator.
66    ///
67    /// # Arguments
68    ///
69    /// - `&Self` - Mutable hasher reference.
70    /// - `u8` - Input byte.
71    #[inline(always)]
72    fn write_u8(&mut self, i: u8) {
73        self.mix_word(u64::from(i));
74    }
75
76    /// Feeds a `u16` directly into the FxHash accumulator.
77    ///
78    /// # Arguments
79    ///
80    /// - `&Self` - Mutable hasher reference.
81    /// - `u16` - Input 16-bit integer.
82    #[inline(always)]
83    fn write_u16(&mut self, i: u16) {
84        self.mix_word(u64::from(i));
85    }
86
87    /// Feeds a `u32` directly into the FxHash accumulator.
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Mutable hasher reference.
92    /// - `u32` - Input 32-bit integer.
93    #[inline(always)]
94    fn write_u32(&mut self, i: u32) {
95        self.mix_word(u64::from(i));
96    }
97
98    /// Feeds a `u64` directly into the FxHash accumulator.
99    ///
100    /// # Arguments
101    ///
102    /// - `&Self` - Mutable hasher reference.
103    /// - `u64` - Input 64-bit integer.
104    #[inline(always)]
105    fn write_u64(&mut self, i: u64) {
106        self.mix_word(i);
107    }
108
109    /// Feeds a `usize` directly into the FxHash accumulator.
110    ///
111    /// # Arguments
112    ///
113    /// - `&Self` - Mutable hasher reference.
114    /// - `usize` - Input pointer-sized integer.
115    #[inline(always)]
116    fn write_usize(&mut self, i: usize) {
117        self.mix_word(i as u64);
118    }
119
120    /// Feeds an `i32` directly into the FxHash accumulator.
121    ///
122    /// # Arguments
123    ///
124    /// - `&Self` - Mutable hasher reference.
125    /// - `i32` - Input signed 32-bit integer.
126    #[inline(always)]
127    fn write_i32(&mut self, i: i32) {
128        self.mix_word(i as u64);
129    }
130
131    /// Feeds an `i64` directly into the FxHash accumulator.
132    ///
133    /// # Arguments
134    ///
135    /// - `&Self` - Mutable hasher reference.
136    /// - `i64` - Input signed 64-bit integer.
137    #[inline(always)]
138    fn write_i64(&mut self, i: i64) {
139        self.mix_word(i as u64);
140    }
141
142    /// Feeds an `isize` directly into the FxHash accumulator.
143    ///
144    /// # Arguments
145    ///
146    /// - `&Self` - Mutable hasher reference.
147    /// - `isize` - Input signed pointer-sized integer.
148    #[inline(always)]
149    fn write_isize(&mut self, i: isize) {
150        self.mix_word(i as u64);
151    }
152}
153
154/// Fast open-addressed hash table operations for `SelectorTable<K>`.
155impl<K> SelectorTable<K>
156where
157    K: Eq + Hash,
158{
159    /// Creates an empty table with zero heap allocations until the first insert.
160    ///
161    /// # Returns
162    ///
163    /// - `Self` - Empty selector lookup table.
164    #[must_use]
165    #[inline(always)]
166    pub(crate) fn new() -> Self {
167        Self {
168            entries: Vec::new(),
169            len: 0,
170        }
171    }
172
173    /// Computes the 64-bit FxHash digest for `key`.
174    ///
175    /// # Arguments
176    ///
177    /// - `&K` - Key reference to hash.
178    ///
179    /// # Returns
180    ///
181    /// - `u64` - Computed 64-bit hash value.
182    #[must_use]
183    #[inline(always)]
184    pub(crate) fn hash_key(key: &K) -> u64 {
185        let mut hasher: SelectorFxHasher = SelectorFxHasher::default();
186        key.hash(&mut hasher);
187        hasher.finish()
188    }
189
190    /// Looks up the `Signal<bool>` registered for `key`.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Table reference.
195    /// - `&K` - Key to look up.
196    ///
197    /// # Returns
198    ///
199    /// - `Option<Signal<bool>>` - Registered signal if present.
200    #[must_use]
201    #[inline(always)]
202    pub(crate) fn get(&self, key: &K) -> Option<Signal<bool>> {
203        let Self { entries, .. } = self;
204        if entries.is_empty() {
205            return None;
206        }
207        let hash: u64 = Self::hash_key(key);
208        self.get_with_hash(key, hash)
209    }
210
211    /// Looks up `key` using a precomputed FxHash digest `hash`.
212    ///
213    /// # Arguments
214    ///
215    /// - `&Self` - Table reference.
216    /// - `&K` - Key to look up.
217    /// - `u64` - Precomputed 64-bit FxHash digest of `key`.
218    ///
219    /// # Returns
220    ///
221    /// - `Option<Signal<bool>>` - Registered signal if present.
222    #[must_use]
223    #[inline(always)]
224    pub(crate) fn get_with_hash(&self, key: &K, hash: u64) -> Option<Signal<bool>> {
225        let Self { entries, .. } = self;
226        let cap: usize = entries.len();
227        if cap == 0 {
228            return None;
229        }
230        let mask: usize = cap - 1;
231        let mut idx: usize = (hash as usize) & mask;
232        loop {
233            let slot: &SelectorEntry<K> = entries[idx].as_ref()?;
234            if slot.hash == hash && slot.key == *key {
235                return Some(slot.signal);
236            }
237            idx = (idx + 1) & mask;
238        }
239    }
240
241    /// Inserts or updates `(key, signal)` using a precomputed FxHash digest `hash`.
242    ///
243    /// # Arguments
244    ///
245    /// - `&Self` - Mutable table reference.
246    /// - `K` - Key to insert.
247    /// - `u64` - Precomputed 64-bit FxHash digest of `key`.
248    /// - `Signal<bool>` - Boolean selection signal for `key`.
249    pub(crate) fn insert_with_hash(&mut self, key: K, hash: u64, signal: Signal<bool>) {
250        let Self { entries, len } = self;
251        let cur_cap: usize = entries.len();
252        if cur_cap == 0 {
253            *entries = (0..SELECTOR_INITIAL_BUCKETS).map(|_: usize| None).collect();
254        } else if (*len + 1) * 10 >= cur_cap * 7 {
255            let next_cap: usize = cur_cap.saturating_mul(2);
256            let mut next_entries: Vec<Option<SelectorEntry<K>>> =
257                (0..next_cap).map(|_: usize| None).collect();
258            let next_mask: usize = next_cap - 1;
259            for entry in entries.drain(..).flatten() {
260                let mut idx: usize = (entry.hash as usize) & next_mask;
261                while next_entries[idx].is_some() {
262                    idx = (idx + 1) & next_mask;
263                }
264                next_entries[idx] = Some(entry);
265            }
266            *entries = next_entries;
267        }
268        let mask: usize = entries.len() - 1;
269        let mut idx: usize = (hash as usize) & mask;
270        loop {
271            match &mut entries[idx] {
272                Some(slot) => {
273                    if slot.hash == hash && slot.key == key {
274                        slot.signal = signal;
275                        return;
276                    }
277                    idx = (idx + 1) & mask;
278                }
279                slot @ None => {
280                    *slot = Some(SelectorEntry { hash, key, signal });
281                    *len += 1;
282                    return;
283                }
284            }
285        }
286    }
287
288    /// Drains all stored per-key signals and resets the table to empty.
289    ///
290    /// # Arguments
291    ///
292    /// - `&Self` - Mutable table reference.
293    ///
294    /// # Returns
295    ///
296    /// - `Vec<Signal<bool>>` - All previously registered boolean selection signals.
297    pub(crate) fn drain_signals(&mut self) -> Vec<Signal<bool>> {
298        let Self { entries, len } = self;
299        let mut out: Vec<Signal<bool>> = Vec::with_capacity(*len);
300        for entry in entries.drain(..).flatten() {
301            out.push(entry.signal);
302        }
303        *len = 0;
304        out
305    }
306}
307
308/// Keyed O(1) selection operations for `Selector<K>`.
309impl<K> Selector<K>
310where
311    K: Clone + Eq + Hash + 'static,
312{
313    /// Creates a selector tracking the key returned by `source`.
314    ///
315    /// # Arguments
316    ///
317    /// - `F` - Reactive key producer closure.
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Selector instance supporting O(1) per-key selection checks.
322    #[must_use]
323    pub fn new<F>(mut source: F) -> Self
324    where
325        F: FnMut() -> K + 'static,
326    {
327        let state: Rc<RefCell<SelectorState<K>>> = Rc::new(RefCell::new(SelectorState {
328            active_key: None,
329            active_sig: None,
330            table: SelectorTable::new(),
331        }));
332        let state_clone: Rc<RefCell<SelectorState<K>>> = state.clone();
333        let watcher: Effect = Effect::new(move || {
334            let next_key: K = source();
335            let (old_id, new_id): (Option<SignalId>, Option<SignalId>) = state_clone
336                .try_borrow_mut()
337                .ok()
338                .map(|mut guard: RefMut<'_, SelectorState<K>>| {
339                    let SelectorState {
340                        active_key,
341                        active_sig,
342                        table,
343                    } = &mut *guard;
344                    if active_key.as_ref() == Some(&next_key) {
345                        return (None, None);
346                    }
347                    let old_sig: Option<Signal<bool>> = *active_sig;
348                    let new_sig: Option<Signal<bool>> = table.get(&next_key);
349                    *active_key = Some(next_key);
350                    *active_sig = new_sig;
351                    (
352                        old_sig.map(|sig: Signal<bool>| sig.id()),
353                        new_sig.map(|sig: Signal<bool>| sig.id()),
354                    )
355                })
356                .unwrap_or((None, None));
357            if old_id.is_none() && new_id.is_none() {
358                return;
359            }
360            let should_flush: bool = with_runtime(
361                |rt: &mut ReactiveRuntime| rt.write_selector_pair(old_id, new_id),
362                false,
363            );
364            if should_flush {
365                flush_effects();
366            }
367        });
368        Self { state, watcher }
369    }
370
371    /// Reactively returns whether `key` is currently selected, subscribing only to `key`.
372    ///
373    /// # Arguments
374    ///
375    /// - `&Self` - Selector reference.
376    /// - `K` - Key to test for active selection.
377    ///
378    /// # Returns
379    ///
380    /// - `bool` - True when `key` equals the active selected key.
381    #[must_use]
382    pub fn is_selected(&self, key: K) -> bool {
383        let Self { state, .. } = self;
384        let hash: u64 = SelectorTable::<K>::hash_key(&key);
385        let sig: Signal<bool> = match state.try_borrow_mut() {
386            Ok(mut guard) => {
387                let SelectorState {
388                    active_key,
389                    active_sig,
390                    table,
391                } = &mut *guard;
392                if let Some(found) = table.get_with_hash(&key, hash) {
393                    found
394                } else {
395                    let is_active: bool = active_key.as_ref().is_some_and(|cur: &K| *cur == key);
396                    let created: Signal<bool> = Signal::new(is_active);
397                    table.insert_with_hash(key, hash, created);
398                    if is_active {
399                        *active_sig = Some(created);
400                    }
401                    created
402                }
403            }
404            Err(_) => return false,
405        };
406        sig.get()
407    }
408
409    /// Disposes the selector's watcher effect and per-key signals.
410    ///
411    /// # Arguments
412    ///
413    /// - `&Self` - Selector to dispose.
414    pub fn dispose(&self) {
415        let Self { state, watcher } = self;
416        watcher.dispose();
417        let signals: Vec<Signal<bool>> = state
418            .try_borrow_mut()
419            .ok()
420            .map(|mut guard: RefMut<'_, SelectorState<K>>| {
421                let SelectorState {
422                    active_key,
423                    active_sig,
424                    table,
425                } = &mut *guard;
426                *active_key = None;
427                *active_sig = None;
428                table.drain_signals()
429            })
430            .unwrap_or_default();
431        if !signals.is_empty() {
432            with_runtime(
433                |rt: &mut ReactiveRuntime| {
434                    for sig in signals.into_iter() {
435                        let _: SignalSlot = rt.dispose_signal(sig.id());
436                    }
437                },
438                (),
439            );
440        }
441    }
442}