bevy_reflect/impls/
smallvec.rs

1use crate::{
2    utility::GenericTypeInfoCell, ApplyError, FromReflect, FromType, Generics, GetTypeRegistration,
3    List, ListInfo, ListIter, MaybeTyped, PartialReflect, Reflect, ReflectFromPtr, ReflectKind,
4    ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypeParamInfo, TypePath, TypeRegistration,
5    Typed,
6};
7use alloc::{boxed::Box, vec::Vec};
8use bevy_reflect::ReflectCloneError;
9use bevy_reflect_derive::impl_type_path;
10use core::any::Any;
11use smallvec::{Array as SmallArray, SmallVec};
12
13impl<T: SmallArray + TypePath + Send + Sync> List for SmallVec<T>
14where
15    T::Item: FromReflect + MaybeTyped + TypePath,
16{
17    fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
18        if index < SmallVec::len(self) {
19            Some(&self[index] as &dyn PartialReflect)
20        } else {
21            None
22        }
23    }
24
25    fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
26        if index < SmallVec::len(self) {
27            Some(&mut self[index] as &mut dyn PartialReflect)
28        } else {
29            None
30        }
31    }
32
33    fn insert(&mut self, index: usize, value: Box<dyn PartialReflect>) {
34        let value = value.try_take::<T::Item>().unwrap_or_else(|value| {
35            <T as SmallArray>::Item::from_reflect(&*value).unwrap_or_else(|| {
36                panic!(
37                    "Attempted to insert invalid value of type {}.",
38                    value.reflect_type_path()
39                )
40            })
41        });
42        SmallVec::insert(self, index, value);
43    }
44
45    fn remove(&mut self, index: usize) -> Box<dyn PartialReflect> {
46        Box::new(self.remove(index))
47    }
48
49    fn push(&mut self, value: Box<dyn PartialReflect>) {
50        let value = value.try_take::<T::Item>().unwrap_or_else(|value| {
51            <T as SmallArray>::Item::from_reflect(&*value).unwrap_or_else(|| {
52                panic!(
53                    "Attempted to push invalid value of type {}.",
54                    value.reflect_type_path()
55                )
56            })
57        });
58        SmallVec::push(self, value);
59    }
60
61    fn pop(&mut self) -> Option<Box<dyn PartialReflect>> {
62        self.pop()
63            .map(|value| Box::new(value) as Box<dyn PartialReflect>)
64    }
65
66    fn len(&self) -> usize {
67        <SmallVec<T>>::len(self)
68    }
69
70    fn iter(&self) -> ListIter<'_> {
71        ListIter::new(self)
72    }
73
74    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
75        self.drain(..)
76            .map(|value| Box::new(value) as Box<dyn PartialReflect>)
77            .collect()
78    }
79}
80
81impl<T: SmallArray + TypePath + Send + Sync> PartialReflect for SmallVec<T>
82where
83    T::Item: FromReflect + MaybeTyped + TypePath,
84{
85    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
86        Some(<Self as Typed>::type_info())
87    }
88
89    #[inline]
90    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
91        self
92    }
93
94    fn as_partial_reflect(&self) -> &dyn PartialReflect {
95        self
96    }
97
98    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
99        self
100    }
101
102    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
103        Ok(self)
104    }
105
106    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
107        Some(self)
108    }
109
110    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
111        Some(self)
112    }
113
114    fn apply(&mut self, value: &dyn PartialReflect) {
115        crate::list_apply(self, value);
116    }
117
118    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
119        crate::list_try_apply(self, value)
120    }
121
122    fn reflect_kind(&self) -> ReflectKind {
123        ReflectKind::List
124    }
125
126    fn reflect_ref(&self) -> ReflectRef<'_> {
127        ReflectRef::List(self)
128    }
129
130    fn reflect_mut(&mut self) -> ReflectMut<'_> {
131        ReflectMut::List(self)
132    }
133
134    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
135        ReflectOwned::List(self)
136    }
137
138    fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
139        Ok(Box::new(
140            // `(**self)` avoids getting `SmallVec<T> as List::iter`, which
141            // would give us the wrong item type.
142            (**self)
143                .iter()
144                .map(PartialReflect::reflect_clone_and_take)
145                .collect::<Result<Self, ReflectCloneError>>()?,
146        ))
147    }
148
149    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
150        crate::list_partial_eq(self, value)
151    }
152}
153
154impl<T: SmallArray + TypePath + Send + Sync> Reflect for SmallVec<T>
155where
156    T::Item: FromReflect + MaybeTyped + TypePath,
157{
158    fn into_any(self: Box<Self>) -> Box<dyn Any> {
159        self
160    }
161
162    fn as_any(&self) -> &dyn Any {
163        self
164    }
165
166    fn as_any_mut(&mut self) -> &mut dyn Any {
167        self
168    }
169
170    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
171        self
172    }
173
174    fn as_reflect(&self) -> &dyn Reflect {
175        self
176    }
177
178    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
179        self
180    }
181
182    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
183        *self = value.take()?;
184        Ok(())
185    }
186}
187
188impl<T: SmallArray + TypePath + Send + Sync + 'static> Typed for SmallVec<T>
189where
190    T::Item: FromReflect + MaybeTyped + TypePath,
191{
192    fn type_info() -> &'static TypeInfo {
193        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
194        CELL.get_or_insert::<Self, _>(|| {
195            TypeInfo::List(
196                ListInfo::new::<Self, T::Item>()
197                    .with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")])),
198            )
199        })
200    }
201}
202
203impl_type_path!(::smallvec::SmallVec<T: SmallArray>);
204
205impl<T: SmallArray + TypePath + Send + Sync> FromReflect for SmallVec<T>
206where
207    T::Item: FromReflect + MaybeTyped + TypePath,
208{
209    fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
210        let ref_list = reflect.reflect_ref().as_list().ok()?;
211
212        let mut new_list = Self::with_capacity(ref_list.len());
213
214        for field in ref_list.iter() {
215            new_list.push(<T as SmallArray>::Item::from_reflect(field)?);
216        }
217
218        Some(new_list)
219    }
220}
221
222impl<T: SmallArray + TypePath + Send + Sync> GetTypeRegistration for SmallVec<T>
223where
224    T::Item: FromReflect + MaybeTyped + TypePath,
225{
226    fn get_type_registration() -> TypeRegistration {
227        let mut registration = TypeRegistration::of::<SmallVec<T>>();
228        registration.insert::<ReflectFromPtr>(FromType::<SmallVec<T>>::from_type());
229        registration
230    }
231}
232
233#[cfg(feature = "functions")]
234crate::func::macros::impl_function_traits!(SmallVec<T>; <T: SmallArray + TypePath + Send + Sync> where T::Item: FromReflect + MaybeTyped + TypePath);