bevy_reflect/
list.rs

1use alloc::{boxed::Box, vec::Vec};
2use core::{
3    any::Any,
4    fmt::{Debug, Formatter},
5    hash::{Hash, Hasher},
6};
7
8use bevy_reflect_derive::impl_type_path;
9
10use crate::generics::impl_generic_info_methods;
11use crate::{
12    type_info::impl_type_methods, utility::reflect_hasher, ApplyError, FromReflect, Generics,
13    MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type,
14    TypeInfo, TypePath,
15};
16
17/// A trait used to power [list-like] operations via [reflection].
18///
19/// This corresponds to types, like [`Vec`], which contain an ordered sequence
20/// of elements that implement [`Reflect`].
21///
22/// Unlike the [`Array`](crate::Array) trait, implementors of this trait are not expected to
23/// maintain a constant length.
24/// Methods like [insertion](List::insert) and [removal](List::remove) explicitly allow for their
25/// internal size to change.
26///
27/// [`push`](List::push) and [`pop`](List::pop) have default implementations,
28/// however it will generally be more performant to implement them manually
29/// as the default implementation uses a very naive approach to find the correct position.
30///
31/// This trait expects its elements to be ordered linearly from front to back.
32/// The _front_ element starts at index 0 with the _back_ element ending at the largest index.
33/// This contract above should be upheld by any manual implementors.
34///
35/// Due to the [type-erasing] nature of the reflection API as a whole,
36/// this trait does not make any guarantees that the implementor's elements
37/// are homogeneous (i.e. all the same type).
38///
39/// # Example
40///
41/// ```
42/// use bevy_reflect::{PartialReflect, Reflect, List};
43///
44/// let foo: &mut dyn List = &mut vec![123_u32, 456_u32, 789_u32];
45/// assert_eq!(foo.len(), 3);
46///
47/// let last_field: Box<dyn PartialReflect> = foo.pop().unwrap();
48/// assert_eq!(last_field.try_downcast_ref::<u32>(), Some(&789));
49/// ```
50///
51/// [list-like]: https://doc.rust-lang.org/book/ch08-01-vectors.html
52/// [reflection]: crate
53/// [type-erasing]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
54pub trait List: PartialReflect {
55    /// Returns a reference to the element at `index`, or `None` if out of bounds.
56    fn get(&self, index: usize) -> Option<&dyn PartialReflect>;
57
58    /// Returns a mutable reference to the element at `index`, or `None` if out of bounds.
59    fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
60
61    /// Inserts an element at position `index` within the list,
62    /// shifting all elements after it towards the back of the list.
63    ///
64    /// # Panics
65    /// Panics if `index > len`.
66    fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>);
67
68    /// Removes and returns the element at position `index` within the list,
69    /// shifting all elements before it towards the front of the list.
70    ///
71    /// # Panics
72    /// Panics if `index` is out of bounds.
73    fn remove(&mut self, index: usize) -> Box<dyn PartialReflect>;
74
75    /// Appends an element to the _back_ of the list.
76    fn push(&mut self, value: Box<dyn PartialReflect>) {
77        self.insert(self.len(), value);
78    }
79
80    /// Removes the _back_ element from the list and returns it, or [`None`] if it is empty.
81    fn pop(&mut self) -> Option<Box<dyn PartialReflect>> {
82        if self.is_empty() {
83            None
84        } else {
85            Some(self.remove(self.len() - 1))
86        }
87    }
88
89    /// Returns the number of elements in the list.
90    fn len(&self) -> usize;
91
92    /// Returns `true` if the collection contains no elements.
93    fn is_empty(&self) -> bool {
94        self.len() == 0
95    }
96
97    /// Returns an iterator over the list.
98    fn iter(&self) -> ListIter<'_>;
99
100    /// Drain the elements of this list to get a vector of owned values.
101    ///
102    /// After calling this function, `self` will be empty. The order of items in the returned
103    /// [`Vec`] will match the order of items in `self`.
104    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
105
106    /// Creates a new [`DynamicList`] from this list.
107    fn to_dynamic_list(&self) -> DynamicList {
108        DynamicList {
109            represented_type: self.get_represented_type_info(),
110            values: self.iter().map(PartialReflect::to_dynamic).collect(),
111        }
112    }
113
114    /// Will return `None` if [`TypeInfo`] is not available.
115    fn get_represented_list_info(&self) -> Option<&'static ListInfo> {
116        self.get_represented_type_info()?.as_list().ok()
117    }
118}
119
120/// A container for compile-time list info.
121#[derive(Clone, Debug)]
122pub struct ListInfo {
123    ty: Type,
124    generics: Generics,
125    item_info: fn() -> Option<&'static TypeInfo>,
126    item_ty: Type,
127    #[cfg(feature = "documentation")]
128    docs: Option<&'static str>,
129}
130
131impl ListInfo {
132    /// Create a new [`ListInfo`].
133    pub fn new<TList: List + TypePath, TItem: FromReflect + MaybeTyped + TypePath>() -> Self {
134        Self {
135            ty: Type::of::<TList>(),
136            generics: Generics::new(),
137            item_info: TItem::maybe_type_info,
138            item_ty: Type::of::<TItem>(),
139            #[cfg(feature = "documentation")]
140            docs: None,
141        }
142    }
143
144    /// Sets the docstring for this list.
145    #[cfg(feature = "documentation")]
146    pub fn with_docs(self, docs: Option<&'static str>) -> Self {
147        Self { docs, ..self }
148    }
149
150    impl_type_methods!(ty);
151
152    /// The [`TypeInfo`] of the list item.
153    ///
154    /// Returns `None` if the list item does not contain static type information,
155    /// such as for dynamic types.
156    pub fn item_info(&self) -> Option<&'static TypeInfo> {
157        (self.item_info)()
158    }
159
160    /// The [type] of the list item.
161    ///
162    /// [type]: Type
163    pub fn item_ty(&self) -> Type {
164        self.item_ty
165    }
166
167    /// The docstring of this list, if any.
168    #[cfg(feature = "documentation")]
169    pub fn docs(&self) -> Option<&'static str> {
170        self.docs
171    }
172
173    impl_generic_info_methods!(generics);
174}
175
176/// A list of reflected values.
177#[derive(Default)]
178pub struct DynamicList {
179    represented_type: Option<&'static TypeInfo>,
180    values: Vec<Box<dyn PartialReflect>>,
181}
182
183impl DynamicList {
184    /// Sets the [type] to be represented by this `DynamicList`.
185    /// # Panics
186    ///
187    /// Panics if the given [type] is not a [`TypeInfo::List`].
188    ///
189    /// [type]: TypeInfo
190    pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
191        if let Some(represented_type) = represented_type {
192            assert!(
193                matches!(represented_type, TypeInfo::List(_)),
194                "expected TypeInfo::List but received: {represented_type:?}"
195            );
196        }
197
198        self.represented_type = represented_type;
199    }
200
201    /// Appends a typed value to the list.
202    pub fn push<T: PartialReflect>(&mut self, value: T) {
203        self.values.push(Box::new(value));
204    }
205
206    /// Appends a [`Reflect`] trait object to the list.
207    pub fn push_box(&mut self, value: Box<dyn PartialReflect>) {
208        self.values.push(value);
209    }
210}
211
212impl List for DynamicList {
213    fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
214        self.values.get(index).map(|value| &**value)
215    }
216
217    fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
218        self.values.get_mut(index).map(|value| &mut **value)
219    }
220
221    fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>) {
222        self.values.insert(index, element);
223    }
224
225    fn remove(&mut self, index: usize) -> Box<dyn PartialReflect> {
226        self.values.remove(index)
227    }
228
229    fn push(&mut self, value: Box<dyn PartialReflect>) {
230        DynamicList::push_box(self, value);
231    }
232
233    fn pop(&mut self) -> Option<Box<dyn PartialReflect>> {
234        self.values.pop()
235    }
236
237    fn len(&self) -> usize {
238        self.values.len()
239    }
240
241    fn iter(&self) -> ListIter<'_> {
242        ListIter::new(self)
243    }
244
245    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
246        self.values.drain(..).collect()
247    }
248}
249
250impl PartialReflect for DynamicList {
251    #[inline]
252    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
253        self.represented_type
254    }
255
256    #[inline]
257    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
258        self
259    }
260
261    #[inline]
262    fn as_partial_reflect(&self) -> &dyn PartialReflect {
263        self
264    }
265
266    #[inline]
267    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
268        self
269    }
270
271    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
272        Err(self)
273    }
274
275    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
276        None
277    }
278
279    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
280        None
281    }
282
283    fn apply(&mut self, value: &dyn PartialReflect) {
284        list_apply(self, value);
285    }
286
287    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
288        list_try_apply(self, value)
289    }
290
291    #[inline]
292    fn reflect_kind(&self) -> ReflectKind {
293        ReflectKind::List
294    }
295
296    #[inline]
297    fn reflect_ref(&self) -> ReflectRef<'_> {
298        ReflectRef::List(self)
299    }
300
301    #[inline]
302    fn reflect_mut(&mut self) -> ReflectMut<'_> {
303        ReflectMut::List(self)
304    }
305
306    #[inline]
307    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
308        ReflectOwned::List(self)
309    }
310
311    #[inline]
312    fn reflect_hash(&self) -> Option<u64> {
313        list_hash(self)
314    }
315
316    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
317        list_partial_eq(self, value)
318    }
319
320    fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
321        write!(f, "DynamicList(")?;
322        list_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) DynamicList);
333
334impl Debug for DynamicList {
335    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
336        self.debug(f)
337    }
338}
339
340impl FromIterator<Box<dyn PartialReflect>> for DynamicList {
341    fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self {
342        Self {
343            represented_type: None,
344            values: values.into_iter().collect(),
345        }
346    }
347}
348
349impl<T: PartialReflect> FromIterator<T> for DynamicList {
350    fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {
351        values
352            .into_iter()
353            .map(|field| Box::new(field).into_partial_reflect())
354            .collect()
355    }
356}
357
358impl IntoIterator for DynamicList {
359    type Item = Box<dyn PartialReflect>;
360    type IntoIter = alloc::vec::IntoIter<Self::Item>;
361
362    fn into_iter(self) -> Self::IntoIter {
363        self.values.into_iter()
364    }
365}
366
367impl<'a> IntoIterator for &'a DynamicList {
368    type Item = &'a dyn PartialReflect;
369    type IntoIter = ListIter<'a>;
370
371    fn into_iter(self) -> Self::IntoIter {
372        self.iter()
373    }
374}
375
376/// An iterator over an [`List`].
377pub struct ListIter<'a> {
378    list: &'a dyn List,
379    index: usize,
380}
381
382impl ListIter<'_> {
383    /// Creates a new [`ListIter`].
384    #[inline]
385    pub const fn new(list: &dyn List) -> ListIter<'_> {
386        ListIter { list, index: 0 }
387    }
388}
389
390impl<'a> Iterator for ListIter<'a> {
391    type Item = &'a dyn PartialReflect;
392
393    #[inline]
394    fn next(&mut self) -> Option<Self::Item> {
395        let value = self.list.get(self.index);
396        self.index += value.is_some() as usize;
397        value
398    }
399
400    #[inline]
401    fn size_hint(&self) -> (usize, Option<usize>) {
402        let size = self.list.len();
403        (size, Some(size))
404    }
405}
406
407impl ExactSizeIterator for ListIter<'_> {}
408
409/// Returns the `u64` hash of the given [list](List).
410#[inline]
411pub fn list_hash<L: List>(list: &L) -> Option<u64> {
412    let mut hasher = reflect_hasher();
413    Any::type_id(list).hash(&mut hasher);
414    list.len().hash(&mut hasher);
415    for value in list.iter() {
416        hasher.write_u64(value.reflect_hash()?);
417    }
418    Some(hasher.finish())
419}
420
421/// Applies the elements of `b` to the corresponding elements of `a`.
422///
423/// If the length of `b` is greater than that of `a`, the excess elements of `b`
424/// are cloned and appended to `a`.
425///
426/// # Panics
427///
428/// This function panics if `b` is not a list.
429#[inline]
430pub fn list_apply<L: List>(a: &mut L, b: &dyn PartialReflect) {
431    if let Err(err) = list_try_apply(a, b) {
432        panic!("{err}");
433    }
434}
435
436/// Tries to apply the elements of `b` to the corresponding elements of `a` and
437/// returns a Result.
438///
439/// If the length of `b` is greater than that of `a`, the excess elements of `b`
440/// are cloned and appended to `a`.
441///
442/// # Errors
443///
444/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a list or if
445/// applying elements to each other fails.
446#[inline]
447pub fn list_try_apply<L: List>(a: &mut L, b: &dyn PartialReflect) -> Result<(), ApplyError> {
448    let list_value = b.reflect_ref().as_list()?;
449
450    for (i, value) in list_value.iter().enumerate() {
451        if i < a.len() {
452            if let Some(v) = a.get_mut(i) {
453                v.try_apply(value)?;
454            }
455        } else {
456            List::push(a, value.to_dynamic());
457        }
458    }
459
460    Ok(())
461}
462
463/// Compares a [`List`] with a [`Reflect`] value.
464///
465/// Returns true if and only if all of the following are true:
466/// - `b` is a list;
467/// - `b` is the same length as `a`;
468/// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise elements of `a` and `b`.
469///
470/// Returns [`None`] if the comparison couldn't even be performed.
471#[inline]
472pub fn list_partial_eq<L: List + ?Sized>(a: &L, b: &dyn PartialReflect) -> Option<bool> {
473    let ReflectRef::List(list) = b.reflect_ref() else {
474        return Some(false);
475    };
476
477    if a.len() != list.len() {
478        return Some(false);
479    }
480
481    for (a_value, b_value) in a.iter().zip(list.iter()) {
482        let eq_result = a_value.reflect_partial_eq(b_value);
483        if let failed @ (Some(false) | None) = eq_result {
484            return failed;
485        }
486    }
487
488    Some(true)
489}
490
491/// The default debug formatter for [`List`] types.
492///
493/// # Example
494/// ```
495/// use bevy_reflect::Reflect;
496///
497/// let my_list: &dyn Reflect = &vec![1, 2, 3];
498/// println!("{:#?}", my_list);
499///
500/// // Output:
501///
502/// // [
503/// //   1,
504/// //   2,
505/// //   3,
506/// // ]
507/// ```
508#[inline]
509pub fn list_debug(dyn_list: &dyn List, f: &mut Formatter<'_>) -> core::fmt::Result {
510    let mut debug = f.debug_list();
511    for item in dyn_list.iter() {
512        debug.entry(&item as &dyn Debug);
513    }
514    debug.finish()
515}
516
517#[cfg(test)]
518mod tests {
519    use super::DynamicList;
520    use crate::Reflect;
521    use alloc::{boxed::Box, vec};
522    use core::assert_eq;
523
524    #[test]
525    fn test_into_iter() {
526        let mut list = DynamicList::default();
527        list.push(0usize);
528        list.push(1usize);
529        list.push(2usize);
530        let items = list.into_iter();
531        for (index, item) in items.into_iter().enumerate() {
532            let value = item
533                .try_take::<usize>()
534                .expect("couldn't downcast to usize");
535            assert_eq!(index, value);
536        }
537    }
538
539    #[test]
540    fn next_index_increment() {
541        const SIZE: usize = if cfg!(debug_assertions) {
542            4
543        } else {
544            // If compiled in release mode, verify we dont overflow
545            usize::MAX
546        };
547        let b = Box::new(vec![(); SIZE]).into_reflect();
548
549        let list = b.reflect_ref().as_list().unwrap();
550
551        let mut iter = list.iter();
552        iter.index = SIZE - 1;
553        assert!(iter.next().is_some());
554
555        // When None we should no longer increase index
556        assert!(iter.next().is_none());
557        assert!(iter.index == SIZE);
558        assert!(iter.next().is_none());
559        assert!(iter.index == SIZE);
560    }
561}