egui/cache/
frame_publisher.rs

1use std::hash::Hash;
2
3use super::CacheTrait;
4
5/// Stores a key:value pair for the duration of this frame and the next.
6pub struct FramePublisher<Key: Eq + Hash, Value> {
7    generation: u32,
8    cache: ahash::HashMap<Key, (u32, Value)>,
9}
10
11impl<Key: Eq + Hash, Value> Default for FramePublisher<Key, Value> {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl<Key: Eq + Hash, Value> FramePublisher<Key, Value> {
18    pub fn new() -> Self {
19        Self {
20            generation: 0,
21            cache: Default::default(),
22        }
23    }
24
25    /// Publish the value. It will be available for the duration of this and the next frame.
26    pub fn set(&mut self, key: Key, value: Value) {
27        self.cache.insert(key, (self.generation, value));
28    }
29
30    /// Retrieve a value if it was published this or the previous frame.
31    pub fn get(&self, key: &Key) -> Option<&Value> {
32        self.cache.get(key).map(|(_, value)| value)
33    }
34
35    /// Must be called once per frame to clear the cache.
36    pub fn evict_cache(&mut self) {
37        let current_generation = self.generation;
38        self.cache.retain(|_key, cached| {
39            cached.0 == current_generation // only keep those that were published this frame
40        });
41        self.generation = self.generation.wrapping_add(1);
42    }
43}
44
45impl<Key, Value> CacheTrait for FramePublisher<Key, Value>
46where
47    Key: 'static + Eq + Hash + Send + Sync,
48    Value: 'static + Send + Sync,
49{
50    fn update(&mut self) {
51        self.evict_cache();
52    }
53
54    fn len(&self) -> usize {
55        self.cache.len()
56    }
57
58    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
59        self
60    }
61}