Skip to main content

bevy_reflect/
list.rs

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