1use 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#[rust_analyzer::completions(ignore_flyimport_methods)]
59pub trait List: PartialReflect {
60 fn get(&self, index: usize) -> Option<&dyn PartialReflect>;
62
63 fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
65
66 fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>);
72
73 fn remove(&mut self, index: usize) -> Box<dyn PartialReflect>;
79
80 fn push(&mut self, value: Box<dyn PartialReflect>) {
82 self.insert(self.len(), value);
83 }
84
85 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 fn len(&self) -> usize;
96
97 fn is_empty(&self) -> bool {
99 self.len() == 0
100 }
101
102 fn iter(&self) -> ListIter<'_>;
104
105 fn drain(&mut self) -> Vec<Box<dyn PartialReflect>>;
110
111 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 fn get_represented_list_info(&self) -> Option<&'static ListInfo> {
126 self.get_represented_type_info()?.as_list().ok()
127 }
128}
129
130#[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 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 #[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 pub fn item_info(&self) -> Option<&'static TypeInfo> {
167 (self.item_info)()
168 }
169
170 pub fn item_ty(&self) -> Type {
174 self.item_ty
175 }
176
177 #[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#[derive(Default)]
188pub struct DynamicList {
189 represented_type: Option<&'static TypeInfo>,
190 values: Vec<Box<dyn PartialReflect>>,
191}
192
193impl DynamicList {
194 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 pub fn push<T: PartialReflect>(&mut self, value: T) {
213 self.values.push(Box::new(value));
214 }
215
216 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
390pub struct ListIter<'a> {
392 list: &'a dyn List,
393 index: usize,
394}
395
396impl ListIter<'_> {
397 #[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#[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#[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#[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#[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#[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#[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 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 assert!(iter.next().is_none());
597 assert!(iter.index == SIZE);
598 assert!(iter.next().is_none());
599 assert!(iter.index == SIZE);
600 }
601}