Skip to content

Commit 186362a

Browse files
optozoraxemilk
andauthored
Arbitrary data in Memory using Any, fix #255 (#257)
* init work * implement deferred deserialization * many improvements * rename `DataElement` -> `AnyMapElement` * make `data` in `Memory` as public field of type with public interface * make interface more rich * transform most unwraps to proper error handling * make `AnyMap` store by `TypeId`, so now individual type can be counted and reset * improve storing TypeId between different rust versions * rewrite system widgets to use AnyMap * refactor everything * replace `serde_json` -> `ron` * move `any_map` to module * separate `AnyMap` into `AnyMapId` and `serializable::AnyMapId` in order to not require `serde` traits in methods * add `AnyMap` and `serializable::AnyMap` that stores elements just by type, without `Id` * write documentation * change tooltips and color picker to use `Memory::data_temp` * fix bugs and docs * Apply suggestions from code review Co-authored-by: Emil Ernerfeldt <[email protected]> * rename `AnyMap` → `TypeMap` * rename `AnyMapId` → `AnyMap`, add generic <Key> to it * rename files `id_map` → `any_map` * move out usages from `serializable` mod * rename `ToDeserialize` → `Serialized` * fix bug with counting * add tests, and... * rename `reset` → `remove` * add function `remove_by_type` * format code * improve code * make identical interface for serialized and simple maps * make serialized maps serialized fully, without features by moving this into `Memory` struct with `#[cfg(feature = "persistence")]` under fields * move `serialized::TypeId` into `AnyMapElement` struct * fix pipeline and add one more test * update docs Co-authored-by: Emil Ernerfeldt <[email protected]>
1 parent 4ecf304 commit 186362a

23 files changed

+1221
-63
lines changed

Cargo.lock

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

egui/Cargo.toml

+5-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ include = [
2222
[dependencies]
2323
epaint = { version = "0.11.0", path = "../epaint", default-features = false }
2424
serde = { version = "1", features = ["derive", "rc"], optional = true }
25+
ron = { version = "0.6.4", optional = true }
2526

2627
[features]
2728
default = ["default_fonts", "single_threaded"]
@@ -30,8 +31,11 @@ default = ["default_fonts", "single_threaded"]
3031
# If you plan on specifying your own fonts you may disable this feature.
3132
default_fonts = ["epaint/default_fonts"]
3233

33-
persistence = ["serde", "epaint/persistence"]
34+
persistence = ["serde", "epaint/persistence", "ron"]
3435

3536
# Only needed if you plan to use the same egui::Context from multiple threads.
3637
single_threaded = ["epaint/single_threaded"]
3738
multi_threaded = ["epaint/multi_threaded"]
39+
40+
[dev-dependencies]
41+
serde_json = "1"

egui/src/any/any_map.rs

+205
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
use crate::any::element::{AnyMapElement, AnyMapTrait};
2+
use std::any::TypeId;
3+
use std::collections::HashMap;
4+
use std::hash::Hash;
5+
6+
/// Stores any object by `Key`.
7+
#[derive(Clone, Debug)]
8+
pub struct AnyMap<Key: Hash + Eq>(HashMap<Key, AnyMapElement>);
9+
10+
impl<Key: Hash + Eq> Default for AnyMap<Key> {
11+
fn default() -> Self {
12+
AnyMap(HashMap::new())
13+
}
14+
}
15+
16+
// ----------------------------------------------------------------------------
17+
18+
impl<Key: Hash + Eq> AnyMap<Key> {
19+
pub fn get<T: AnyMapTrait>(&mut self, key: &Key) -> Option<&T> {
20+
self.get_mut(key).map(|x| &*x)
21+
}
22+
23+
pub fn get_mut<T: AnyMapTrait>(&mut self, key: &Key) -> Option<&mut T> {
24+
self.0.get_mut(key)?.get_mut()
25+
}
26+
}
27+
28+
impl<Key: Hash + Eq> AnyMap<Key> {
29+
pub fn get_or_insert_with<T: AnyMapTrait>(
30+
&mut self,
31+
key: Key,
32+
or_insert_with: impl FnOnce() -> T,
33+
) -> &T {
34+
&*self.get_mut_or_insert_with(key, or_insert_with)
35+
}
36+
37+
pub fn get_or_default<T: AnyMapTrait + Default>(&mut self, key: Key) -> &T {
38+
self.get_or_insert_with(key, Default::default)
39+
}
40+
41+
pub fn get_mut_or_insert_with<T: AnyMapTrait>(
42+
&mut self,
43+
key: Key,
44+
or_insert_with: impl FnOnce() -> T,
45+
) -> &mut T {
46+
use std::collections::hash_map::Entry;
47+
match self.0.entry(key) {
48+
Entry::Vacant(vacant) => vacant
49+
.insert(AnyMapElement::new(or_insert_with()))
50+
.get_mut()
51+
.unwrap(), // this unwrap will never panic, because we insert correct type right now
52+
Entry::Occupied(occupied) => occupied.into_mut().get_mut_or_set_with(or_insert_with),
53+
}
54+
}
55+
56+
pub fn get_mut_or_default<T: AnyMapTrait + Default>(&mut self, key: Key) -> &mut T {
57+
self.get_mut_or_insert_with(key, Default::default)
58+
}
59+
}
60+
61+
impl<Key: Hash + Eq> AnyMap<Key> {
62+
pub fn insert<T: AnyMapTrait>(&mut self, key: Key, element: T) {
63+
self.0.insert(key, AnyMapElement::new(element));
64+
}
65+
66+
pub fn remove(&mut self, key: &Key) {
67+
self.0.remove(key);
68+
}
69+
70+
pub fn remove_by_type<T: AnyMapTrait>(&mut self) {
71+
let key = TypeId::of::<T>();
72+
self.0.retain(|_, v| v.type_id() != key);
73+
}
74+
75+
pub fn clear(&mut self) {
76+
self.0.clear();
77+
}
78+
}
79+
80+
impl<Key: Hash + Eq> AnyMap<Key> {
81+
/// You could use this function to find is there some leak or misusage.
82+
pub fn count<T: AnyMapTrait>(&mut self) -> usize {
83+
let key = TypeId::of::<T>();
84+
self.0.iter().filter(|(_, v)| v.type_id() == key).count()
85+
}
86+
87+
pub fn count_all(&mut self) -> usize {
88+
self.0.len()
89+
}
90+
}
91+
92+
// ----------------------------------------------------------------------------
93+
94+
#[cfg(test)]
95+
#[test]
96+
fn basic_usage() {
97+
#[derive(Debug, Clone, Eq, PartialEq, Default)]
98+
struct State {
99+
a: i32,
100+
}
101+
102+
let mut map: AnyMap<i32> = Default::default();
103+
104+
assert!(map.get::<State>(&0).is_none());
105+
map.insert(0, State { a: 42 });
106+
107+
assert_eq!(*map.get::<State>(&0).unwrap(), State { a: 42 });
108+
assert!(map.get::<State>(&1).is_none());
109+
map.get_mut::<State>(&0).unwrap().a = 43;
110+
assert_eq!(*map.get::<State>(&0).unwrap(), State { a: 43 });
111+
112+
map.remove(&0);
113+
assert!(map.get::<State>(&0).is_none());
114+
115+
assert_eq!(
116+
*map.get_or_insert_with(0, || State { a: 55 }),
117+
State { a: 55 }
118+
);
119+
map.remove(&0);
120+
assert_eq!(
121+
*map.get_mut_or_insert_with(0, || State { a: 56 }),
122+
State { a: 56 }
123+
);
124+
map.remove(&0);
125+
assert_eq!(*map.get_or_default::<State>(0), State { a: 0 });
126+
map.remove(&0);
127+
assert_eq!(*map.get_mut_or_default::<State>(0), State { a: 0 });
128+
}
129+
130+
#[cfg(test)]
131+
#[test]
132+
fn different_type_same_id() {
133+
#[derive(Debug, Clone, Eq, PartialEq, Default)]
134+
struct State {
135+
a: i32,
136+
}
137+
138+
let mut map: AnyMap<i32> = Default::default();
139+
140+
map.insert(0, State { a: 42 });
141+
142+
assert_eq!(*map.get::<State>(&0).unwrap(), State { a: 42 });
143+
assert!(map.get::<i32>(&0).is_none());
144+
145+
map.insert(0, 255i32);
146+
147+
assert_eq!(*map.get::<i32>(&0).unwrap(), 255);
148+
assert!(map.get::<State>(&0).is_none());
149+
}
150+
151+
#[cfg(test)]
152+
#[test]
153+
fn cloning() {
154+
#[derive(Debug, Clone, Eq, PartialEq, Default)]
155+
struct State {
156+
a: i32,
157+
}
158+
159+
let mut map: AnyMap<i32> = Default::default();
160+
161+
map.insert(0, State::default());
162+
map.insert(10, 10i32);
163+
map.insert(11, 11i32);
164+
165+
let mut cloned_map = map.clone();
166+
167+
map.insert(12, 12i32);
168+
map.insert(1, State { a: 10 });
169+
170+
assert_eq!(*cloned_map.get::<State>(&0).unwrap(), State { a: 0 });
171+
assert!(cloned_map.get::<State>(&1).is_none());
172+
assert_eq!(*cloned_map.get::<i32>(&10).unwrap(), 10i32);
173+
assert_eq!(*cloned_map.get::<i32>(&11).unwrap(), 11i32);
174+
assert!(cloned_map.get::<i32>(&12).is_none());
175+
}
176+
177+
#[cfg(test)]
178+
#[test]
179+
fn counting() {
180+
#[derive(Debug, Clone, Eq, PartialEq, Default)]
181+
struct State {
182+
a: i32,
183+
}
184+
185+
let mut map: AnyMap<i32> = Default::default();
186+
187+
map.insert(0, State::default());
188+
map.insert(1, State { a: 10 });
189+
map.insert(10, 10i32);
190+
map.insert(11, 11i32);
191+
map.insert(12, 12i32);
192+
193+
assert_eq!(map.count::<State>(), 2);
194+
assert_eq!(map.count::<i32>(), 3);
195+
196+
map.remove_by_type::<State>();
197+
198+
assert_eq!(map.count::<State>(), 0);
199+
assert_eq!(map.count::<i32>(), 3);
200+
201+
map.clear();
202+
203+
assert_eq!(map.count::<State>(), 0);
204+
assert_eq!(map.count::<i32>(), 0);
205+
}

egui/src/any/element.rs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
use std::any::{Any, TypeId};
2+
use std::fmt;
3+
4+
/// Like [`std::any::Any`], but also implements `Clone`.
5+
pub(crate) struct AnyMapElement {
6+
value: Box<dyn Any + 'static>,
7+
clone_fn: fn(&Box<dyn Any + 'static>) -> Box<dyn Any + 'static>,
8+
}
9+
10+
impl fmt::Debug for AnyMapElement {
11+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12+
f.debug_struct("AnyMapElement")
13+
.field("value_type_id", &self.type_id())
14+
.finish()
15+
}
16+
}
17+
18+
impl Clone for AnyMapElement {
19+
fn clone(&self) -> Self {
20+
AnyMapElement {
21+
value: (self.clone_fn)(&self.value),
22+
clone_fn: self.clone_fn,
23+
}
24+
}
25+
}
26+
27+
pub trait AnyMapTrait: 'static + Any + Clone {}
28+
29+
impl<T: 'static + Any + Clone> AnyMapTrait for T {}
30+
31+
impl AnyMapElement {
32+
pub(crate) fn new<T: AnyMapTrait>(t: T) -> Self {
33+
AnyMapElement {
34+
value: Box::new(t),
35+
clone_fn: |x| {
36+
let x = x.downcast_ref::<T>().unwrap(); // This unwrap will never panic, because we always construct this type using this `new` function and because we return &mut reference only with type `T`, so type cannot change.
37+
Box::new(x.clone())
38+
},
39+
}
40+
}
41+
42+
pub(crate) fn type_id(&self) -> TypeId {
43+
(*self.value).type_id()
44+
}
45+
46+
pub(crate) fn get_mut<T: AnyMapTrait>(&mut self) -> Option<&mut T> {
47+
self.value.downcast_mut()
48+
}
49+
50+
pub(crate) fn get_mut_or_set_with<T: AnyMapTrait>(
51+
&mut self,
52+
set_with: impl FnOnce() -> T,
53+
) -> &mut T {
54+
if !self.value.is::<T>() {
55+
*self = Self::new(set_with());
56+
// TODO: log this error, because it can occurs when user used same Id or same type for different widgets
57+
}
58+
59+
self.value.downcast_mut().unwrap() // This unwrap will never panic because we already converted object to required type
60+
}
61+
}

egui/src/any/mod.rs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//! Any-type storages for [`Memory`].
2+
//!
3+
//! This module contains structs to store arbitrary types using [`Any`] trait. Also, they can be cloned, and structs in [`serializable`] can be de/serialized.
4+
//!
5+
//! All this is just `HashMap<TypeId, Box<dyn Any + static>>` and `HashMap<Key, Box<dyn Any + static>>`, but with helper functions and hacks for cloning and de/serialization.
6+
//!
7+
//! # Trait requirements
8+
//!
9+
//! If you want to store your type here, it must implement `Clone` and `Any` and be `'static`, which means it must not contain references. If you want to store your data in serializable storage, it must implement `serde::Serialize` and `serde::Deserialize` under the `persistent` feature.
10+
//!
11+
//! # [`TypeMap`]
12+
//!
13+
//! It stores everything by just type. You should use this map for your widget when all instances of your widgets can have only one state. E.g. for popup windows, for color picker.
14+
//!
15+
//! To not have intersections, you should create newtype for anything you try to store here, like:
16+
//! ```rust
17+
//! struct MyEditBool(pub bool);
18+
//! ```
19+
//!
20+
//! # [`AnyMap<Key>`]
21+
//!
22+
//! In [`Memory`] `Key` = [`Id`].
23+
//!
24+
//! [`TypeMap`] and [`AnyMap<Key>`] has a quite similar interface, except for [`AnyMap`] you should pass `Key` to get and insert things.
25+
//!
26+
//! It stores everything by `Key`, this should be used when your widget can have different data for different instances of the widget.
27+
//!
28+
//! # `serializable`
29+
//!
30+
//! [`TypeMap`] and [`serializable::TypeMap`] has exactly the same interface, but [`serializable::TypeMap`] only requires serde traits for stored object under `persistent` feature. Same thing for [`AnyMap`] and [`serializable::AnyMap`].
31+
//!
32+
//! # What could break
33+
//!
34+
//! Things here could break only when you trying to load this from file.
35+
//!
36+
//! First, serialized `TypeId` in [`serializable::TypeMap`] could broke if you updated the version of the Rust compiler between runs.
37+
//!
38+
//! Second, count and reset all instances of a type in [`serializable::AnyMap`] could return an incorrect value for the same reason.
39+
//!
40+
//! Deserialization errors of loaded elements of these storages can be determined only when you call `get_...` functions, they not logged and not provided to a user, on this errors value is just replaced with `or_insert()`/default value.
41+
//!
42+
//! # When not to use this
43+
//!
44+
//! This is not for important widget data. Some errors are just ignored and the correct value of type is inserted when you call. This is done to more simple interface.
45+
//!
46+
//! You shouldn't use any map here when you need very reliable state storage with rich error-handling. For this purpose you should create your own `Memory` struct and pass it everywhere you need it. Then, you should de/serialize it by yourself, handling all serialization or other errors as you wish.
47+
//!
48+
//! [`Id`]: crate::Id
49+
//! [`Memory`]: crate::Memory
50+
//! [`Any`]: std::any::Any
51+
//! [`AnyMap<Key>`]: crate::any::AnyMap
52+
53+
mod any_map;
54+
mod element;
55+
mod type_map;
56+
57+
/// Same structs and traits, but also can be de/serialized under `persistence` feature.
58+
#[cfg(feature = "persistence")]
59+
pub mod serializable;
60+
61+
pub use self::{any_map::AnyMap, element::AnyMapTrait, type_map::TypeMap};

0 commit comments

Comments
 (0)