1//! A trait used to power [set-like] operations via reflection.
2//!
3//! [set-like]: https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html
4use alloc::{boxed::Box, vec::Vec};
5use core::fmt::{Debug, Formatter};
67use bevy_platform::collections::{hash_table::OccupiedEntryas HashTableOccupiedEntry, HashTable};
8use bevy_reflect_derive::impl_type_path;
910use crate::{
11generics::impl_generic_info_methods, hash_error, ty::impl_type_methods, ApplyError, Generics,
12PartialReflect, Reflect, ReflectCloneError, ReflectKind, ReflectMut, ReflectOwned, ReflectRef,
13Type, TypeInfo, TypePath,
14};
1516/// A trait used to power [set-like] operations via [reflection].
17///
18/// Sets contain zero or more entries of a fixed type, and correspond to types
19/// like [`HashSet`] and [`BTreeSet`].
20/// The order of these entries is not guaranteed by this trait.
21///
22/// # Hashing and equality
23///
24/// All values are expected to return a valid hash value from [`PartialReflect::reflect_hash`] and be
25/// comparable using [`PartialReflect::reflect_partial_eq`].
26/// If using the [`#[derive(Reflect)]`](derive@crate::Reflect) macro, this can be done by adding
27/// `#[reflect(Hash, PartialEq)]` to the entire struct or enum.
28/// The ordering is expected to be total, that is as if the reflected type implements the [`Eq`] trait.
29/// This is true even for manual implementors who do not hash or compare values,
30/// as it is still relied on by [`DynamicSet`].
31///
32/// # Example
33///
34/// ```
35/// use bevy_reflect::{PartialReflect, set::Set};
36/// use std::collections::HashSet;
37///
38///
39/// let foo: &mut dyn Set = &mut HashSet::<u32>::new();
40/// foo.insert_boxed(Box::new(123_u32));
41/// assert_eq!(foo.len(), 1);
42///
43/// let field: &dyn PartialReflect = foo.get(&123_u32).unwrap();
44/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123_u32));
45/// ```
46///
47/// [`HashSet`]: std::collections::HashSet
48/// [`BTreeSet`]: alloc::collections::BTreeSet
49/// [set-like]: https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html
50/// [reflection]: crate
51// Prevents unexpectedly importing this trait when trying to call, for example, `HashSet::iter`
52#[rust_analyzer::completions(ignore_flyimport_methods)]
53pub trait Set: PartialReflect {
54/// Returns a reference to the value.
55 ///
56 /// If no value is contained, returns `None`.
57fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect>;
5859/// Returns the number of elements in the set.
60fn len(&self) -> usize;
6162/// Returns `true` if the list contains no elements.
63fn is_empty(&self) -> bool {
64self.len() == 0
65}
6667/// Returns an iterator over the values of the set.
68fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_>;
6970/// Drain the values of this set to get a vector of owned values.
71 ///
72 /// After calling this function, `self` will be empty.
73fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
7475/// Retain only the elements specified by the predicate.
76 ///
77 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
78fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool);
7980/// Creates a new [`DynamicSet`] from this set.
81 ///
82 /// Returns an error if any value cannot be converted via [`PartialReflect::to_dynamic`].
83fn to_dynamic_set(&self) -> Result<DynamicSet, ReflectCloneError> {
84let mut set = DynamicSet::default();
85set.set_represented_type(self.get_represented_type_info());
86for value in self.iter() {
87 set.insert_boxed(value.to_dynamic()?);
88 }
89Ok(set)
90 }
9192/// Inserts a value into 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.
96fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool;
9798/// Removes a value from the set.
99 ///
100 /// If the set did have this value present, `true` is returned.
101 /// If the set did not have this value present, `false` is returned.
102fn remove(&mut self, value: &dyn PartialReflect) -> bool;
103104/// Checks if the given value is contained in the set
105fn contains(&self, value: &dyn PartialReflect) -> bool;
106}
107108/// A container for compile-time set info.
109#[derive(#[automatically_derived]impl ::core::clone::Clone for SetInfo {
#[inline]
fn clone(&self) -> Self {
SetInfo {
ty: ::core::clone::Clone::clone(&self.ty),
generics: ::core::clone::Clone::clone(&self.generics),
value_ty: ::core::clone::Clone::clone(&self.value_ty),
docs: ::core::clone::Clone::clone(&self.docs),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SetInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "SetInfo", "ty",
&self.ty, "generics", &self.generics, "value_ty", &self.value_ty,
"docs", &&self.docs)
}
}Debug)]
110pub struct SetInfo {
111 ty: Type,
112 generics: Generics,
113 value_ty: Type,
114#[cfg(feature = "reflect_documentation")]
115docs: Option<&'static str>,
116}
117118impl SetInfo {
119/// Create a new [`SetInfo`].
120pub fn new<TSet: Set + TypePath, TValue: Reflect + TypePath>() -> Self {
121Self {
122 ty: Type::of::<TSet>(),
123 generics: Generics::new(),
124 value_ty: Type::of::<TValue>(),
125#[cfg(feature = "reflect_documentation")]
126docs: None,
127 }
128 }
129130/// Sets the docstring for this set.
131#[cfg(feature = "reflect_documentation")]
132pub fn with_docs(self, docs: Option<&'static str>) -> Self {
133Self { docs, ..self }
134 }
135136/// The underlying Rust [type].
///
/// [type]: crate::ty::Type
pub fn ty(&self) -> &crate::ty::Type { { &self.ty } }
/// The [`TypeId`] of this type.
///
/// [`TypeId`]: core::any::TypeId
pub fn type_id(&self) -> ::core::any::TypeId { self.ty().id() }
/// The [stable, full type path] of this type.
///
/// Use [`type_path_table`] if you need access to the other methods on [`TypePath`].
///
/// [stable, full type path]: TypePath
/// [`type_path_table`]: Self::type_path_table
pub fn type_path(&self) -> &'static str { self.ty().path() }
/// A representation of the type path of this type.
///
/// Provides dynamic access to all methods on [`TypePath`].
///
/// [`TypePath`]: crate::type_path::TypePath
pub fn type_path_table(&self) -> &crate::type_path::TypePathTable {
&self.ty().type_path_table()
}
/// Check if the given type matches this one.
///
/// This only compares the [`TypeId`] of the types
/// and does not verify they share the same [`TypePath`]
/// (though it implies they do).
///
/// [`TypeId`]: core::any::TypeId
/// [`TypePath`]: crate::type_path::TypePath
pub fn is<T: ::core::any::Any>(&self) -> bool { self.ty().is::<T>() }impl_type_methods!(ty);
137138/// The [type] of the value.
139 ///
140 /// [type]: Type
141pub fn value_ty(&self) -> Type {
142self.value_ty
143 }
144145/// The docstring of this set, if any.
146#[cfg(feature = "reflect_documentation")]
147pub fn docs(&self) -> Option<&'static str> {
148self.docs
149 }
150151/// Gets the generic parameters for this type.
pub fn generics(&self) -> &crate::generics::Generics { &self.generics }
/// Sets the generic parameters for this type.
pub fn with_generics(mut self, generics: crate::generics::Generics) -> Self {
self.generics = generics;
self
}impl_generic_info_methods!(generics);
152}
153154/// An unordered set of reflected values.
155#[derive(#[automatically_derived]impl ::core::default::Default for DynamicSet {
#[inline]
fn default() -> Self {
DynamicSet {
represented_type: ::core::default::Default::default(),
hash_table: ::core::default::Default::default(),
}
}
}Default)]
156pub struct DynamicSet {
157 represented_type: Option<&'static TypeInfo>,
158 hash_table: HashTable<Box<dyn PartialReflect>>,
159}
160161impl DynamicSet {
162/// Sets the [type] to be represented by this `DynamicSet`.
163 ///
164 /// # Panics
165 ///
166 /// Panics if the given [type] is not a [`TypeInfo::Set`].
167 ///
168 /// [type]: TypeInfo
169pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
170if let Some(represented_type) = represented_type {
171if !#[allow(non_exhaustive_omitted_patterns)] match represented_type {
TypeInfo::Set(_) => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("expected TypeInfo::Set but received: {0:?}",
represented_type));
}
};assert!(
172matches!(represented_type, TypeInfo::Set(_)),
173"expected TypeInfo::Set but received: {represented_type:?}"
174);
175 }
176177self.represented_type = represented_type;
178 }
179180/// Inserts a typed value into the set.
181pub fn insert<V: Reflect>(&mut self, value: V) {
182self.insert_boxed(Box::new(value));
183 }
184185fn internal_hash(value: &dyn PartialReflect) -> u64 {
186value.reflect_hash().expect(&{
let type_path = (*value).reflect_type_path();
if !value.is_dynamic() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the given key of type `{0}` does not support hashing",
type_path))
})
} else {
match (*value).get_represented_type_info() {
::core::option::Option::None =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the dynamic type `{0}` does not support hashing",
type_path))
}),
::core::option::Option::Some(s) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the dynamic type `{0}` (representing `{1}`) does not support hashing",
type_path, s.type_path()))
}),
}
}
}hash_error!(value))
187 }
188189fn internal_eq(
190 value: &dyn PartialReflect,
191 ) -> impl FnMut(&Box<dyn PartialReflect>) -> bool + '_ {
192 |other| {
193value194 .reflect_partial_eq(&**other)
195 .expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks")
196 }
197 }
198}
199200impl Setfor DynamicSet {
201fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
202self.hash_table
203 .find(Self::internal_hash(value), Self::internal_eq(value))
204 .map(|value| &**value)
205 }
206207fn len(&self) -> usize {
208self.hash_table.len()
209 }
210211fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> {
212let iter = self.hash_table.iter().map(|v| &**v);
213Box::new(iter)
214 }
215216fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
217self.hash_table.drain().collect::<Vec<_>>()
218 }
219220fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool) {
221self.hash_table.retain(move |value| f(&**value));
222 }
223224fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool {
225{
match (&value.reflect_partial_eq(&*value), &Some(true)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Values inserted in `Set` like types are expected to reflect `PartialEq`")));
}
}
}
};assert_eq!(
226 value.reflect_partial_eq(&*value),
227Some(true),
228"Values inserted in `Set` like types are expected to reflect `PartialEq`"
229);
230match self231 .hash_table
232 .find_mut(Self::internal_hash(&*value), Self::internal_eq(&*value))
233 {
234Some(old) => {
235*old = value;
236false
237}
238None => {
239self.hash_table.insert_unique(
240Self::internal_hash(value.as_ref()),
241value,
242 |boxed| Self::internal_hash(boxed.as_ref()),
243 );
244true
245}
246 }
247 }
248249fn remove(&mut self, value: &dyn PartialReflect) -> bool {
250self.hash_table
251 .find_entry(Self::internal_hash(value), Self::internal_eq(value))
252 .map(HashTableOccupiedEntry::remove)
253 .is_ok()
254 }
255256fn contains(&self, value: &dyn PartialReflect) -> bool {
257self.hash_table
258 .find(Self::internal_hash(value), Self::internal_eq(value))
259 .is_some()
260 }
261}
262263impl PartialReflectfor DynamicSet {
264#[inline]
265fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
266self.represented_type
267 }
268269#[inline]
270fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
271self272 }
273274#[inline]
275fn as_partial_reflect(&self) -> &dyn PartialReflect {
276self277 }
278279#[inline]
280fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
281self282 }
283284#[inline]
285fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
286Err(self)
287 }
288289#[inline]
290fn try_as_reflect(&self) -> Option<&dyn Reflect> {
291None292 }
293294#[inline]
295fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
296None297 }
298299fn apply(&mut self, value: &dyn PartialReflect) {
300set_apply(self, value);
301 }
302303fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
304set_try_apply(self, value)
305 }
306307fn reflect_kind(&self) -> ReflectKind {
308 ReflectKind::Set309 }
310311fn reflect_ref(&self) -> ReflectRef<'_> {
312 ReflectRef::Set(self)
313 }
314315fn reflect_mut(&mut self) -> ReflectMut<'_> {
316 ReflectMut::Set(self)
317 }
318319fn reflect_owned(self: Box<Self>) -> ReflectOwned {
320 ReflectOwned::Set(self)
321 }
322323fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
324set_partial_eq(self, value)
325 }
326327fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
328f.write_fmt(format_args!("DynamicSet("))write!(f, "DynamicSet(")?;
329 set_debug(self, f)?;
330f.write_fmt(format_args!(")"))write!(f, ")")331 }
332333#[inline]
334fn is_dynamic(&self) -> bool {
335true
336}
337}
338339const _: () =
{
#[allow(deprecated, reason =
"derives on a deprecated type shouldn't be considered a usage")]
impl bevy_reflect::TypePath for DynamicSet where {
fn type_path() -> &'static str { "bevy_reflect::DynamicSet" }
fn short_type_path() -> &'static str { "DynamicSet" }
fn type_ident() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("DynamicSet")
}
fn crate_name() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_reflect")
}
fn module_path() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_reflect")
}
}
};impl_type_path!((in bevy_reflect) DynamicSet);
340341impl Debugfor DynamicSet {
342fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
343self.debug(f)
344 }
345}
346347impl FromIterator<Box<dyn PartialReflect>> for DynamicSet {
348fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self {
349let mut this = Self {
350 represented_type: None,
351 hash_table: HashTable::new(),
352 };
353354for value in values {
355 this.insert_boxed(value);
356 }
357358this359 }
360}
361362impl<T: Reflect> FromIterator<T> for DynamicSet {
363fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {
364let mut this = Self {
365 represented_type: None,
366 hash_table: HashTable::new(),
367 };
368369for value in values {
370 this.insert(value);
371 }
372373this374 }
375}
376377impl IntoIteratorfor DynamicSet {
378type Item = Box<dyn PartialReflect>;
379type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>;
380381fn into_iter(self) -> Self::IntoIter {
382self.hash_table.into_iter()
383 }
384}
385386impl<'a> IntoIteratorfor &'a DynamicSet {
387type Item = &'a dyn PartialReflect;
388type IntoIter = core::iter::Map<
389 bevy_platform::collections::hash_table::Iter<'a, Box<dyn PartialReflect>>,
390fn(&'a Box<dyn PartialReflect>) -> Self::Item,
391 >;
392393fn into_iter(self) -> Self::IntoIter {
394self.hash_table.iter().map(|v| v.as_ref())
395 }
396}
397398/// Compares a [`Set`] with a [`PartialReflect`] value.
399///
400/// Returns true if and only if all of the following are true:
401/// - `b` is a set;
402/// - `b` is the same length as `a`;
403/// - For each value pair in `a`, `b` contains the value too,
404/// and [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two values.
405///
406/// Returns [`None`] if the comparison couldn't even be performed.
407#[inline]
408pub fn set_partial_eq<M: Set>(a: &M, b: &dyn PartialReflect) -> Option<bool> {
409let ReflectRef::Set(set) = b.reflect_ref() else {
410return Some(false);
411 };
412413if a.len() != set.len() {
414return Some(false);
415 }
416417for value in a.iter() {
418if let Some(set_value) = set.get(value) {
419let eq_result = value.reflect_partial_eq(set_value);
420if let failed @ (Some(false) | None) = eq_result {
421return failed;
422 }
423 } else {
424return Some(false);
425 }
426 }
427428Some(true)
429}
430431/// The default debug formatter for [`Set`] types.
432///
433/// # Example
434/// ```
435/// # use std::collections::HashSet;
436/// use bevy_reflect::Reflect;
437///
438/// let mut my_set = HashSet::new();
439/// my_set.insert(String::from("Hello"));
440/// println!("{:#?}", &my_set as &dyn Reflect);
441///
442/// // Output:
443///
444/// // {
445/// // "Hello",
446/// // }
447/// ```
448#[inline]
449pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> core::fmt::Result {
450let mut debug = f.debug_set();
451for value in dyn_set.iter() {
452 debug.entry(&value as &dyn Debug);
453 }
454debug.finish()
455}
456457/// Applies the elements of reflected set `b` to the corresponding elements of set `a`.
458///
459/// If a value from `b` does not exist in `a`, the value is cloned and inserted.
460/// If a value from `a` does not exist in `b`, the value is removed.
461///
462/// # Panics
463///
464/// This function panics if `b` is not a reflected set.
465#[inline]
466pub fn set_apply<M: Set>(a: &mut M, b: &dyn PartialReflect) {
467if let Err(err) = set_try_apply(a, b) {
468{ ::core::panicking::panic_fmt(format_args!("{0}", err)); };panic!("{err}");
469 }
470}
471472/// Tries to apply the elements of reflected set `b` to the corresponding elements of set `a`
473/// and returns a Result.
474///
475/// If a value from `b` does not exist in `a`, the value is cloned and inserted.
476/// If a value from `a` does not exist in `b`, the value is removed.
477///
478/// # Errors
479///
480/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a reflected set or if
481/// applying elements to each other fails.
482#[inline]
483pub fn set_try_apply<S: Set>(a: &mut S, b: &dyn PartialReflect) -> Result<(), ApplyError> {
484let set_value = b.reflect_ref().as_set()?;
485486for b_value in set_value.iter() {
487if a.get(b_value).is_none() {
488 a.insert_boxed(b_value.to_dynamic()?);
489 }
490 }
491a.retain(&mut |value| set_value.get(value).is_some());
492493Ok(())
494}
495496#[cfg(test)]
497mod tests {
498use crate::{set::Set, PartialReflect};
499500use super::DynamicSet;
501use alloc::string::{String, ToString};
502503#[test]
504fn test_into_iter() {
505let expected = ["foo", "bar", "baz"];
506507let mut set = DynamicSet::default();
508 set.insert(expected[0].to_string());
509 set.insert(expected[1].to_string());
510 set.insert(expected[2].to_string());
511512for item in set.into_iter() {
513let value = item
514 .try_take::<String>()
515 .expect("couldn't downcast to String");
516let index = expected
517 .iter()
518 .position(|i| *i == value.as_str())
519 .expect("Element found in expected array");
520assert_eq!(expected[index], value);
521 }
522 }
523524#[test]
525fn apply() {
526let mut map_a = DynamicSet::default();
527 map_a.insert(0);
528 map_a.insert(1);
529530let mut map_b = DynamicSet::default();
531 map_b.insert(1);
532 map_b.insert(2);
533534 map_a.apply(&map_b);
535536assert!(map_a.get(&0).is_none());
537assert_eq!(map_a.get(&1).unwrap().try_downcast_ref(), Some(&1));
538assert_eq!(map_a.get(&2).unwrap().try_downcast_ref(), Some(&2));
539 }
540}