Skip to main content

egui/data/
user_data.rs

1use core::any::Any;
2use std::sync::Arc;
3
4/// A wrapper around `dyn Any`, used for passing custom user data
5/// to [`crate::ViewportCommand::Screenshot`].
6#[derive(Clone, Debug, Default)]
7pub struct UserData {
8    /// A user value given to the screenshot command,
9    /// that will be returned in [`crate::Event::Screenshot`].
10    pub data: Option<Arc<dyn Any + Send + Sync>>,
11}
12
13impl UserData {
14    /// You can also use [`Self::default`].
15    pub fn new(user_info: impl Any + Send + Sync) -> Self {
16        Self {
17            data: Some(Arc::new(user_info)),
18        }
19    }
20}
21
22impl PartialEq for UserData {
23    fn eq(&self, other: &Self) -> bool {
24        match (&self.data, &other.data) {
25            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
26            (None, None) => true,
27            _ => false,
28        }
29    }
30}
31
32impl Eq for UserData {}
33
34impl core::hash::Hash for UserData {
35    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
36        self.data.as_ref().map(Arc::as_ptr).hash(state);
37    }
38}
39
40#[cfg(feature = "serde")]
41impl serde::Serialize for UserData {
42    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
43    where
44        S: serde::Serializer,
45    {
46        serializer.serialize_none() // can't serialize an `Any`
47    }
48}
49
50#[cfg(feature = "serde")]
51impl<'de> serde::Deserialize<'de> for UserData {
52    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53    where
54        D: serde::Deserializer<'de>,
55    {
56        struct UserDataVisitor;
57
58        impl serde::de::Visitor<'_> for UserDataVisitor {
59            type Value = UserData;
60
61            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62                formatter.write_str("a None value")
63            }
64
65            fn visit_none<E>(self) -> Result<UserData, E>
66            where
67                E: serde::de::Error,
68            {
69                Ok(UserData::default())
70            }
71        }
72
73        deserializer.deserialize_option(UserDataVisitor)
74    }
75}