bevy_reflect/
set.rs

1use alloc::{boxed::Box, format, vec::Vec};
2use core::fmt::{Debug, Formatter};
3
4use bevy_platform::collections::{hash_table::OccupiedEntry as HashTableOccupiedEntry, HashTable};
5use bevy_reflect_derive::impl_type_path;
6
7use crate::{
8    generics::impl_generic_info_methods, hash_error, type_info::impl_type_methods, ApplyError,
9    Generics, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type,
10    TypeInfo, TypePath,
11};
12
13/// A trait used to power [set-like] operations via [reflection].
14///
15/// Sets contain zero or more entries of a fixed type, and correspond to types
16/// like [`HashSet`] and [`BTreeSet`].
17/// The order of these entries is not guaranteed by this trait.
18///
19/// # Hashing and equality
20///
21/// All values are expected to return a valid hash value from [`PartialReflect::reflect_hash`] and be
22/// comparable using [`PartialReflect::reflect_partial_eq`].
23/// If using the [`#[derive(Reflect)]`](derive@crate::Reflect) macro, this can be done by adding
24/// `#[reflect(Hash, PartialEq)]` to the entire struct or enum.
25/// The ordering is expected to be total, that is as if the reflected type implements the [`Eq`] trait.
26/// This is true even for manual implementors who do not hash or compare values,
27/// as it is still relied on by [`DynamicSet`].
28///
29/// # Example
30///
31/// ```
32/// use bevy_reflect::{PartialReflect, Set};
33/// use std::collections::HashSet;
34///
35///
36/// let foo: &mut dyn Set = &mut HashSet::<u32>::new();
37/// foo.insert_boxed(Box::new(123_u32));
38/// assert_eq!(foo.len(), 1);
39///
40/// let field: &dyn PartialReflect = foo.get(&123_u32).unwrap();
41/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123_u32));
42/// ```
43///
44/// [`HashSet`]: std::collections::HashSet
45/// [`BTreeSet`]: alloc::collections::BTreeSet
46/// [set-like]: https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html
47/// [reflection]: crate
48pub trait Set: PartialReflect {
49    /// Returns a reference to the value.
50    ///
51    /// If no value is contained, returns `None`.
52    fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect>;
53
54    /// Returns the number of elements in the set.
55    fn len(&self) -> usize;
56
57    /// Returns `true` if the list contains no elements.
58    fn is_empty(&self) -> bool {
59        self.len() == 0
60    }
61
62    /// Returns an iterator over the values of the set.
63    fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_>;
64
65    /// Drain the values of this set to get a vector of owned values.
66    ///
67    /// After calling this function, `self` will be empty.
68    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
69
70    /// Clones the set, producing a [`DynamicSet`].
71    #[deprecated(since = "0.16.0", note = "use `to_dynamic_set` instead")]
72    fn clone_dynamic(&self) -> DynamicSet {
73        self.to_dynamic_set()
74    }
75
76    /// Creates a new [`DynamicSet`] from this set.
77    fn to_dynamic_set(&self) -> DynamicSet {
78        let mut set = DynamicSet::default();
79        set.set_represented_type(self.get_represented_type_info());
80        for value in self.iter() {
81            set.insert_boxed(value.to_dynamic());
82        }
83        set
84    }
85
86    /// Inserts a value into the set.
87    ///
88    /// If the set did not have this value present, `true` is returned.
89    /// If the set did have this value present, `false` is returned.
90    fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool;
91
92    /// Removes a value from the set.
93    ///
94    /// If the set did not have this value present, `true` is returned.
95    /// If the set did have this value present, `false` is returned.
96    fn remove(&mut self, value: &dyn PartialReflect) -> bool;
97
98    /// Checks if the given value is contained in the set
99    fn contains(&self, value: &dyn PartialReflect) -> bool;
100}
101
102/// A container for compile-time set info.
103#[derive(Clone, Debug)]
104pub struct SetInfo {
105    ty: Type,
106    generics: Generics,
107    value_ty: Type,
108    #[cfg(feature = "documentation")]
109    docs: Option<&'static str>,
110}
111
112impl SetInfo {
113    /// Create a new [`SetInfo`].
114    pub fn new<TSet: Set + TypePath, TValue: Reflect + TypePath>() -> Self {
115        Self {
116            ty: Type::of::<TSet>(),
117            generics: Generics::new(),
118            value_ty: Type::of::<TValue>(),
119            #[cfg(feature = "documentation")]
120            docs: None,
121        }
122    }
123
124    /// Sets the docstring for this set.
125    #[cfg(feature = "documentation")]
126    pub fn with_docs(self, docs: Option<&'static str>) -> Self {
127        Self { docs, ..self }
128    }
129
130    impl_type_methods!(ty);
131
132    /// The [type] of the value.
133    ///
134    /// [type]: Type
135    pub fn value_ty(&self) -> Type {
136        self.value_ty
137    }
138
139    /// The docstring of this set, if any.
140    #[cfg(feature = "documentation")]
141    pub fn docs(&self) -> Option<&'static str> {
142        self.docs
143    }
144
145    impl_generic_info_methods!(generics);
146}
147
148/// An ordered set of reflected values.
149#[derive(Default)]
150pub struct DynamicSet {
151    represented_type: Option<&'static TypeInfo>,
152    hash_table: HashTable<Box<dyn PartialReflect>>,
153}
154
155impl DynamicSet {
156    /// Sets the [type] to be represented by this `DynamicSet`.
157    ///
158    /// # Panics
159    ///
160    /// Panics if the given [type] is not a [`TypeInfo::Set`].
161    ///
162    /// [type]: TypeInfo
163    pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
164        if let Some(represented_type) = represented_type {
165            assert!(
166                matches!(represented_type, TypeInfo::Set(_)),
167                "expected TypeInfo::Set but received: {:?}",
168                represented_type
169            );
170        }
171
172        self.represented_type = represented_type;
173    }
174
175    /// Inserts a typed value into the set.
176    pub fn insert<V: Reflect>(&mut self, value: V) {
177        self.insert_boxed(Box::new(value));
178    }
179
180    fn internal_hash(value: &dyn PartialReflect) -> u64 {
181        value.reflect_hash().expect(&hash_error!(value))
182    }
183
184    fn internal_eq(
185        value: &dyn PartialReflect,
186    ) -> impl FnMut(&Box<dyn PartialReflect>) -> bool + '_ {
187        |other| {
188            value
189                .reflect_partial_eq(&**other)
190                .expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks")
191        }
192    }
193}
194
195impl Set for DynamicSet {
196    fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
197        self.hash_table
198            .find(Self::internal_hash(value), Self::internal_eq(value))
199            .map(|value| &**value)
200    }
201
202    fn len(&self) -> usize {
203        self.hash_table.len()
204    }
205
206    fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> {
207        let iter = self.hash_table.iter().map(|v| &**v);
208        Box::new(iter)
209    }
210
211    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
212        self.hash_table.drain().collect::<Vec<_>>()
213    }
214
215    fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool {
216        assert_eq!(
217            value.reflect_partial_eq(&*value),
218            Some(true),
219            "Values inserted in `Set` like types are expected to reflect `PartialEq`"
220        );
221        match self
222            .hash_table
223            .find_mut(Self::internal_hash(&*value), Self::internal_eq(&*value))
224        {
225            Some(old) => {
226                *old = value;
227                false
228            }
229            None => {
230                self.hash_table.insert_unique(
231                    Self::internal_hash(value.as_ref()),
232                    value,
233                    |boxed| Self::internal_hash(boxed.as_ref()),
234                );
235                true
236            }
237        }
238    }
239
240    fn remove(&mut self, value: &dyn PartialReflect) -> bool {
241        self.hash_table
242            .find_entry(Self::internal_hash(value), Self::internal_eq(value))
243            .map(HashTableOccupiedEntry::remove)
244            .is_ok()
245    }
246
247    fn contains(&self, value: &dyn PartialReflect) -> bool {
248        self.hash_table
249            .find(Self::internal_hash(value), Self::internal_eq(value))
250            .is_some()
251    }
252}
253
254impl PartialReflect for DynamicSet {
255    #[inline]
256    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
257        self.represented_type
258    }
259
260    #[inline]
261    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
262        self
263    }
264
265    #[inline]
266    fn as_partial_reflect(&self) -> &dyn PartialReflect {
267        self
268    }
269
270    #[inline]
271    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
272        self
273    }
274
275    #[inline]
276    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
277        Err(self)
278    }
279
280    #[inline]
281    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
282        None
283    }
284
285    #[inline]
286    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
287        None
288    }
289
290    fn apply(&mut self, value: &dyn PartialReflect) {
291        set_apply(self, value);
292    }
293
294    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
295        set_try_apply(self, value)
296    }
297
298    fn reflect_kind(&self) -> ReflectKind {
299        ReflectKind::Set
300    }
301
302    fn reflect_ref(&self) -> ReflectRef {
303        ReflectRef::Set(self)
304    }
305
306    fn reflect_mut(&mut self) -> ReflectMut {
307        ReflectMut::Set(self)
308    }
309
310    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
311        ReflectOwned::Set(self)
312    }
313
314    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
315        set_partial_eq(self, value)
316    }
317
318    fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
319        write!(f, "DynamicSet(")?;
320        set_debug(self, f)?;
321        write!(f, ")")
322    }
323
324    #[inline]
325    fn is_dynamic(&self) -> bool {
326        true
327    }
328}
329
330impl_type_path!((in bevy_reflect) DynamicSet);
331
332impl Debug for DynamicSet {
333    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
334        self.debug(f)
335    }
336}
337
338impl FromIterator<Box<dyn PartialReflect>> for DynamicSet {
339    fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self {
340        let mut this = Self {
341            represented_type: None,
342            hash_table: HashTable::new(),
343        };
344
345        for value in values {
346            this.insert_boxed(value);
347        }
348
349        this
350    }
351}
352
353impl<T: Reflect> FromIterator<T> for DynamicSet {
354    fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {
355        let mut this = Self {
356            represented_type: None,
357            hash_table: HashTable::new(),
358        };
359
360        for value in values {
361            this.insert(value);
362        }
363
364        this
365    }
366}
367
368impl IntoIterator for DynamicSet {
369    type Item = Box<dyn PartialReflect>;
370    type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>;
371
372    fn into_iter(self) -> Self::IntoIter {
373        self.hash_table.into_iter()
374    }
375}
376
377impl<'a> IntoIterator for &'a DynamicSet {
378    type Item = &'a dyn PartialReflect;
379    type IntoIter = core::iter::Map<
380        bevy_platform::collections::hash_table::Iter<'a, Box<dyn PartialReflect>>,
381        fn(&'a Box<dyn PartialReflect>) -> Self::Item,
382    >;
383
384    fn into_iter(self) -> Self::IntoIter {
385        self.hash_table.iter().map(|v| v.as_ref())
386    }
387}
388
389/// Compares a [`Set`] with a [`PartialReflect`] value.
390///
391/// Returns true if and only if all of the following are true:
392/// - `b` is a set;
393/// - `b` is the same length as `a`;
394/// - For each value pair in `a`, `b` contains the value too,
395///   and [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two values.
396///
397/// Returns [`None`] if the comparison couldn't even be performed.
398#[inline]
399pub fn set_partial_eq<M: Set>(a: &M, b: &dyn PartialReflect) -> Option<bool> {
400    let ReflectRef::Set(set) = b.reflect_ref() else {
401        return Some(false);
402    };
403
404    if a.len() != set.len() {
405        return Some(false);
406    }
407
408    for value in a.iter() {
409        if let Some(set_value) = set.get(value) {
410            let eq_result = value.reflect_partial_eq(set_value);
411            if let failed @ (Some(false) | None) = eq_result {
412                return failed;
413            }
414        } else {
415            return Some(false);
416        }
417    }
418
419    Some(true)
420}
421
422/// The default debug formatter for [`Set`] types.
423///
424/// # Example
425/// ```
426/// # use std::collections::HashSet;
427/// use bevy_reflect::Reflect;
428///
429/// let mut my_set = HashSet::new();
430/// my_set.insert(String::from("Hello"));
431/// println!("{:#?}", &my_set as &dyn Reflect);
432///
433/// // Output:
434///
435/// // {
436/// //   "Hello",
437/// // }
438/// ```
439#[inline]
440pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> core::fmt::Result {
441    let mut debug = f.debug_set();
442    for value in dyn_set.iter() {
443        debug.entry(&value as &dyn Debug);
444    }
445    debug.finish()
446}
447
448/// Applies the elements of reflected set `b` to the corresponding elements of set `a`.
449///
450/// If a value from `b` does not exist in `a`, the value is cloned and inserted.
451///
452/// # Panics
453///
454/// This function panics if `b` is not a reflected set.
455#[inline]
456pub fn set_apply<M: Set>(a: &mut M, b: &dyn PartialReflect) {
457    if let ReflectRef::Set(set_value) = b.reflect_ref() {
458        for b_value in set_value.iter() {
459            if a.get(b_value).is_none() {
460                a.insert_boxed(b_value.to_dynamic());
461            }
462        }
463    } else {
464        panic!("Attempted to apply a non-set type to a set type.");
465    }
466}
467
468/// Tries to apply the elements of reflected set `b` to the corresponding elements of set `a`
469/// and returns a Result.
470///
471/// If a key from `b` does not exist in `a`, the value is cloned and inserted.
472///
473/// # Errors
474///
475/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a reflected set or if
476/// applying elements to each other fails.
477#[inline]
478pub fn set_try_apply<S: Set>(a: &mut S, b: &dyn PartialReflect) -> Result<(), ApplyError> {
479    let set_value = b.reflect_ref().as_set()?;
480
481    for b_value in set_value.iter() {
482        if a.get(b_value).is_none() {
483            a.insert_boxed(b_value.to_dynamic());
484        }
485    }
486
487    Ok(())
488}
489
490#[cfg(test)]
491mod tests {
492    use super::DynamicSet;
493    use alloc::string::{String, ToString};
494
495    #[test]
496    fn test_into_iter() {
497        let expected = ["foo", "bar", "baz"];
498
499        let mut set = DynamicSet::default();
500        set.insert(expected[0].to_string());
501        set.insert(expected[1].to_string());
502        set.insert(expected[2].to_string());
503
504        for item in set.into_iter() {
505            let value = item
506                .try_take::<String>()
507                .expect("couldn't downcast to String");
508            let index = expected
509                .iter()
510                .position(|i| *i == value.as_str())
511                .expect("Element found in expected array");
512            assert_eq!(expected[index], value);
513        }
514    }
515}