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
13pub trait Set: PartialReflect {
49 fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect>;
53
54 fn len(&self) -> usize;
56
57 fn is_empty(&self) -> bool {
59 self.len() == 0
60 }
61
62 fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_>;
64
65 fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
69
70 fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool);
74
75 fn to_dynamic_set(&self) -> DynamicSet {
77 let mut set = DynamicSet::default();
78 set.set_represented_type(self.get_represented_type_info());
79 for value in self.iter() {
80 set.insert_boxed(value.to_dynamic());
81 }
82 set
83 }
84
85 fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool;
90
91 fn remove(&mut self, value: &dyn PartialReflect) -> bool;
96
97 fn contains(&self, value: &dyn PartialReflect) -> bool;
99}
100
101#[derive(Clone, Debug)]
103pub struct SetInfo {
104 ty: Type,
105 generics: Generics,
106 value_ty: Type,
107 #[cfg(feature = "documentation")]
108 docs: Option<&'static str>,
109}
110
111impl SetInfo {
112 pub fn new<TSet: Set + TypePath, TValue: Reflect + TypePath>() -> Self {
114 Self {
115 ty: Type::of::<TSet>(),
116 generics: Generics::new(),
117 value_ty: Type::of::<TValue>(),
118 #[cfg(feature = "documentation")]
119 docs: None,
120 }
121 }
122
123 #[cfg(feature = "documentation")]
125 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
126 Self { docs, ..self }
127 }
128
129 impl_type_methods!(ty);
130
131 pub fn value_ty(&self) -> Type {
135 self.value_ty
136 }
137
138 #[cfg(feature = "documentation")]
140 pub fn docs(&self) -> Option<&'static str> {
141 self.docs
142 }
143
144 impl_generic_info_methods!(generics);
145}
146
147#[derive(Default)]
149pub struct DynamicSet {
150 represented_type: Option<&'static TypeInfo>,
151 hash_table: HashTable<Box<dyn PartialReflect>>,
152}
153
154impl DynamicSet {
155 pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
163 if let Some(represented_type) = represented_type {
164 assert!(
165 matches!(represented_type, TypeInfo::Set(_)),
166 "expected TypeInfo::Set but received: {represented_type:?}"
167 );
168 }
169
170 self.represented_type = represented_type;
171 }
172
173 pub fn insert<V: Reflect>(&mut self, value: V) {
175 self.insert_boxed(Box::new(value));
176 }
177
178 fn internal_hash(value: &dyn PartialReflect) -> u64 {
179 value.reflect_hash().expect(&hash_error!(value))
180 }
181
182 fn internal_eq(
183 value: &dyn PartialReflect,
184 ) -> impl FnMut(&Box<dyn PartialReflect>) -> bool + '_ {
185 |other| {
186 value
187 .reflect_partial_eq(&**other)
188 .expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks")
189 }
190 }
191}
192
193impl Set for DynamicSet {
194 fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
195 self.hash_table
196 .find(Self::internal_hash(value), Self::internal_eq(value))
197 .map(|value| &**value)
198 }
199
200 fn len(&self) -> usize {
201 self.hash_table.len()
202 }
203
204 fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> {
205 let iter = self.hash_table.iter().map(|v| &**v);
206 Box::new(iter)
207 }
208
209 fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
210 self.hash_table.drain().collect::<Vec<_>>()
211 }
212
213 fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool) {
214 self.hash_table.retain(move |value| f(&**value));
215 }
216
217 fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool {
218 assert_eq!(
219 value.reflect_partial_eq(&*value),
220 Some(true),
221 "Values inserted in `Set` like types are expected to reflect `PartialEq`"
222 );
223 match self
224 .hash_table
225 .find_mut(Self::internal_hash(&*value), Self::internal_eq(&*value))
226 {
227 Some(old) => {
228 *old = value;
229 false
230 }
231 None => {
232 self.hash_table.insert_unique(
233 Self::internal_hash(value.as_ref()),
234 value,
235 |boxed| Self::internal_hash(boxed.as_ref()),
236 );
237 true
238 }
239 }
240 }
241
242 fn remove(&mut self, value: &dyn PartialReflect) -> bool {
243 self.hash_table
244 .find_entry(Self::internal_hash(value), Self::internal_eq(value))
245 .map(HashTableOccupiedEntry::remove)
246 .is_ok()
247 }
248
249 fn contains(&self, value: &dyn PartialReflect) -> bool {
250 self.hash_table
251 .find(Self::internal_hash(value), Self::internal_eq(value))
252 .is_some()
253 }
254}
255
256impl PartialReflect for DynamicSet {
257 #[inline]
258 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
259 self.represented_type
260 }
261
262 #[inline]
263 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
264 self
265 }
266
267 #[inline]
268 fn as_partial_reflect(&self) -> &dyn PartialReflect {
269 self
270 }
271
272 #[inline]
273 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
274 self
275 }
276
277 #[inline]
278 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
279 Err(self)
280 }
281
282 #[inline]
283 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
284 None
285 }
286
287 #[inline]
288 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
289 None
290 }
291
292 fn apply(&mut self, value: &dyn PartialReflect) {
293 set_apply(self, value);
294 }
295
296 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
297 set_try_apply(self, value)
298 }
299
300 fn reflect_kind(&self) -> ReflectKind {
301 ReflectKind::Set
302 }
303
304 fn reflect_ref(&self) -> ReflectRef<'_> {
305 ReflectRef::Set(self)
306 }
307
308 fn reflect_mut(&mut self) -> ReflectMut<'_> {
309 ReflectMut::Set(self)
310 }
311
312 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
313 ReflectOwned::Set(self)
314 }
315
316 fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
317 set_partial_eq(self, value)
318 }
319
320 fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
321 write!(f, "DynamicSet(")?;
322 set_debug(self, f)?;
323 write!(f, ")")
324 }
325
326 #[inline]
327 fn is_dynamic(&self) -> bool {
328 true
329 }
330}
331
332impl_type_path!((in bevy_reflect) DynamicSet);
333
334impl Debug for DynamicSet {
335 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
336 self.debug(f)
337 }
338}
339
340impl FromIterator<Box<dyn PartialReflect>> for DynamicSet {
341 fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self {
342 let mut this = Self {
343 represented_type: None,
344 hash_table: HashTable::new(),
345 };
346
347 for value in values {
348 this.insert_boxed(value);
349 }
350
351 this
352 }
353}
354
355impl<T: Reflect> FromIterator<T> for DynamicSet {
356 fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {
357 let mut this = Self {
358 represented_type: None,
359 hash_table: HashTable::new(),
360 };
361
362 for value in values {
363 this.insert(value);
364 }
365
366 this
367 }
368}
369
370impl IntoIterator for DynamicSet {
371 type Item = Box<dyn PartialReflect>;
372 type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>;
373
374 fn into_iter(self) -> Self::IntoIter {
375 self.hash_table.into_iter()
376 }
377}
378
379impl<'a> IntoIterator for &'a DynamicSet {
380 type Item = &'a dyn PartialReflect;
381 type IntoIter = core::iter::Map<
382 bevy_platform::collections::hash_table::Iter<'a, Box<dyn PartialReflect>>,
383 fn(&'a Box<dyn PartialReflect>) -> Self::Item,
384 >;
385
386 fn into_iter(self) -> Self::IntoIter {
387 self.hash_table.iter().map(|v| v.as_ref())
388 }
389}
390
391#[inline]
401pub fn set_partial_eq<M: Set>(a: &M, b: &dyn PartialReflect) -> Option<bool> {
402 let ReflectRef::Set(set) = b.reflect_ref() else {
403 return Some(false);
404 };
405
406 if a.len() != set.len() {
407 return Some(false);
408 }
409
410 for value in a.iter() {
411 if let Some(set_value) = set.get(value) {
412 let eq_result = value.reflect_partial_eq(set_value);
413 if let failed @ (Some(false) | None) = eq_result {
414 return failed;
415 }
416 } else {
417 return Some(false);
418 }
419 }
420
421 Some(true)
422}
423
424#[inline]
442pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> core::fmt::Result {
443 let mut debug = f.debug_set();
444 for value in dyn_set.iter() {
445 debug.entry(&value as &dyn Debug);
446 }
447 debug.finish()
448}
449
450#[inline]
459pub fn set_apply<M: Set>(a: &mut M, b: &dyn PartialReflect) {
460 if let Err(err) = set_try_apply(a, b) {
461 panic!("{err}");
462 }
463}
464
465#[inline]
476pub fn set_try_apply<S: Set>(a: &mut S, b: &dyn PartialReflect) -> Result<(), ApplyError> {
477 let set_value = b.reflect_ref().as_set()?;
478
479 for b_value in set_value.iter() {
480 if a.get(b_value).is_none() {
481 a.insert_boxed(b_value.to_dynamic());
482 }
483 }
484 a.retain(&mut |value| set_value.get(value).is_some());
485
486 Ok(())
487}
488
489#[cfg(test)]
490mod tests {
491 use crate::{PartialReflect, Set};
492
493 use super::DynamicSet;
494 use alloc::string::{String, ToString};
495
496 #[test]
497 fn test_into_iter() {
498 let expected = ["foo", "bar", "baz"];
499
500 let mut set = DynamicSet::default();
501 set.insert(expected[0].to_string());
502 set.insert(expected[1].to_string());
503 set.insert(expected[2].to_string());
504
505 for item in set.into_iter() {
506 let value = item
507 .try_take::<String>()
508 .expect("couldn't downcast to String");
509 let index = expected
510 .iter()
511 .position(|i| *i == value.as_str())
512 .expect("Element found in expected array");
513 assert_eq!(expected[index], value);
514 }
515 }
516
517 #[test]
518 fn apply() {
519 let mut map_a = DynamicSet::default();
520 map_a.insert(0);
521 map_a.insert(1);
522
523 let mut map_b = DynamicSet::default();
524 map_b.insert(1);
525 map_b.insert(2);
526
527 map_a.apply(&map_b);
528
529 assert!(map_a.get(&0).is_none());
530 assert_eq!(map_a.get(&1).unwrap().try_downcast_ref(), Some(&1));
531 assert_eq!(map_a.get(&2).unwrap().try_downcast_ref(), Some(&2));
532 }
533}