1
0
mirror of https://github.com/emilk/egui.git synced 2026-06-26 22:53:14 -04:00

Make FrameCache::get return a reference instead of cloning the cached value (#7834)

This is a breaking change.

- Enables using `FrameCache` in cases where the cached value cannot be
cloned.
- Improves use cases where only a reference to the cached value is
needed.
- If the user needs an owned value, they can clone it themselves.

Adding a `get_ref` method instead of changing `get` would avoid the
breaking change, but I didn't want to do so because it is kind of
expected for `get` to return `&V` when querying a collection.
This commit is contained in:
Trương Hoàng Long
2026-01-11 16:31:58 +01:00
committed by GitHub
parent a9e92525c0
commit 7fb4627dad
4 changed files with 7 additions and 7 deletions

View File

@@ -19,7 +19,7 @@ use super::CacheTrait;
///
/// # let mut cache_storage = CacheStorage::default();
/// let mut cache = cache_storage.cache::<CharCountCache<'_>>();
/// assert_eq!(cache.get("hello"), 5);
/// assert_eq!(*cache.get("hello"), 5);
/// ```
#[derive(Default)]
pub struct CacheStorage {

View File

@@ -46,10 +46,9 @@ impl<Value, Computer> FrameCache<Value, Computer> {
impl<Value, Computer> FrameCache<Value, Computer> {
/// Get from cache (if the same key was used last frame)
/// or recompute and store in the cache.
pub fn get<Key>(&mut self, key: Key) -> Value
pub fn get<Key>(&mut self, key: Key) -> &Value
where
Key: Copy + std::hash::Hash,
Value: Clone,
Computer: ComputerMut<Key, Value>,
{
let hash = crate::util::hash(key);
@@ -58,12 +57,12 @@ impl<Value, Computer> FrameCache<Value, Computer> {
std::collections::hash_map::Entry::Occupied(entry) => {
let cached = entry.into_mut();
cached.0 = self.generation;
cached.1.clone()
&cached.1
}
std::collections::hash_map::Entry::Vacant(entry) => {
let value = self.computer.compute(key);
entry.insert((self.generation, value.clone()));
value
let inserted = entry.insert((self.generation, value));
&inserted.1
}
}
}

View File

@@ -68,7 +68,7 @@ pub struct Memory {
/// # let mut ctx = egui::Context::default();
/// ctx.memory_mut(|mem| {
/// let cache = mem.caches.cache::<CharCountCache<'_>>();
/// assert_eq!(cache.get("hello"), 5);
/// assert_eq!(*cache.get("hello"), 5);
/// });
/// ```
#[cfg_attr(feature = "persistence", serde(skip))]

View File

@@ -116,6 +116,7 @@ fn highlight_inner(
mem.caches
.cache::<HighlightCache>()
.get((&font_id, theme, code, language, settings))
.clone()
})
}