Skip to content

Commit

Permalink
Add egui::cache::FramePublisher
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk committed Dec 3, 2024
1 parent d97b225 commit 9922183
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
61 changes: 61 additions & 0 deletions crates/egui/src/cache/frame_publisher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::hash::Hash;

use super::CacheTrait;

/// Stores a key:value pair for the duration of this frame and the next.
pub struct FramePublisher<Key: Eq + Hash, Value> {
generation: u32,
cache: ahash::HashMap<Key, (u32, Value)>,
}

impl<Key: Eq + Hash, Value> Default for FramePublisher<Key, Value> {
fn default() -> Self {
Self::new()
}
}

impl<Key: Eq + Hash, Value> FramePublisher<Key, Value> {
pub fn new() -> Self {
Self {
generation: 0,
cache: Default::default(),
}
}

/// Publish the value. It will be available for the duration of the and the next frame.
pub fn set(&mut self, key: Key, value: Value) {
self.cache.insert(key, (self.generation, value));
}

/// Retrieve a value if it was publiushed this or the previous frame.
pub fn get(&self, key: &Key) -> Option<&Value> {
self.cache.get(key).map(|(_, value)| value)
}

/// Must be called once per frame to clear the cache.
pub fn evict_cache(&mut self) {
let current_generation = self.generation;
self.cache.retain(|_key, cached| {
cached.0 == current_generation // only keep those that were used this frame
});
self.generation = self.generation.wrapping_add(1);
}
}

impl<Key, Value> CacheTrait for FramePublisher<Key, Value>
where
Key: 'static + Eq + Hash + Send + Sync,
Value: 'static + Send + Sync,
{
fn update(&mut self) {
self.evict_cache();
}

fn len(&self) -> usize {
self.cache.len()
}

fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
2 changes: 2 additions & 0 deletions crates/egui/src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
mod cache_storage;
mod cache_trait;
mod frame_cache;
mod frame_publisher;

pub use cache_storage::CacheStorage;
pub use cache_trait::CacheTrait;
pub use frame_cache::{ComputerMut, FrameCache};
pub use frame_publisher::FramePublisher;

0 comments on commit 9922183

Please sign in to comment.