1use crate::generics::impl_generic_info_methods;
5use crate::{
6 type_info::impl_type_methods, utility::reflect_hasher, ApplyError, Generics, MaybeTyped,
7 PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo,
8 TypePath,
9};
10use alloc::{boxed::Box, vec::Vec};
11use bevy_reflect_derive::impl_type_path;
12use core::{
13 any::Any,
14 fmt::{Debug, Formatter},
15 hash::{Hash, Hasher},
16};
17
18pub trait Array: PartialReflect {
54 fn get(&self, index: usize) -> Option<&dyn PartialReflect>;
56
57 fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
59
60 fn len(&self) -> usize;
62
63 fn is_empty(&self) -> bool {
65 self.len() == 0
66 }
67
68 fn iter(&self) -> ArrayIter<'_>;
70
71 fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>>;
73
74 fn to_dynamic_array(&self) -> DynamicArray {
76 DynamicArray {
77 represented_type: self.get_represented_type_info(),
78 values: self.iter().map(PartialReflect::to_dynamic).collect(),
79 }
80 }
81
82 fn get_represented_array_info(&self) -> Option<&'static ArrayInfo> {
84 self.get_represented_type_info()?.as_array().ok()
85 }
86}
87
88#[derive(Clone, Debug)]
90pub struct ArrayInfo {
91 ty: Type,
92 generics: Generics,
93 item_info: fn() -> Option<&'static TypeInfo>,
94 item_ty: Type,
95 capacity: usize,
96 #[cfg(feature = "reflect_documentation")]
97 docs: Option<&'static str>,
98}
99
100impl ArrayInfo {
101 pub fn new<TArray: Array + TypePath, TItem: Reflect + MaybeTyped + TypePath>(
107 capacity: usize,
108 ) -> Self {
109 Self {
110 ty: Type::of::<TArray>(),
111 generics: Generics::new(),
112 item_info: TItem::maybe_type_info,
113 item_ty: Type::of::<TItem>(),
114 capacity,
115 #[cfg(feature = "reflect_documentation")]
116 docs: None,
117 }
118 }
119
120 #[cfg(feature = "reflect_documentation")]
122 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
123 Self { docs, ..self }
124 }
125
126 pub fn capacity(&self) -> usize {
128 self.capacity
129 }
130
131 impl_type_methods!(ty);
132
133 pub fn item_info(&self) -> Option<&'static TypeInfo> {
138 (self.item_info)()
139 }
140
141 pub fn item_ty(&self) -> Type {
145 self.item_ty
146 }
147
148 #[cfg(feature = "reflect_documentation")]
150 pub fn docs(&self) -> Option<&'static str> {
151 self.docs
152 }
153
154 impl_generic_info_methods!(generics);
155}
156
157#[derive(Debug)]
167pub struct DynamicArray {
168 pub(crate) represented_type: Option<&'static TypeInfo>,
169 pub(crate) values: Box<[Box<dyn PartialReflect>]>,
170}
171
172impl DynamicArray {
173 #[inline]
175 pub fn new(values: Box<[Box<dyn PartialReflect>]>) -> Self {
176 Self {
177 represented_type: None,
178 values,
179 }
180 }
181
182 pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
190 if let Some(represented_type) = represented_type {
191 assert!(
192 matches!(represented_type, TypeInfo::Array(_)),
193 "expected TypeInfo::Array but received: {represented_type:?}"
194 );
195 }
196
197 self.represented_type = represented_type;
198 }
199}
200
201impl PartialReflect for DynamicArray {
202 #[inline]
203 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
204 self.represented_type
205 }
206
207 #[inline]
208 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
209 self
210 }
211
212 #[inline]
213 fn as_partial_reflect(&self) -> &dyn PartialReflect {
214 self
215 }
216
217 #[inline]
218 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
219 self
220 }
221
222 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
223 Err(self)
224 }
225
226 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
227 None
228 }
229
230 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
231 None
232 }
233
234 fn apply(&mut self, value: &dyn PartialReflect) {
235 array_apply(self, value);
236 }
237
238 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
239 array_try_apply(self, value)
240 }
241
242 #[inline]
243 fn reflect_kind(&self) -> ReflectKind {
244 ReflectKind::Array
245 }
246
247 #[inline]
248 fn reflect_ref(&self) -> ReflectRef<'_> {
249 ReflectRef::Array(self)
250 }
251
252 #[inline]
253 fn reflect_mut(&mut self) -> ReflectMut<'_> {
254 ReflectMut::Array(self)
255 }
256
257 #[inline]
258 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
259 ReflectOwned::Array(self)
260 }
261
262 #[inline]
263 fn reflect_hash(&self) -> Option<u64> {
264 array_hash(self)
265 }
266
267 fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
268 array_partial_eq(self, value)
269 }
270
271 fn reflect_partial_cmp(&self, value: &dyn PartialReflect) -> Option<::core::cmp::Ordering> {
272 array_partial_cmp(self, value)
273 }
274
275 fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
276 write!(f, "DynamicArray(")?;
277 array_debug(self, f)?;
278 write!(f, ")")
279 }
280
281 #[inline]
282 fn is_dynamic(&self) -> bool {
283 true
284 }
285}
286
287impl Array for DynamicArray {
288 #[inline]
289 fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
290 self.values.get(index).map(|value| &**value)
291 }
292
293 #[inline]
294 fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
295 self.values.get_mut(index).map(|value| &mut **value)
296 }
297
298 #[inline]
299 fn len(&self) -> usize {
300 self.values.len()
301 }
302
303 #[inline]
304 fn iter(&self) -> ArrayIter<'_> {
305 ArrayIter::new(self)
306 }
307
308 #[inline]
309 fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> {
310 self.values.into_vec()
311 }
312}
313
314impl FromIterator<Box<dyn PartialReflect>> for DynamicArray {
315 fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(values: I) -> Self {
316 Self {
317 represented_type: None,
318 values: values.into_iter().collect::<Vec<_>>().into_boxed_slice(),
319 }
320 }
321}
322
323impl<T: PartialReflect> FromIterator<T> for DynamicArray {
324 fn from_iter<I: IntoIterator<Item = T>>(values: I) -> Self {
325 values
326 .into_iter()
327 .map(|value| Box::new(value).into_partial_reflect())
328 .collect()
329 }
330}
331
332impl IntoIterator for DynamicArray {
333 type Item = Box<dyn PartialReflect>;
334 type IntoIter = alloc::vec::IntoIter<Self::Item>;
335
336 fn into_iter(self) -> Self::IntoIter {
337 self.values.into_vec().into_iter()
338 }
339}
340
341impl<'a> IntoIterator for &'a DynamicArray {
342 type Item = &'a dyn PartialReflect;
343 type IntoIter = ArrayIter<'a>;
344
345 fn into_iter(self) -> Self::IntoIter {
346 self.iter()
347 }
348}
349
350impl_type_path!((in bevy_reflect) DynamicArray);
351
352pub struct ArrayIter<'a> {
354 array: &'a dyn Array,
355 index: usize,
356}
357
358impl ArrayIter<'_> {
359 #[inline]
361 pub const fn new(array: &dyn Array) -> ArrayIter<'_> {
362 ArrayIter { array, index: 0 }
363 }
364}
365
366impl<'a> Iterator for ArrayIter<'a> {
367 type Item = &'a dyn PartialReflect;
368
369 #[inline]
370 fn next(&mut self) -> Option<Self::Item> {
371 let value = self.array.get(self.index);
372 self.index += value.is_some() as usize;
373 value
374 }
375
376 #[inline]
377 fn size_hint(&self) -> (usize, Option<usize>) {
378 let size = self.array.len();
379 (size, Some(size))
380 }
381}
382
383impl<'a> ExactSizeIterator for ArrayIter<'a> {}
384
385#[inline]
387pub fn array_hash<A: Array + ?Sized>(array: &A) -> Option<u64> {
388 let mut hasher = reflect_hasher();
389 Any::type_id(array).hash(&mut hasher);
390 array.len().hash(&mut hasher);
391 for value in array.iter() {
392 hasher.write_u64(value.reflect_hash()?);
393 }
394 Some(hasher.finish())
395}
396
397#[inline]
404pub fn array_apply<A: Array + ?Sized>(array: &mut A, reflect: &dyn PartialReflect) {
405 if let ReflectRef::Array(reflect_array) = reflect.reflect_ref() {
406 if array.len() != reflect_array.len() {
407 panic!("Attempted to apply different sized `Array` types.");
408 }
409 for (i, value) in reflect_array.iter().enumerate() {
410 let v = array.get_mut(i).unwrap();
411 v.apply(value);
412 }
413 } else {
414 panic!("Attempted to apply a non-`Array` type to an `Array` type.");
415 }
416}
417
418#[inline]
428pub fn array_try_apply<A: Array>(
429 array: &mut A,
430 reflect: &dyn PartialReflect,
431) -> Result<(), ApplyError> {
432 let reflect_array = reflect.reflect_ref().as_array()?;
433
434 if array.len() != reflect_array.len() {
435 return Err(ApplyError::DifferentSize {
436 from_size: reflect_array.len(),
437 to_size: array.len(),
438 });
439 }
440
441 for (i, value) in reflect_array.iter().enumerate() {
442 let v = array.get_mut(i).unwrap();
443 v.try_apply(value)?;
444 }
445
446 Ok(())
447}
448
449#[inline]
454pub fn array_partial_eq<A: Array + ?Sized>(
455 array: &A,
456 reflect: &dyn PartialReflect,
457) -> Option<bool> {
458 match reflect.reflect_ref() {
459 ReflectRef::Array(reflect_array) if reflect_array.len() == array.len() => {
460 for (a, b) in array.iter().zip(reflect_array.iter()) {
461 let eq_result = a.reflect_partial_eq(b);
462 if let failed @ (Some(false) | None) = eq_result {
463 return failed;
464 }
465 }
466 }
467 _ => return Some(false),
468 }
469
470 Some(true)
471}
472
473#[inline]
478pub fn array_partial_cmp<A: Array + ?Sized>(
479 array: &A,
480 reflect: &dyn PartialReflect,
481) -> Option<::core::cmp::Ordering> {
482 let ReflectRef::Array(reflect_array) = reflect.reflect_ref() else {
483 return None;
484 };
485
486 let min_len = core::cmp::min(array.len(), reflect_array.len());
487
488 for (a, b) in array.iter().zip(reflect_array.iter()).take(min_len) {
489 match a.reflect_partial_cmp(b) {
490 None => return None,
491 Some(core::cmp::Ordering::Equal) => continue,
492 Some(ord) => return Some(ord),
493 }
494 }
495
496 Some(array.len().cmp(&reflect_array.len()))
498}
499
500#[inline]
518pub fn array_debug(dyn_array: &dyn Array, f: &mut Formatter<'_>) -> core::fmt::Result {
519 let mut debug = f.debug_list();
520 for item in dyn_array.iter() {
521 debug.entry(&item as &dyn Debug);
522 }
523 debug.finish()
524}
525#[cfg(test)]
526mod tests {
527 use crate::Reflect;
528 use alloc::boxed::Box;
529
530 #[test]
531 fn next_index_increment() {
532 const SIZE: usize = if cfg!(debug_assertions) {
533 4
534 } else {
535 usize::MAX
537 };
538
539 let b = Box::new([(); SIZE]).into_reflect();
540
541 let array = b.reflect_ref().as_array().unwrap();
542
543 let mut iter = array.iter();
544 iter.index = SIZE - 1;
545 assert!(iter.next().is_some());
546
547 assert!(iter.next().is_none());
549 assert!(iter.index == SIZE);
550 assert!(iter.next().is_none());
551 assert!(iter.index == SIZE);
552 }
553}