Skip to content

Commit

Permalink
Fix UI data() read mutability (#2742)
Browse files Browse the repository at this point in the history
* Make `IdTypeMap::get_temp` use immutable `self`

* Add note to `IdTypeMap::get_persisted` about mutability

* Add mention of `ArcSwap` in `IdTypeMap` docs

* Fix formatting with `cargo fmt`
  • Loading branch information
IS2511 authored Mar 29, 2023
1 parent 2946ed7 commit 74d43bf
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions crates/egui/src/util/id_type_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ impl Element {
}
}

#[inline]
pub(crate) fn get_temp<T: 'static>(&self) -> Option<&T> {
match self {
Self::Value { value, .. } => value.downcast_ref(),
Self::Serialized { .. } => None,
}
}

#[inline]
pub(crate) fn get_mut_temp<T: 'static>(&mut self) -> Option<&mut T> {
match self {
Expand Down Expand Up @@ -301,6 +309,7 @@ use crate::Id;
///
/// Values are cloned when read, so keep them small and light.
/// If you want to store something bigger, wrap them in `Arc<Mutex<…>>`.
/// Also try `Arc<ArcSwap<…>>`.
///
/// Values can either be "persisted" (serializable) or "temporary" (cleared when egui is shut down).
///
Expand Down Expand Up @@ -355,16 +364,16 @@ impl IdTypeMap {
///
/// The call clones the value (if found), so make sure it is cheap to clone!
#[inline]
pub fn get_temp<T: 'static + Clone>(&mut self, id: Id) -> Option<T> {
pub fn get_temp<T: 'static + Clone>(&self, id: Id) -> Option<T> {
let hash = hash(TypeId::of::<T>(), id);
self.0
.get_mut(&hash)
.and_then(|x| x.get_mut_temp())
.cloned()
self.0.get(&hash).and_then(|x| x.get_temp()).cloned()
}

/// Read a value, optionally deserializing it if available.
///
/// NOTE: A mutable `self` is needed because internally this deserializes on first call
/// and caches the result (caching requires self-mutability).
///
/// The call clones the value (if found), so make sure it is cheap to clone!
#[inline]
pub fn get_persisted<T: SerializableAny>(&mut self, id: Id) -> Option<T> {
Expand Down

0 comments on commit 74d43bf

Please sign in to comment.