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
17pub trait List: PartialReflect {
55 fn get(&self, index: usize) -> Option<&dyn PartialReflect>;
57
58 fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
60
61 fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>);
67
68 fn remove(&mut self, index: usize) -> Box<dyn PartialReflect>;
74
75 fn push(&mut self, value: Box<dyn PartialReflect>) {
77 self.insert(self.len(), value);
78 }
79
80 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 fn len(&self) -> usize;
91
92 fn is_empty(&self) -> bool {
94 self.len() == 0
95 }
96
97 fn iter(&self) -> ListIter<'_>;
99
100 fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
105
106 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 fn get_represented_list_info(&self) -> Option<&'static ListInfo> {
116 self.get_represented_type_info()?.as_list().ok()
117 }
118}
119
120#[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 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 #[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 pub fn item_info(&self) -> Option<&'static TypeInfo> {
157 (self.item_info)()
158 }
159
160 pub fn item_ty(&self) -> Type {
164 self.item_ty
165 }
166
167 #[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#[derive(Default)]
178pub struct DynamicList {
179 represented_type: Option<&'static TypeInfo>,
180 values: Vec<Box<dyn PartialReflect>>,
181}
182
183impl DynamicList {
184 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 pub fn push<T: PartialReflect>(&mut self, value: T) {
203 self.values.push(Box::new(value));
204 }
205
206 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
376pub struct ListIter<'a> {
378 list: &'a dyn List,
379 index: usize,
380}
381
382impl ListIter<'_> {
383 #[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#[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#[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#[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#[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#[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 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 assert!(iter.next().is_none());
557 assert!(iter.index == SIZE);
558 assert!(iter.next().is_none());
559 assert!(iter.index == SIZE);
560 }
561}