Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/set.rs
6598 views
1
use alloc::{boxed::Box, format, vec::Vec};
2
use core::fmt::{Debug, Formatter};
3
4
use bevy_platform::collections::{hash_table::OccupiedEntry as HashTableOccupiedEntry, HashTable};
5
use bevy_reflect_derive::impl_type_path;
6
7
use 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
48
pub 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
/// Retain only the elements specified by the predicate.
71
///
72
/// In other words, remove all elements `e` for which `f(&e)` returns `false`.
73
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool);
74
75
/// Creates a new [`DynamicSet`] from this set.
76
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
/// Inserts a value into the set.
86
///
87
/// If the set did not have this value present, `true` is returned.
88
/// If the set did have this value present, `false` is returned.
89
fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool;
90
91
/// Removes a value from the set.
92
///
93
/// If the set did not have this value present, `true` is returned.
94
/// If the set did have this value present, `false` is returned.
95
fn remove(&mut self, value: &dyn PartialReflect) -> bool;
96
97
/// Checks if the given value is contained in the set
98
fn contains(&self, value: &dyn PartialReflect) -> bool;
99
}
100
101
/// A container for compile-time set info.
102
#[derive(Clone, Debug)]
103
pub struct SetInfo {
104
ty: Type,
105
generics: Generics,
106
value_ty: Type,
107
#[cfg(feature = "documentation")]
108
docs: Option<&'static str>,
109
}
110
111
impl SetInfo {
112
/// Create a new [`SetInfo`].
113
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
/// Sets the docstring for this set.
124
#[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
/// The [type] of the value.
132
///
133
/// [type]: Type
134
pub fn value_ty(&self) -> Type {
135
self.value_ty
136
}
137
138
/// The docstring of this set, if any.
139
#[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
/// An unordered set of reflected values.
148
#[derive(Default)]
149
pub struct DynamicSet {
150
represented_type: Option<&'static TypeInfo>,
151
hash_table: HashTable<Box<dyn PartialReflect>>,
152
}
153
154
impl DynamicSet {
155
/// Sets the [type] to be represented by this `DynamicSet`.
156
///
157
/// # Panics
158
///
159
/// Panics if the given [type] is not a [`TypeInfo::Set`].
160
///
161
/// [type]: TypeInfo
162
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
/// Inserts a typed value into the set.
174
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
193
impl 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
256
impl 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
332
impl_type_path!((in bevy_reflect) DynamicSet);
333
334
impl Debug for DynamicSet {
335
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
336
self.debug(f)
337
}
338
}
339
340
impl 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
355
impl<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
370
impl 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
379
impl<'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
/// Compares a [`Set`] with a [`PartialReflect`] value.
392
///
393
/// Returns true if and only if all of the following are true:
394
/// - `b` is a set;
395
/// - `b` is the same length as `a`;
396
/// - For each value pair in `a`, `b` contains the value too,
397
/// and [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two values.
398
///
399
/// Returns [`None`] if the comparison couldn't even be performed.
400
#[inline]
401
pub 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
/// The default debug formatter for [`Set`] types.
425
///
426
/// # Example
427
/// ```
428
/// # use std::collections::HashSet;
429
/// use bevy_reflect::Reflect;
430
///
431
/// let mut my_set = HashSet::new();
432
/// my_set.insert(String::from("Hello"));
433
/// println!("{:#?}", &my_set as &dyn Reflect);
434
///
435
/// // Output:
436
///
437
/// // {
438
/// // "Hello",
439
/// // }
440
/// ```
441
#[inline]
442
pub 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
/// Applies the elements of reflected set `b` to the corresponding elements of set `a`.
451
///
452
/// If a value from `b` does not exist in `a`, the value is cloned and inserted.
453
/// If a value from `a` does not exist in `b`, the value is removed.
454
///
455
/// # Panics
456
///
457
/// This function panics if `b` is not a reflected set.
458
#[inline]
459
pub 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
/// Tries to apply the elements of reflected set `b` to the corresponding elements of set `a`
466
/// and returns a Result.
467
///
468
/// If a value from `b` does not exist in `a`, the value is cloned and inserted.
469
/// If a value from `a` does not exist in `b`, the value is removed.
470
///
471
/// # Errors
472
///
473
/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a reflected set or if
474
/// applying elements to each other fails.
475
#[inline]
476
pub 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)]
490
mod 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
}
534
535