godot_core/builtin/collections/array.rs
1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8use std::cell::OnceCell;
9use std::marker::PhantomData;
10use std::{cmp, fmt};
11
12use godot_ffi as sys;
13use sys::{ffi_methods, interface_fn, GodotFfi};
14
15use crate::builtin::*;
16use crate::meta;
17use crate::meta::error::{ConvertError, FromGodotError, FromVariantError};
18use crate::meta::signed_range::SignedRange;
19use crate::meta::{
20 element_godot_type_name, element_variant_type, ArrayElement, AsArg, ClassId, ElementType,
21 ExtVariantType, FromGodot, GodotConvert, GodotFfiVariant, GodotType, PropertyHintInfo, RefArg,
22 ToGodot,
23};
24use crate::obj::{bounds, Bounds, DynGd, Gd, GodotClass};
25use crate::registry::property::{BuiltinExport, Export, Var};
26
27/// Godot's `Array` type.
28///
29/// Versatile, linear storage container for all types that can be represented inside a `Variant`. \
30/// For space-efficient storage, consider using [`PackedArray<T>`][crate::builtin::PackedArray] or `Vec<T>`.
31///
32/// Check out the [book](https://godot-rust.github.io/book/godot-api/builtins.html#arrays-and-dictionaries) for a tutorial on arrays.
33///
34/// # Typed arrays
35///
36/// Godot's `Array` can be either typed or untyped.
37///
38/// An untyped array can contain any kind of [`Variant`], even different types in the same array.
39/// We represent this in Rust as `VariantArray`, which is just a type alias for `Array<Variant>`.
40///
41/// Godot also supports typed arrays, which are also just `Variant` arrays under the hood, but with
42/// runtime checks, so that no values of the wrong type are inserted into the array. We represent this as
43/// `Array<T>`, where the type `T` must implement `ArrayElement`. Some types like `Array<T>` cannot
44/// be stored inside arrays, as Godot prevents nesting.
45///
46/// If you plan to use any integer or float types apart from `i64` and `f64`, read
47/// [this documentation](../meta/trait.ArrayElement.html#integer-and-float-types).
48///
49/// # Reference semantics
50///
51/// Like in GDScript, `Array` acts as a reference type: multiple `Array` instances may
52/// refer to the same underlying array, and changes to one are visible in the other.
53///
54/// To create a copy that shares data with the original array, use [`Clone::clone()`].
55/// If you want to create a copy of the data, use [`duplicate_shallow()`][Self::duplicate_shallow]
56/// or [`duplicate_deep()`][Self::duplicate_deep].
57///
58/// # Typed array example
59///
60/// ```no_run
61/// # use godot::prelude::*;
62/// // Create typed Array<i64> and add values.
63/// let mut array = Array::new();
64/// array.push(10);
65/// array.push(20);
66/// array.push(30);
67///
68/// // Or create the same array in a single expression.
69/// let array = array![10, 20, 30];
70///
71/// // Access elements.
72/// let value: i64 = array.at(0); // 10
73/// let maybe: Option<i64> = array.get(3); // None
74///
75/// // Iterate over i64 elements.
76/// for value in array.iter_shared() {
77/// println!("{value}");
78/// }
79///
80/// // Clone array (shares the reference), and overwrite elements through clone.
81/// let mut cloned = array.clone();
82/// cloned.set(0, 50); // [50, 20, 30]
83/// cloned.remove(1); // [50, 30]
84/// cloned.pop(); // [50]
85///
86/// // Changes will be reflected in the original array.
87/// assert_eq!(array.len(), 1);
88/// assert_eq!(array.front(), Some(50));
89/// ```
90///
91/// # Untyped array example
92///
93/// ```no_run
94/// # use godot::prelude::*;
95/// // VariantArray allows dynamic element types.
96/// let mut array = VariantArray::new();
97/// array.push(&10.to_variant());
98/// array.push(&"Hello".to_variant());
99///
100/// // Or equivalent, use the `varray!` macro which converts each element.
101/// let array = varray![10, "Hello"];
102///
103/// // Access elements.
104/// let value: Variant = array.at(0);
105/// let value: i64 = array.at(0).to(); // Variant::to() extracts i64.
106/// let maybe: Result<i64, _> = array.at(1).try_to(); // "Hello" is not i64 -> Err.
107/// let maybe: Option<Variant> = array.get(3);
108///
109/// // ...and so on.
110/// ```
111///
112/// # Working with signed ranges and steps
113///
114/// For negative indices, use [`wrapped()`](crate::meta::wrapped).
115///
116/// ```no_run
117/// # use godot::builtin::array;
118/// # use godot::meta::wrapped;
119/// let arr = array![0, 1, 2, 3, 4, 5];
120///
121/// // The values of `begin` (inclusive) and `end` (exclusive) will be clamped to the array size.
122/// let clamped_array = arr.subarray_deep(999..99999, None);
123/// assert_eq!(clamped_array, array![]);
124///
125/// // If either `begin` or `end` is negative, its value is relative to the end of the array.
126/// let sub = arr.subarray_shallow(wrapped(-1..-5), None);
127/// assert_eq!(sub, array![5, 3]);
128///
129/// // If `end` is not specified, the range spans through whole array.
130/// let sub = arr.subarray_deep(1.., None);
131/// assert_eq!(sub, array![1, 2, 3, 4, 5]);
132/// let other_clamped_array = arr.subarray_shallow(5.., Some(2));
133/// assert_eq!(other_clamped_array, array![5]);
134///
135/// // If specified, `step` is the relative index between source elements. It can be negative,
136/// // in which case `begin` must be higher than `end`.
137/// let sub = arr.subarray_shallow(wrapped(-1..-5), Some(-2));
138/// assert_eq!(sub, array![5, 3]);
139/// ```
140///
141/// # Thread safety
142///
143/// Usage is safe if the `Array` is used on a single thread only. Concurrent reads on
144/// different threads are also safe, but any writes must be externally synchronized. The Rust
145/// compiler will enforce this as long as you use only Rust threads, but it cannot protect against
146/// concurrent modification on other threads (e.g. created through GDScript).
147///
148/// # Element type safety
149///
150/// We provide a richer set of element types than Godot, for convenience and stronger invariants in your _Rust_ code.
151/// This, however, means that the Godot representation of such arrays is not capable of incorporating the additional "Rust-side" information.
152/// This can lead to situations where GDScript code or the editor UI can insert values that do not fulfill the Rust-side invariants.
153/// The library offers some best-effort protection in Debug mode, but certain errors may only occur on element access, in the form of panics.
154///
155/// Concretely, the following types lose type information when passed to Godot. If you want 100% bullet-proof arrays, avoid those.
156/// - Non-`i64` integers: `i8`, `i16`, `i32`, `u8`, `u16`, `u32`. (`u64` is unsupported).
157/// - Non-`f64` floats: `f32`.
158/// - Non-null objects: [`Gd<T>`][crate::obj::Gd].
159/// Godot generally allows `null` in arrays due to default-constructability, e.g. when using `resize()`.
160/// The Godot-faithful (but less convenient) alternative is to use `Option<Gd<T>>` element types.
161/// - Objects with dyn-trait association: [`DynGd<T, D>`][crate::obj::DynGd].
162/// Godot doesn't know Rust traits and will only see the `T` part.
163///
164/// # Differences from GDScript
165///
166/// Unlike GDScript, all indices and sizes are unsigned, so negative indices are not supported.
167///
168/// # Godot docs
169///
170/// [`Array[T]` (stable)](https://docs.godotengine.org/en/stable/classes/class_array.html)
171pub struct Array<T: ArrayElement> {
172 // Safety Invariant: The type of all values in `opaque` matches the type `T`.
173 opaque: sys::types::OpaqueArray,
174 _phantom: PhantomData<T>,
175
176 /// Lazily computed and cached element type information.
177 cached_element_type: OnceCell<ElementType>,
178}
179
180/// Guard that can only call immutable methods on the array.
181struct ImmutableInnerArray<'a> {
182 inner: inner::InnerArray<'a>,
183}
184
185impl<'a> std::ops::Deref for ImmutableInnerArray<'a> {
186 type Target = inner::InnerArray<'a>;
187
188 fn deref(&self) -> &Self::Target {
189 &self.inner
190 }
191}
192
193/// A Godot `Array` without an assigned type.
194pub type VariantArray = Array<Variant>;
195
196// TODO check if these return a typed array
197impl_builtin_froms!(VariantArray;
198 PackedByteArray => array_from_packed_byte_array,
199 PackedColorArray => array_from_packed_color_array,
200 PackedFloat32Array => array_from_packed_float32_array,
201 PackedFloat64Array => array_from_packed_float64_array,
202 PackedInt32Array => array_from_packed_int32_array,
203 PackedInt64Array => array_from_packed_int64_array,
204 PackedStringArray => array_from_packed_string_array,
205 PackedVector2Array => array_from_packed_vector2_array,
206 PackedVector3Array => array_from_packed_vector3_array,
207);
208
209#[cfg(since_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.3")))]
210impl_builtin_froms!(VariantArray;
211 PackedVector4Array => array_from_packed_vector4_array,
212);
213
214impl<T: ArrayElement> Array<T> {
215 fn from_opaque(opaque: sys::types::OpaqueArray) -> Self {
216 // Note: type is not yet checked at this point, because array has not yet been initialized!
217 Self {
218 opaque,
219 _phantom: PhantomData,
220 cached_element_type: OnceCell::new(),
221 }
222 }
223
224 /// Constructs an empty `Array`.
225 pub fn new() -> Self {
226 Self::default()
227 }
228
229 /// ⚠️ Returns the value at the specified index.
230 ///
231 /// This replaces the `Index` trait, which cannot be implemented for `Array` as references are not guaranteed to remain valid.
232 ///
233 /// # Panics
234 ///
235 /// If `index` is out of bounds. If you want to handle out-of-bounds access, use [`get()`](Self::get) instead.
236 pub fn at(&self, index: usize) -> T {
237 // Panics on out-of-bounds.
238 let ptr = self.ptr(index);
239
240 // SAFETY: `ptr` is a live pointer to a variant since `ptr.is_null()` just verified that the index is not out of bounds.
241 let variant = unsafe { Variant::borrow_var_sys(ptr) };
242 T::from_variant(variant)
243 }
244
245 /// Returns the value at the specified index, or `None` if the index is out-of-bounds.
246 ///
247 /// If you know the index is correct, use [`at()`](Self::at) instead.
248 pub fn get(&self, index: usize) -> Option<T> {
249 let ptr = self.ptr_or_null(index);
250 if ptr.is_null() {
251 None
252 } else {
253 // SAFETY: `ptr` is a live pointer to a variant since `ptr.is_null()` just verified that the index is not out of bounds.
254 let variant = unsafe { Variant::borrow_var_sys(ptr) };
255 Some(T::from_variant(variant))
256 }
257 }
258
259 /// Returns `true` if the array contains the given value. Equivalent of `has` in GDScript.
260 pub fn contains(&self, value: impl AsArg<T>) -> bool {
261 meta::arg_into_ref!(value: T);
262 self.as_inner().has(&value.to_variant())
263 }
264
265 /// Returns the number of times a value is in the array.
266 pub fn count(&self, value: impl AsArg<T>) -> usize {
267 meta::arg_into_ref!(value: T);
268 to_usize(self.as_inner().count(&value.to_variant()))
269 }
270
271 /// Returns the number of elements in the array. Equivalent of `size()` in Godot.
272 ///
273 /// Retrieving the size incurs an FFI call. If you know the size hasn't changed, you may consider storing
274 /// it in a variable. For loops, prefer iterators.
275 #[doc(alias = "size")]
276 pub fn len(&self) -> usize {
277 to_usize(self.as_inner().size())
278 }
279
280 /// Returns `true` if the array is empty.
281 ///
282 /// Checking for emptiness incurs an FFI call. If you know the size hasn't changed, you may consider storing
283 /// it in a variable. For loops, prefer iterators.
284 pub fn is_empty(&self) -> bool {
285 self.as_inner().is_empty()
286 }
287
288 crate::declare_hash_u32_method! {
289 /// Returns a 32-bit integer hash value representing the array and its contents.
290 ///
291 /// Note: Arrays with equal content will always produce identical hash values. However, the
292 /// reverse is not true. Returning identical hash values does not imply the arrays are equal,
293 /// because different arrays can have identical hash values due to hash collisions.
294 }
295
296 #[deprecated = "renamed to hash_u32"]
297 pub fn hash(&self) -> u32 {
298 self.as_inner().hash().try_into().unwrap()
299 }
300
301 /// Returns the first element in the array, or `None` if the array is empty.
302 #[doc(alias = "first")]
303 pub fn front(&self) -> Option<T> {
304 (!self.is_empty()).then(|| {
305 let variant = self.as_inner().front();
306 T::from_variant(&variant)
307 })
308 }
309
310 /// Returns the last element in the array, or `None` if the array is empty.
311 #[doc(alias = "last")]
312 pub fn back(&self) -> Option<T> {
313 (!self.is_empty()).then(|| {
314 let variant = self.as_inner().back();
315 T::from_variant(&variant)
316 })
317 }
318
319 /// Clears the array, removing all elements.
320 pub fn clear(&mut self) {
321 self.debug_ensure_mutable();
322
323 // SAFETY: No new values are written to the array, we only remove values from the array.
324 unsafe { self.as_inner_mut() }.clear();
325 }
326
327 /// Sets the value at the specified index.
328 ///
329 /// # Panics
330 ///
331 /// If `index` is out of bounds.
332 pub fn set(&mut self, index: usize, value: impl AsArg<T>) {
333 self.debug_ensure_mutable();
334
335 let ptr_mut = self.ptr_mut(index);
336
337 meta::arg_into_ref!(value: T);
338 let variant = value.to_variant();
339
340 // SAFETY: `ptr_mut` just checked that the index is not out of bounds.
341 unsafe { variant.move_into_var_ptr(ptr_mut) };
342 }
343
344 /// Appends an element to the end of the array.
345 ///
346 /// _Godot equivalents: `append` and `push_back`_
347 #[doc(alias = "append")]
348 #[doc(alias = "push_back")]
349 pub fn push(&mut self, value: impl AsArg<T>) {
350 self.debug_ensure_mutable();
351
352 meta::arg_into_ref!(value: T);
353
354 // SAFETY: The array has type `T` and we're writing a value of type `T` to it.
355 let mut inner = unsafe { self.as_inner_mut() };
356 inner.push_back(&value.to_variant());
357 }
358
359 /// Adds an element at the beginning of the array, in O(n).
360 ///
361 /// On large arrays, this method is much slower than [`push()`][Self::push], as it will move all the array's elements.
362 /// The larger the array, the slower `push_front()` will be.
363 pub fn push_front(&mut self, value: impl AsArg<T>) {
364 self.debug_ensure_mutable();
365
366 meta::arg_into_ref!(value: T);
367
368 // SAFETY: The array has type `T` and we're writing a value of type `T` to it.
369 let mut inner_array = unsafe { self.as_inner_mut() };
370 inner_array.push_front(&value.to_variant());
371 }
372
373 /// Removes and returns the last element of the array. Returns `None` if the array is empty.
374 ///
375 /// _Godot equivalent: `pop_back`_
376 #[doc(alias = "pop_back")]
377 pub fn pop(&mut self) -> Option<T> {
378 self.debug_ensure_mutable();
379
380 (!self.is_empty()).then(|| {
381 // SAFETY: We do not write any values to the array, we just remove one.
382 let variant = unsafe { self.as_inner_mut() }.pop_back();
383 T::from_variant(&variant)
384 })
385 }
386
387 /// Removes and returns the first element of the array, in O(n). Returns `None` if the array is empty.
388 ///
389 /// Note: On large arrays, this method is much slower than `pop()` as it will move all the
390 /// array's elements. The larger the array, the slower `pop_front()` will be.
391 pub fn pop_front(&mut self) -> Option<T> {
392 self.debug_ensure_mutable();
393
394 (!self.is_empty()).then(|| {
395 // SAFETY: We do not write any values to the array, we just remove one.
396 let variant = unsafe { self.as_inner_mut() }.pop_front();
397 T::from_variant(&variant)
398 })
399 }
400
401 /// ⚠️ Inserts a new element before the index. The index must be valid or the end of the array (`index == len()`).
402 ///
403 /// On large arrays, this method is much slower than [`push()`][Self::push], as it will move all the array's elements after the inserted element.
404 /// The larger the array, the slower `insert()` will be.
405 ///
406 /// # Panics
407 /// If `index > len()`.
408 pub fn insert(&mut self, index: usize, value: impl AsArg<T>) {
409 self.debug_ensure_mutable();
410
411 let len = self.len();
412 assert!(
413 index <= len,
414 "Array insertion index {index} is out of bounds: length is {len}",
415 );
416
417 meta::arg_into_ref!(value: T);
418
419 // SAFETY: The array has type `T` and we're writing a value of type `T` to it.
420 unsafe { self.as_inner_mut() }.insert(to_i64(index), &value.to_variant());
421 }
422
423 /// ⚠️ Removes and returns the element at the specified index. Equivalent of `pop_at` in GDScript.
424 ///
425 /// On large arrays, this method is much slower than [`pop()`][Self::pop] as it will move all the array's
426 /// elements after the removed element. The larger the array, the slower `remove()` will be.
427 ///
428 /// # Panics
429 ///
430 /// If `index` is out of bounds.
431 #[doc(alias = "pop_at")]
432 pub fn remove(&mut self, index: usize) -> T {
433 self.debug_ensure_mutable();
434
435 self.check_bounds(index);
436
437 // SAFETY: We do not write any values to the array, we just remove one.
438 let variant = unsafe { self.as_inner_mut() }.pop_at(to_i64(index));
439 T::from_variant(&variant)
440 }
441
442 /// Removes the first occurrence of a value from the array.
443 ///
444 /// If the value does not exist in the array, nothing happens. To remove an element by index, use [`remove()`][Self::remove] instead.
445 ///
446 /// On large arrays, this method is much slower than [`pop()`][Self::pop], as it will move all the array's
447 /// elements after the removed element.
448 pub fn erase(&mut self, value: impl AsArg<T>) {
449 self.debug_ensure_mutable();
450
451 meta::arg_into_ref!(value: T);
452
453 // SAFETY: We don't write anything to the array.
454 unsafe { self.as_inner_mut() }.erase(&value.to_variant());
455 }
456
457 /// Assigns the given value to all elements in the array. This can be used together with
458 /// `resize` to create an array with a given size and initialized elements.
459 pub fn fill(&mut self, value: impl AsArg<T>) {
460 self.debug_ensure_mutable();
461
462 meta::arg_into_ref!(value: T);
463
464 // SAFETY: The array has type `T` and we're writing values of type `T` to it.
465 unsafe { self.as_inner_mut() }.fill(&value.to_variant());
466 }
467
468 /// Resizes the array to contain a different number of elements.
469 ///
470 /// If the new size is smaller than the current size, then it removes elements from the end. If the new size is bigger than the current one
471 /// then the new elements are set to `value`.
472 ///
473 /// If you know that the new size is smaller, then consider using [`shrink`](Array::shrink) instead.
474 pub fn resize(&mut self, new_size: usize, value: impl AsArg<T>) {
475 self.debug_ensure_mutable();
476
477 let original_size = self.len();
478
479 // SAFETY: While we do insert `Variant::nil()` if the new size is larger, we then fill it with `value` ensuring that all values in the
480 // array are of type `T` still.
481 unsafe { self.as_inner_mut() }.resize(to_i64(new_size));
482
483 meta::arg_into_ref!(value: T);
484
485 // If new_size < original_size then this is an empty iterator and does nothing.
486 for i in original_size..new_size {
487 // Exception safety: if to_variant() panics, the array will become inconsistent (filled with non-T nils).
488 // At the moment (Nov 2024), this can only happen for u64, which isn't a valid Array element type.
489 // This could be changed to use clone() (if that doesn't panic) or store a variant without moving.
490 let variant = value.to_variant();
491
492 let ptr_mut = self.ptr_mut(i);
493
494 // SAFETY: we iterate pointer within bounds; ptr_mut() additionally checks them.
495 // ptr_mut() lookup could be optimized if we know the internal layout.
496 unsafe { variant.move_into_var_ptr(ptr_mut) };
497 }
498 }
499
500 /// Shrinks the array down to `new_size`.
501 ///
502 /// This will only change the size of the array if `new_size` is smaller than the current size. Returns `true` if the array was shrunk.
503 ///
504 /// If you want to increase the size of the array, use [`resize`](Array::resize) instead.
505 #[doc(alias = "resize")]
506 pub fn shrink(&mut self, new_size: usize) -> bool {
507 self.debug_ensure_mutable();
508
509 if new_size >= self.len() {
510 return false;
511 }
512
513 // SAFETY: Since `new_size` is less than the current size, we'll only be removing elements from the array.
514 unsafe { self.as_inner_mut() }.resize(to_i64(new_size));
515
516 true
517 }
518
519 /// Appends another array at the end of this array. Equivalent of `append_array` in GDScript.
520 pub fn extend_array(&mut self, other: &Array<T>) {
521 self.debug_ensure_mutable();
522
523 // SAFETY: `append_array` will only read values from `other`, and all types can be converted to `Variant`.
524 let other: &VariantArray = unsafe { other.assume_type_ref::<Variant>() };
525
526 // SAFETY: `append_array` will only write values gotten from `other` into `self`, and all values in `other` are guaranteed
527 // to be of type `T`.
528 let mut inner_self = unsafe { self.as_inner_mut() };
529 inner_self.append_array(other);
530 }
531
532 /// Returns a shallow copy of the array. All array elements are copied, but any reference types
533 /// (such as `Array`, `Dictionary` and `Object`) will still refer to the same value.
534 ///
535 /// To create a deep copy, use [`duplicate_deep()`][Self::duplicate_deep] instead.
536 /// To create a new reference to the same array data, use [`clone()`][Clone::clone].
537 pub fn duplicate_shallow(&self) -> Self {
538 // SAFETY: duplicate() returns a typed array with the same type as Self, and all values are taken from `self` so have the right type
539 let duplicate: Self = unsafe { self.as_inner().duplicate(false) };
540
541 // Note: cache is being set while initializing the duplicate as a return value for above call.
542 duplicate
543 }
544
545 /// Returns a deep copy of the array. All nested arrays and dictionaries are duplicated and
546 /// will not be shared with the original array. Note that any `Object`-derived elements will
547 /// still be shallow copied.
548 ///
549 /// To create a shallow copy, use [`duplicate_shallow()`][Self::duplicate_shallow] instead.
550 /// To create a new reference to the same array data, use [`clone()`][Clone::clone].
551 pub fn duplicate_deep(&self) -> Self {
552 // SAFETY: duplicate() returns a typed array with the same type as Self, and all values are taken from `self` so have the right type
553 let duplicate: Self = unsafe { self.as_inner().duplicate(true) };
554
555 // Note: cache is being set while initializing the duplicate as a return value for above call.
556 duplicate
557 }
558
559 /// Returns a sub-range `begin..end` as a new `Array`.
560 ///
561 /// Array elements are copied to the slice, but any reference types (such as `Array`,
562 /// `Dictionary` and `Object`) will still refer to the same value. To create a deep copy, use
563 /// [`subarray_deep()`][Self::subarray_deep] instead.
564 ///
565 /// _Godot equivalent: `slice`_
566 #[doc(alias = "slice")]
567 pub fn subarray_shallow(&self, range: impl SignedRange, step: Option<i32>) -> Self {
568 self.subarray_impl(range, step, false)
569 }
570
571 /// Returns a sub-range `begin..end` as a new `Array`.
572 ///
573 /// All nested arrays and dictionaries are duplicated and will not be shared with the original
574 /// array. Note that any `Object`-derived elements will still be shallow copied. To create a
575 /// shallow copy, use [`subarray_shallow()`][Self::subarray_shallow] instead.
576 ///
577 /// _Godot equivalent: `slice`_
578 #[doc(alias = "slice")]
579 pub fn subarray_deep(&self, range: impl SignedRange, step: Option<i32>) -> Self {
580 self.subarray_impl(range, step, true)
581 }
582
583 // Note: Godot will clamp values by itself.
584 fn subarray_impl(&self, range: impl SignedRange, step: Option<i32>, deep: bool) -> Self {
585 assert_ne!(step, Some(0), "subarray: step cannot be zero");
586
587 let step = step.unwrap_or(1);
588 let (begin, end) = range.signed();
589 let end = end.unwrap_or(i32::MAX as i64);
590
591 // SAFETY: slice() returns a typed array with the same type as Self, and all values are taken from `self` so have the right type.
592 let subarray: Self = unsafe { self.as_inner().slice(begin, end, step as i64, deep) };
593
594 subarray
595 }
596
597 /// Returns an iterator over the elements of the `Array`. Note that this takes the array
598 /// by reference but returns its elements by value, since they are internally converted from
599 /// `Variant`.
600 ///
601 /// Notice that it's possible to modify the `Array` through another reference while
602 /// iterating over it. This will not result in unsoundness or crashes, but will cause the
603 /// iterator to behave in an unspecified way.
604 pub fn iter_shared(&self) -> Iter<'_, T> {
605 Iter {
606 array: self,
607 next_idx: 0,
608 }
609 }
610
611 /// Returns the minimum value contained in the array if all elements are of comparable types.
612 ///
613 /// If the elements can't be compared or the array is empty, `None` is returned.
614 pub fn min(&self) -> Option<T> {
615 let min = self.as_inner().min();
616 (!min.is_nil()).then(|| T::from_variant(&min))
617 }
618
619 /// Returns the maximum value contained in the array if all elements are of comparable types.
620 ///
621 /// If the elements can't be compared or the array is empty, `None` is returned.
622 pub fn max(&self) -> Option<T> {
623 let max = self.as_inner().max();
624 (!max.is_nil()).then(|| T::from_variant(&max))
625 }
626
627 /// Returns a random element from the array, or `None` if it is empty.
628 pub fn pick_random(&self) -> Option<T> {
629 (!self.is_empty()).then(|| {
630 let variant = self.as_inner().pick_random();
631 T::from_variant(&variant)
632 })
633 }
634
635 /// Searches the array for the first occurrence of a value and returns its index, or `None` if
636 /// not found.
637 ///
638 /// Starts searching at index `from`; pass `None` to search the entire array.
639 pub fn find(&self, value: impl AsArg<T>, from: Option<usize>) -> Option<usize> {
640 meta::arg_into_ref!(value: T);
641
642 let from = to_i64(from.unwrap_or(0));
643 let index = self.as_inner().find(&value.to_variant(), from);
644 if index >= 0 {
645 Some(index.try_into().unwrap())
646 } else {
647 None
648 }
649 }
650
651 /// Searches the array backwards for the last occurrence of a value and returns its index, or
652 /// `None` if not found.
653 ///
654 /// Starts searching at index `from`; pass `None` to search the entire array.
655 pub fn rfind(&self, value: impl AsArg<T>, from: Option<usize>) -> Option<usize> {
656 meta::arg_into_ref!(value: T);
657
658 let from = from.map(to_i64).unwrap_or(-1);
659 let index = self.as_inner().rfind(&value.to_variant(), from);
660
661 // It's not documented, but `rfind` returns -1 if not found.
662 if index >= 0 {
663 Some(to_usize(index))
664 } else {
665 None
666 }
667 }
668
669 /// Finds the index of a value in a sorted array using binary search.
670 ///
671 /// If the value is not present in the array, returns the insertion index that would maintain sorting order.
672 ///
673 /// Calling `bsearch` on an unsorted array results in unspecified behavior. Consider using `sort()` to ensure the sorting
674 /// order is compatible with your callable's ordering.
675 pub fn bsearch(&self, value: impl AsArg<T>) -> usize {
676 meta::arg_into_ref!(value: T);
677
678 to_usize(self.as_inner().bsearch(&value.to_variant(), true))
679 }
680
681 /// Finds the index of a value in a sorted array using binary search, with type-safe custom predicate.
682 ///
683 /// The comparator function should return an ordering that indicates whether its argument is `Less`, `Equal` or `Greater` the desired value.
684 /// For example, for an ascending-ordered array, a simple predicate searching for a constant value would be `|elem| elem.cmp(&4)`.
685 /// See also [`slice::binary_search_by()`].
686 ///
687 /// If the value is found, returns `Ok(index)` with its index. Otherwise, returns `Err(index)`, where `index` is the insertion index
688 /// that would maintain sorting order.
689 ///
690 /// Calling `bsearch_by` on an unsorted array results in unspecified behavior. Consider using [`sort_by()`] to ensure
691 /// the sorting order is compatible with your callable's ordering.
692 pub fn bsearch_by<F>(&self, mut func: F) -> Result<usize, usize>
693 where
694 F: FnMut(&T) -> cmp::Ordering + 'static,
695 {
696 // Early exit; later code relies on index 0 being present.
697 if self.is_empty() {
698 return Err(0);
699 }
700
701 // We need one dummy element of type T, because Godot's bsearch_custom() checks types (so Variant::nil() can't be passed).
702 // Optimization: roundtrip Variant -> T -> Variant could be avoided, but anyone needing speed would use Rust binary search...
703 let ignored_value = self.at(0);
704 let ignored_value = meta::owned_into_arg(ignored_value);
705
706 let godot_comparator = |args: &[&Variant]| {
707 let value = T::from_variant(args[0]);
708 let is_less = matches!(func(&value), cmp::Ordering::Less);
709
710 is_less.to_variant()
711 };
712
713 let debug_name = std::any::type_name::<F>();
714 let index = Callable::with_scoped_fn(debug_name, godot_comparator, |pred| {
715 self.bsearch_custom(ignored_value, pred)
716 });
717
718 if let Some(value_at_index) = self.get(index) {
719 if func(&value_at_index) == cmp::Ordering::Equal {
720 return Ok(index);
721 }
722 }
723
724 Err(index)
725 }
726
727 /// Finds the index of a value in a sorted array using binary search, with `Callable` custom predicate.
728 ///
729 /// The callable `pred` takes two elements `(a, b)` and should return if `a < b` (strictly less).
730 /// For a type-safe version, check out [`bsearch_by()`][Self::bsearch_by].
731 ///
732 /// If the value is not present in the array, returns the insertion index that would maintain sorting order.
733 ///
734 /// Calling `bsearch_custom` on an unsorted array results in unspecified behavior. Consider using `sort_custom()` to ensure
735 /// the sorting order is compatible with your callable's ordering.
736 pub fn bsearch_custom(&self, value: impl AsArg<T>, pred: &Callable) -> usize {
737 meta::arg_into_ref!(value: T);
738
739 to_usize(
740 self.as_inner()
741 .bsearch_custom(&value.to_variant(), pred, true),
742 )
743 }
744
745 /// Reverses the order of the elements in the array.
746 pub fn reverse(&mut self) {
747 self.debug_ensure_mutable();
748
749 // SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
750 unsafe { self.as_inner_mut() }.reverse();
751 }
752
753 /// Sorts the array.
754 ///
755 /// The sorting algorithm used is not [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
756 /// This means that values considered equal may have their order changed when using `sort_unstable`. For most variant types,
757 /// this distinction should not matter though.
758 ///
759 /// _Godot equivalent: `Array.sort()`_
760 #[doc(alias = "sort")]
761 pub fn sort_unstable(&mut self) {
762 self.debug_ensure_mutable();
763
764 // SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
765 unsafe { self.as_inner_mut() }.sort();
766 }
767
768 /// Sorts the array, using a type-safe comparator.
769 ///
770 /// The predicate expects two parameters `(a, b)` and should return an ordering relation. For example, simple ascending ordering of the
771 /// elements themselves would be achieved with `|a, b| a.cmp(b)`.
772 ///
773 /// The sorting algorithm used is not [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
774 /// This means that values considered equal may have their order changed when using `sort_unstable_by`. For most variant types,
775 /// this distinction should not matter though.
776 pub fn sort_unstable_by<F>(&mut self, mut func: F)
777 where
778 F: FnMut(&T, &T) -> cmp::Ordering,
779 {
780 self.debug_ensure_mutable();
781
782 let godot_comparator = |args: &[&Variant]| {
783 let lhs = T::from_variant(args[0]);
784 let rhs = T::from_variant(args[1]);
785 let is_less = matches!(func(&lhs, &rhs), cmp::Ordering::Less);
786
787 is_less.to_variant()
788 };
789
790 let debug_name = std::any::type_name::<F>();
791 Callable::with_scoped_fn(debug_name, godot_comparator, |pred| {
792 self.sort_unstable_custom(pred)
793 });
794 }
795
796 /// Sorts the array, using type-unsafe `Callable` comparator.
797 ///
798 /// For a type-safe variant of this method, use [`sort_unstable_by()`][Self::sort_unstable_by].
799 ///
800 /// The callable expects two parameters `(lhs, rhs)` and should return a bool `lhs < rhs`.
801 ///
802 /// The sorting algorithm used is not [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
803 /// This means that values considered equal may have their order changed when using `sort_unstable_custom`.For most variant types,
804 /// this distinction should not matter though.
805 ///
806 /// _Godot equivalent: `Array.sort_custom()`_
807 #[doc(alias = "sort_custom")]
808 pub fn sort_unstable_custom(&mut self, func: &Callable) {
809 self.debug_ensure_mutable();
810
811 // SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
812 unsafe { self.as_inner_mut() }.sort_custom(func);
813 }
814
815 /// Shuffles the array such that the items will have a random order. This method uses the
816 /// global random number generator common to methods such as `randi`. Call `randomize` to
817 /// ensure that a new seed will be used each time if you want non-reproducible shuffling.
818 pub fn shuffle(&mut self) {
819 self.debug_ensure_mutable();
820
821 // SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
822 unsafe { self.as_inner_mut() }.shuffle();
823 }
824
825 /// Turns the array into a shallow-immutable array.
826 ///
827 /// Makes the array read-only and returns the original array. The array's elements cannot be overridden with different values, and their
828 /// order cannot change. Does not apply to nested elements, such as dictionaries. This operation is irreversible.
829 ///
830 /// In GDScript, arrays are automatically read-only if declared with the `const` keyword.
831 ///
832 /// # Semantics and alternatives
833 /// You can use this in Rust, but the behavior of mutating methods is only validated in a best-effort manner (more than in GDScript though):
834 /// some methods like `set()` panic in Debug mode, when used on a read-only array. There is no guarantee that any attempts to change result
835 /// in feedback; some may silently do nothing.
836 ///
837 /// In Rust, you can use shared references (`&Array<T>`) to prevent mutation. Note however that `Clone` can be used to create another
838 /// reference, through which mutation can still occur. For deep-immutable arrays, you'll need to keep your `Array` encapsulated or directly
839 /// use Rust data structures.
840 ///
841 /// _Godot equivalent: `make_read_only`_
842 #[doc(alias = "make_read_only")]
843 pub fn into_read_only(self) -> Self {
844 // SAFETY: Changes a per-array property, no elements.
845 unsafe { self.as_inner_mut() }.make_read_only();
846 self
847 }
848
849 /// Returns true if the array is read-only.
850 ///
851 /// See [`into_read_only()`][Self::into_read_only].
852 /// In GDScript, arrays are automatically read-only if declared with the `const` keyword.
853 pub fn is_read_only(&self) -> bool {
854 self.as_inner().is_read_only()
855 }
856
857 /// Best-effort mutability check.
858 ///
859 /// # Panics
860 /// In Debug mode, if the array is marked as read-only.
861 fn debug_ensure_mutable(&self) {
862 debug_assert!(
863 !self.is_read_only(),
864 "mutating operation on read-only array"
865 );
866 }
867
868 /// Asserts that the given index refers to an existing element.
869 ///
870 /// # Panics
871 /// If `index` is out of bounds.
872 fn check_bounds(&self, index: usize) {
873 let len = self.len();
874 assert!(
875 index < len,
876 "Array index {index} is out of bounds: length is {len}",
877 );
878 }
879
880 /// Returns a pointer to the element at the given index.
881 ///
882 /// # Panics
883 /// If `index` is out of bounds.
884 fn ptr(&self, index: usize) -> sys::GDExtensionConstVariantPtr {
885 let ptr = self.ptr_or_null(index);
886 assert!(
887 !ptr.is_null(),
888 "Array index {index} out of bounds (len {len})",
889 len = self.len(),
890 );
891 ptr
892 }
893
894 /// Returns a pointer to the element at the given index, or null if out of bounds.
895 fn ptr_or_null(&self, index: usize) -> sys::GDExtensionConstVariantPtr {
896 // SAFETY: array_operator_index_const returns null for invalid indexes.
897 let variant_ptr = unsafe {
898 let index = to_i64(index);
899 interface_fn!(array_operator_index_const)(self.sys(), index)
900 };
901
902 // Signature is wrong in GDExtension, semantically this is a const ptr
903 sys::SysPtr::as_const(variant_ptr)
904 }
905
906 /// Returns a mutable pointer to the element at the given index.
907 ///
908 /// # Panics
909 ///
910 /// If `index` is out of bounds.
911 fn ptr_mut(&mut self, index: usize) -> sys::GDExtensionVariantPtr {
912 let ptr = self.ptr_mut_or_null(index);
913 assert!(
914 !ptr.is_null(),
915 "Array index {index} out of bounds (len {len})",
916 len = self.len(),
917 );
918 ptr
919 }
920
921 /// Returns a pointer to the element at the given index, or null if out of bounds.
922 fn ptr_mut_or_null(&mut self, index: usize) -> sys::GDExtensionVariantPtr {
923 // SAFETY: array_operator_index returns null for invalid indexes.
924 unsafe {
925 let index = to_i64(index);
926 interface_fn!(array_operator_index)(self.sys_mut(), index)
927 }
928 }
929
930 /// # Safety
931 ///
932 /// This has the same safety issues as doing `self.assume_type::<Variant>()` and so the relevant safety invariants from
933 /// [`assume_type`](Self::assume_type) must be upheld.
934 ///
935 /// In particular this means that all reads are fine, since all values can be converted to `Variant`. However, writes are only OK
936 /// if they match the type `T`.
937 #[doc(hidden)]
938 pub unsafe fn as_inner_mut(&self) -> inner::InnerArray<'_> {
939 // The memory layout of `Array<T>` does not depend on `T`.
940 inner::InnerArray::from_outer_typed(self)
941 }
942
943 fn as_inner(&self) -> ImmutableInnerArray<'_> {
944 ImmutableInnerArray {
945 // SAFETY: We can only read from the array.
946 inner: unsafe { self.as_inner_mut() },
947 }
948 }
949
950 /// Changes the generic type on this array, without changing its contents. Needed for API functions
951 /// that take a variant array even though we want to pass a typed one.
952 ///
953 /// # Safety
954 ///
955 /// - Any values written to the array must match the runtime type of the array.
956 /// - Any values read from the array must be convertible to the type `U`.
957 ///
958 /// If the safety invariant of `Array` is intact, which it must be for any publicly accessible arrays, then `U` must match
959 /// the runtime type of the array. This then implies that both of the conditions above hold. This means that you only need
960 /// to keep the above conditions in mind if you are intentionally violating the safety invariant of `Array`.
961 ///
962 /// Note also that any `GodotType` can be written to a `Variant` array.
963 ///
964 /// In the current implementation, both cases will produce a panic rather than undefined behavior, but this should not be relied upon.
965 unsafe fn assume_type_ref<U: ArrayElement>(&self) -> &Array<U> {
966 // The memory layout of `Array<T>` does not depend on `T`.
967 std::mem::transmute::<&Array<T>, &Array<U>>(self)
968 }
969
970 /// Validates that all elements in this array can be converted to integers of type `T`.
971 #[cfg(debug_assertions)] #[cfg_attr(published_docs, doc(cfg(debug_assertions)))]
972 pub(crate) fn debug_validate_int_elements(&self) -> Result<(), ConvertError> {
973 // SAFETY: every element is internally represented as Variant.
974 let canonical_array = unsafe { self.assume_type_ref::<Variant>() };
975
976 // If any element is not convertible, this will return an error.
977 for elem in canonical_array.iter_shared() {
978 elem.try_to::<T>().map_err(|_err| {
979 FromGodotError::BadArrayTypeInt {
980 expected_int_type: std::any::type_name::<T>(),
981 value: elem
982 .try_to::<i64>()
983 .expect("origin must be i64 compatible; this is a bug"),
984 }
985 .into_error(self.clone()) // Context info about array, not element.
986 })?;
987 }
988
989 Ok(())
990 }
991
992 // No-op in Release. Avoids O(n) conversion checks, but still panics on access.
993 #[cfg(not(debug_assertions))] #[cfg_attr(published_docs, doc(cfg(not(debug_assertions))))]
994 pub(crate) fn debug_validate_int_elements(&self) -> Result<(), ConvertError> {
995 Ok(())
996 }
997
998 /// Returns the runtime element type information for this array.
999 ///
1000 /// The result is generally cached, so feel free to call this method repeatedly.
1001 ///
1002 /// # Panics (Debug)
1003 /// In the astronomically rare case where another extension in Godot modifies an array's type (which godot-rust already cached as `Untyped`)
1004 /// via C function `array_set_typed`, thus leading to incorrect cache values. Such bad practice of not typing arrays immediately on
1005 /// construction is not supported, and will not be checked in Release mode.
1006 pub fn element_type(&self) -> ElementType {
1007 ElementType::get_or_compute_cached(
1008 &self.cached_element_type,
1009 || self.as_inner().get_typed_builtin(),
1010 || self.as_inner().get_typed_class_name(),
1011 || self.as_inner().get_typed_script(),
1012 )
1013 }
1014
1015 /// Checks that the inner array has the correct type set on it for storing elements of type `T`.
1016 fn with_checked_type(self) -> Result<Self, ConvertError> {
1017 let self_ty = self.element_type();
1018 let target_ty = ElementType::of::<T>();
1019
1020 // Exact match: check successful.
1021 if self_ty == target_ty {
1022 return Ok(self);
1023 }
1024
1025 // Check if script class (runtime) matches its native base class (compile-time).
1026 // This allows an Array[Enemy] from GDScript to be used as Array<Gd<RefCounted>> in Rust.
1027 if let (ElementType::ScriptClass(_), ElementType::Class(expected_class)) =
1028 (&self_ty, &target_ty)
1029 {
1030 if let Some(actual_base_class) = self_ty.class_id() {
1031 if actual_base_class == *expected_class {
1032 return Ok(self);
1033 }
1034 }
1035 }
1036
1037 Err(FromGodotError::BadArrayType {
1038 expected: target_ty,
1039 actual: self_ty,
1040 }
1041 .into_error(self))
1042 }
1043
1044 /// Sets the type of the inner array.
1045 ///
1046 /// # Safety
1047 /// Must only be called once, directly after creation.
1048 unsafe fn init_inner_type(&mut self) {
1049 debug_assert!(self.is_empty());
1050 debug_assert!(
1051 self.cached_element_type.get().is_none(),
1052 "init_inner_type() called twice"
1053 );
1054
1055 // Immediately set cache to static type.
1056 let elem_ty = ElementType::of::<T>();
1057 let _ = self.cached_element_type.set(elem_ty);
1058
1059 if elem_ty.is_typed() {
1060 let script = Variant::nil();
1061
1062 // A bit contrived because empty StringName is lazy-initialized but must also remain valid.
1063 #[allow(unused_assignments)]
1064 let mut empty_string_name = None;
1065 let class_name = if let Some(class_id) = elem_ty.class_id() {
1066 class_id.string_sys()
1067 } else {
1068 empty_string_name = Some(StringName::default());
1069 // as_ref() crucial here -- otherwise the StringName is dropped.
1070 empty_string_name.as_ref().unwrap().string_sys()
1071 };
1072
1073 // SAFETY: Valid pointers are passed in.
1074 // Relevant for correctness, not safety: the array is a newly created, empty, untyped array.
1075 unsafe {
1076 interface_fn!(array_set_typed)(
1077 self.sys_mut(),
1078 elem_ty.variant_type().sys(),
1079 class_name, // must be empty if variant_type != OBJECT.
1080 script.var_sys(),
1081 );
1082 }
1083 }
1084 }
1085
1086 /// Returns a clone of the array without checking the resulting type.
1087 ///
1088 /// # Safety
1089 /// Should be used only in scenarios where the caller can guarantee that the resulting array will have the correct type,
1090 /// or when an incorrect Rust type is acceptable (passing raw arrays to Godot FFI).
1091 unsafe fn clone_unchecked(&self) -> Self {
1092 let result = Self::new_with_uninit(|self_ptr| {
1093 let ctor = sys::builtin_fn!(array_construct_copy);
1094 let args = [self.sys()];
1095 ctor(self_ptr, args.as_ptr());
1096 });
1097 result.with_cache(self)
1098 }
1099
1100 /// Whether this array is untyped and holds `Variant` elements (compile-time check).
1101 ///
1102 /// Used as `if` statement in trait impls. Avoids defining yet another trait or non-local overridden function just for this case;
1103 /// `Variant` is the only Godot type that has variant type NIL and can be used as an array element.
1104 fn has_variant_t() -> bool {
1105 element_variant_type::<T>() == VariantType::NIL
1106 }
1107
1108 /// Execute a function that creates a new Array, transferring cached element type if available.
1109 ///
1110 /// This is a convenience helper for methods that create new Array instances and want to preserve
1111 /// cached type information to avoid redundant FFI calls.
1112 fn with_cache(self, source: &Self) -> Self {
1113 ElementType::transfer_cache(&source.cached_element_type, &self.cached_element_type);
1114 self
1115 }
1116}
1117
1118#[test]
1119fn correct_variant_t() {
1120 assert!(Array::<Variant>::has_variant_t());
1121 assert!(!Array::<i64>::has_variant_t());
1122}
1123
1124impl VariantArray {
1125 /// # Safety
1126 /// - Variant must have type `VariantType::ARRAY`.
1127 /// - Subsequent operations on this array must not rely on the type of the array.
1128 pub(crate) unsafe fn from_variant_unchecked(variant: &Variant) -> Self {
1129 // See also ffi_from_variant().
1130 Self::new_with_uninit(|self_ptr| {
1131 let array_from_variant = sys::builtin_fn!(array_from_variant);
1132 array_from_variant(self_ptr, sys::SysPtr::force_mut(variant.var_sys()));
1133 })
1134 }
1135}
1136
1137// ----------------------------------------------------------------------------------------------------------------------------------------------
1138// Traits
1139
1140// Godot has some inconsistent behavior around NaN values. In GDScript, `NAN == NAN` is `false`,
1141// but `[NAN] == [NAN]` is `true`. If they decide to make all NaNs equal, we can implement `Eq` and
1142// `Ord`; if they decide to make all NaNs unequal, we can remove this comment.
1143//
1144// impl<T> Eq for Array<T> {}
1145//
1146// impl<T> Ord for Array<T> {
1147// ...
1148// }
1149
1150// SAFETY:
1151// - `move_return_ptr`
1152// Nothing special needs to be done beyond a `std::mem::swap` when returning an Array.
1153// So we can just use `ffi_methods`.
1154//
1155// - `from_arg_ptr`
1156// Arrays are properly initialized through a `from_sys` call, but the ref-count should be incremented
1157// as that is the callee's responsibility. Which we do by calling `std::mem::forget(array.clone())`.
1158unsafe impl<T: ArrayElement> GodotFfi for Array<T> {
1159 const VARIANT_TYPE: ExtVariantType = ExtVariantType::Concrete(VariantType::ARRAY);
1160
1161 ffi_methods! { type sys::GDExtensionTypePtr = *mut Opaque; .. }
1162}
1163
1164// Only implement for untyped arrays; typed arrays cannot be nested in Godot.
1165impl ArrayElement for VariantArray {}
1166
1167impl<T: ArrayElement> GodotConvert for Array<T> {
1168 type Via = Self;
1169}
1170
1171impl<T: ArrayElement> ToGodot for Array<T> {
1172 type Pass = meta::ByRef;
1173
1174 fn to_godot(&self) -> &Self::Via {
1175 self
1176 }
1177
1178 fn to_godot_owned(&self) -> Self::Via
1179 where
1180 Self::Via: Clone,
1181 {
1182 // Overridden, because default clone() validates that before/after element types are equal, which doesn't matter when we pass to FFI.
1183 // This may however be an issue if to_godot_owned() is used by the user directly.
1184 unsafe { self.clone_unchecked() }
1185 }
1186}
1187
1188impl<T: ArrayElement> FromGodot for Array<T> {
1189 fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
1190 T::debug_validate_elements(&via)?;
1191 Ok(via)
1192 }
1193}
1194
1195impl<T: ArrayElement> fmt::Debug for Array<T> {
1196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1197 // Going through `Variant` because there doesn't seem to be a direct way.
1198 // Reuse Display.
1199 write!(f, "{}", self.to_variant().stringify())
1200 }
1201}
1202
1203impl<T: ArrayElement + fmt::Display> fmt::Display for Array<T> {
1204 /// Formats `Array` to match Godot's string representation.
1205 ///
1206 /// # Example
1207 /// ```no_run
1208 /// # use godot::prelude::*;
1209 /// let a = array![1,2,3,4];
1210 /// assert_eq!(format!("{a}"), "[1, 2, 3, 4]");
1211 /// ```
1212 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1213 write!(f, "[")?;
1214 for (count, v) in self.iter_shared().enumerate() {
1215 if count != 0 {
1216 write!(f, ", ")?;
1217 }
1218 write!(f, "{v}")?;
1219 }
1220 write!(f, "]")
1221 }
1222}
1223
1224/// Creates a new reference to the data in this array. Changes to the original array will be
1225/// reflected in the copy and vice versa.
1226///
1227/// To create a (mostly) independent copy instead, see [`Array::duplicate_shallow()`] and
1228/// [`Array::duplicate_deep()`].
1229impl<T: ArrayElement> Clone for Array<T> {
1230 fn clone(&self) -> Self {
1231 // SAFETY: `self` is a valid array, since we have a reference that keeps it alive.
1232 // Type-check follows below.
1233 let copy = unsafe { self.clone_unchecked() };
1234
1235 // Double-check copy's runtime type in Debug mode.
1236 if cfg!(debug_assertions) {
1237 copy.with_checked_type().unwrap_or_else(|e| {
1238 panic!("copied array should have same type as original array: {e}")
1239 })
1240 } else {
1241 copy
1242 }
1243 }
1244}
1245
1246impl<T: ArrayElement> Var for Array<T> {
1247 fn get_property(&self) -> Self::Via {
1248 self.to_godot_owned()
1249 }
1250
1251 fn set_property(&mut self, value: Self::Via) {
1252 *self = FromGodot::from_godot(value)
1253 }
1254
1255 fn var_hint() -> PropertyHintInfo {
1256 // For array #[var], the hint string is "PackedInt32Array", "Node" etc. for typed arrays, and "" for untyped arrays.
1257 if Self::has_variant_t() {
1258 PropertyHintInfo::none()
1259 } else {
1260 PropertyHintInfo::var_array_element::<T>()
1261 }
1262 }
1263}
1264
1265impl<T> Export for Array<T>
1266where
1267 T: ArrayElement + Export,
1268{
1269 fn export_hint() -> PropertyHintInfo {
1270 // If T == Variant, then we return "Array" builtin type hint.
1271 if Self::has_variant_t() {
1272 PropertyHintInfo::type_name::<VariantArray>()
1273 } else {
1274 PropertyHintInfo::export_array_element::<T>()
1275 }
1276 }
1277}
1278
1279impl<T: ArrayElement> BuiltinExport for Array<T> {}
1280
1281impl<T> Export for Array<Gd<T>>
1282where
1283 T: GodotClass + Bounds<Exportable = bounds::Yes>,
1284{
1285 fn export_hint() -> PropertyHintInfo {
1286 PropertyHintInfo::export_array_element::<Gd<T>>()
1287 }
1288
1289 #[doc(hidden)]
1290 fn as_node_class() -> Option<ClassId> {
1291 PropertyHintInfo::object_as_node_class::<T>()
1292 }
1293}
1294
1295/// `#[export]` for `Array<DynGd<T, D>>` is available only for `T` being Engine class (such as Node or Resource).
1296///
1297/// Consider exporting `Array<Gd<T>>` instead of `Array<DynGd<T, D>>` for user-declared GDExtension classes.
1298impl<T: GodotClass, D> Export for Array<DynGd<T, D>>
1299where
1300 T: GodotClass + Bounds<Exportable = bounds::Yes>,
1301 D: ?Sized + 'static,
1302{
1303 fn export_hint() -> PropertyHintInfo {
1304 PropertyHintInfo::export_array_element::<DynGd<T, D>>()
1305 }
1306
1307 #[doc(hidden)]
1308 fn as_node_class() -> Option<ClassId> {
1309 PropertyHintInfo::object_as_node_class::<T>()
1310 }
1311}
1312
1313impl<T: ArrayElement> Default for Array<T> {
1314 #[inline]
1315 fn default() -> Self {
1316 let mut array = unsafe {
1317 Self::new_with_uninit(|self_ptr| {
1318 let ctor = sys::builtin_fn!(array_construct_default);
1319 ctor(self_ptr, std::ptr::null_mut())
1320 })
1321 };
1322
1323 // SAFETY: We just created this array, and haven't called `init_inner_type` before.
1324 unsafe { array.init_inner_type() };
1325 array
1326 }
1327}
1328
1329// T must be GodotType (or subtrait ArrayElement), because drop() requires sys_mut(), which is on the GodotFfi trait.
1330// Its sister method GodotFfi::from_sys_init() requires Default, which is only implemented for T: GodotType.
1331// This could be addressed by splitting up GodotFfi if desired.
1332impl<T: ArrayElement> Drop for Array<T> {
1333 #[inline]
1334 fn drop(&mut self) {
1335 unsafe {
1336 let array_destroy = sys::builtin_fn!(array_destroy);
1337 array_destroy(self.sys_mut());
1338 }
1339 }
1340}
1341
1342impl<T: ArrayElement> GodotType for Array<T> {
1343 type Ffi = Self;
1344
1345 type ToFfi<'f>
1346 = RefArg<'f, Array<T>>
1347 where
1348 Self: 'f;
1349
1350 fn to_ffi(&self) -> Self::ToFfi<'_> {
1351 RefArg::new(self)
1352 }
1353
1354 fn into_ffi(self) -> Self::Ffi {
1355 self
1356 }
1357
1358 fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
1359 Ok(ffi)
1360 }
1361
1362 fn godot_type_name() -> String {
1363 "Array".to_string()
1364 }
1365
1366 fn property_hint_info() -> PropertyHintInfo {
1367 // Array<Variant>, aka untyped array, has no hints.
1368 if Self::has_variant_t() {
1369 return PropertyHintInfo::none();
1370 }
1371
1372 // Typed arrays use type hint.
1373 PropertyHintInfo {
1374 hint: crate::global::PropertyHint::ARRAY_TYPE,
1375 hint_string: GString::from(&element_godot_type_name::<T>()),
1376 }
1377 }
1378}
1379
1380impl<T: ArrayElement> GodotFfiVariant for Array<T> {
1381 fn ffi_to_variant(&self) -> Variant {
1382 unsafe {
1383 Variant::new_with_var_uninit(|variant_ptr| {
1384 let array_to_variant = sys::builtin_fn!(array_to_variant);
1385 array_to_variant(variant_ptr, sys::SysPtr::force_mut(self.sys()));
1386 })
1387 }
1388 }
1389
1390 fn ffi_from_variant(variant: &Variant) -> Result<Self, ConvertError> {
1391 // First check if the variant is an array. The array conversion shouldn't be called otherwise.
1392 if variant.get_type() != Self::VARIANT_TYPE.variant_as_nil() {
1393 return Err(FromVariantError::BadType {
1394 expected: Self::VARIANT_TYPE.variant_as_nil(),
1395 actual: variant.get_type(),
1396 }
1397 .into_error(variant.clone()));
1398 }
1399
1400 let array = unsafe {
1401 Self::new_with_uninit(|self_ptr| {
1402 let array_from_variant = sys::builtin_fn!(array_from_variant);
1403 array_from_variant(self_ptr, sys::SysPtr::force_mut(variant.var_sys()));
1404 })
1405 };
1406
1407 // Then, check the runtime type of the array.
1408 array.with_checked_type()
1409 }
1410}
1411
1412// ----------------------------------------------------------------------------------------------------------------------------------------------
1413// Conversion traits
1414
1415/// Creates a `Array` from the given Rust array.
1416impl<T: ArrayElement + ToGodot, const N: usize> From<&[T; N]> for Array<T> {
1417 fn from(arr: &[T; N]) -> Self {
1418 Self::from(&arr[..])
1419 }
1420}
1421
1422/// Creates a `Array` from the given slice.
1423impl<T: ArrayElement + ToGodot> From<&[T]> for Array<T> {
1424 fn from(slice: &[T]) -> Self {
1425 let mut array = Self::new();
1426 let len = slice.len();
1427 if len == 0 {
1428 return array;
1429 }
1430
1431 // SAFETY: We fill the array with `Variant::nil()`, however since we're resizing to the size of the slice we'll end up rewriting all
1432 // the nulls with values of type `T`.
1433 unsafe { array.as_inner_mut() }.resize(to_i64(len));
1434
1435 // SAFETY: `array` has `len` elements since we just resized it, and they are all valid `Variant`s. Additionally, since
1436 // the array was created in this function, and we do not access the array while this slice exists, the slice has unique
1437 // access to the elements.
1438 let elements = unsafe { Variant::borrow_slice_mut(array.ptr_mut(0), len) };
1439 for (element, array_slot) in slice.iter().zip(elements.iter_mut()) {
1440 *array_slot = element.to_variant();
1441 }
1442
1443 array
1444 }
1445}
1446
1447/// Creates a `Array` from an iterator.
1448impl<T: ArrayElement + ToGodot> FromIterator<T> for Array<T> {
1449 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1450 let mut array = Self::new();
1451 array.extend(iter);
1452 array
1453 }
1454}
1455
1456/// Extends a `Array` with the contents of an iterator.
1457impl<T: ArrayElement> Extend<T> for Array<T> {
1458 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1459 // Unfortunately the GDExtension API does not offer the equivalent of `Vec::reserve`.
1460 // Otherwise, we could use it to pre-allocate based on `iter.size_hint()`.
1461 //
1462 // A faster implementation using `resize()` and direct pointer writes might still be possible.
1463 // Note that this could technically also use iter(), since no moves need to happen (however Extend requires IntoIterator).
1464 for item in iter.into_iter() {
1465 // self.push(AsArg::into_arg(&item));
1466 self.push(meta::owned_into_arg(item));
1467 }
1468 }
1469}
1470
1471/// Converts this array to a strongly typed Rust vector.
1472impl<T: ArrayElement + FromGodot> From<&Array<T>> for Vec<T> {
1473 fn from(array: &Array<T>) -> Vec<T> {
1474 let len = array.len();
1475 let mut vec = Vec::with_capacity(len);
1476
1477 // SAFETY: Unless `experimental-threads` is enabled, then we cannot have concurrent access to this array.
1478 // And since we don't concurrently access the array in this function, we can create a slice to its contents.
1479 let elements = unsafe { Variant::borrow_slice(array.ptr(0), len) };
1480
1481 vec.extend(elements.iter().map(T::from_variant));
1482
1483 vec
1484 }
1485}
1486
1487// ----------------------------------------------------------------------------------------------------------------------------------------------
1488
1489/// An iterator over typed elements of an [`Array`].
1490pub struct Iter<'a, T: ArrayElement> {
1491 array: &'a Array<T>,
1492 next_idx: usize,
1493}
1494
1495impl<T: ArrayElement + FromGodot> Iterator for Iter<'_, T> {
1496 type Item = T;
1497
1498 fn next(&mut self) -> Option<Self::Item> {
1499 if self.next_idx < self.array.len() {
1500 let idx = self.next_idx;
1501 self.next_idx += 1;
1502
1503 let element_ptr = self.array.ptr_or_null(idx);
1504
1505 // SAFETY: We just checked that the index is not out of bounds, so the pointer won't be null.
1506 // We immediately convert this to the right element, so barring `experimental-threads` the pointer won't be invalidated in time.
1507 let variant = unsafe { Variant::borrow_var_sys(element_ptr) };
1508 let element = T::from_variant(variant);
1509 Some(element)
1510 } else {
1511 None
1512 }
1513 }
1514
1515 fn size_hint(&self) -> (usize, Option<usize>) {
1516 let remaining = self.array.len() - self.next_idx;
1517 (remaining, Some(remaining))
1518 }
1519}
1520
1521// TODO There's a macro for this, but it doesn't support generics yet; add support and use it
1522impl<T: ArrayElement> PartialEq for Array<T> {
1523 #[inline]
1524 fn eq(&self, other: &Self) -> bool {
1525 unsafe {
1526 let mut result = false;
1527 sys::builtin_call! {
1528 array_operator_equal(self.sys(), other.sys(), result.sys_mut())
1529 }
1530 result
1531 }
1532 }
1533}
1534
1535impl<T: ArrayElement> PartialOrd for Array<T> {
1536 #[inline]
1537 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1538 let op_less = |lhs, rhs| unsafe {
1539 let mut result = false;
1540 sys::builtin_call! {
1541 array_operator_less(lhs, rhs, result.sys_mut())
1542 }
1543 result
1544 };
1545
1546 if op_less(self.sys(), other.sys()) {
1547 Some(std::cmp::Ordering::Less)
1548 } else if op_less(other.sys(), self.sys()) {
1549 Some(std::cmp::Ordering::Greater)
1550 } else if self.eq(other) {
1551 Some(std::cmp::Ordering::Equal)
1552 } else {
1553 None
1554 }
1555 }
1556}
1557
1558// ----------------------------------------------------------------------------------------------------------------------------------------------
1559
1560/// Constructs [`Array`] literals, similar to Rust's standard `vec!` macro.
1561///
1562///
1563/// # Type inference
1564/// To create an `Array<E>`, the types of the provided values `T` must implement [`AsArg<E>`].
1565///
1566/// For values that can directly be represented in Godot (implementing [`GodotType`]), types can usually be inferred.
1567/// You need to respect by-value vs. by-reference semantics as per [`ToGodot::Pass`].
1568///
1569/// # Examples
1570/// ```no_run
1571/// # use godot::prelude::*;
1572/// // Inferred type - i32: AsArg<i32>
1573/// let ints = array![3, 1, 4];
1574///
1575/// // Inferred type - &GString: AsArg<GString>
1576/// let strs = array![&GString::from("godot-rust")];
1577///
1578/// // Explicitly specified type - &str: AsArg<GString>
1579/// let strs: Array<GString> = array!["Godot", "Rust"];
1580/// ```
1581///
1582/// # See also
1583/// To create an `Array` of variants, see the [`varray!`] macro.
1584///
1585/// For dictionaries, a similar macro [`vdict!`] exists.
1586#[macro_export]
1587macro_rules! array {
1588 ($($elements:expr),* $(,)?) => {
1589 {
1590 let mut array = $crate::builtin::Array::default();
1591 $(
1592 array.push($elements);
1593 )*
1594 array
1595 }
1596 };
1597}
1598
1599/// Constructs [`VariantArray`] literals, similar to Rust's standard `vec!` macro.
1600///
1601/// The type of the array elements is always [`Variant`].
1602///
1603/// # Example
1604/// ```no_run
1605/// # use godot::prelude::*;
1606/// let arr: VariantArray = varray![42_i64, "hello", true];
1607/// ```
1608///
1609/// # See also
1610/// To create a typed `Array` with a single element type, see the [`array!`] macro.
1611///
1612/// For dictionaries, a similar macro [`vdict!`] exists.
1613///
1614/// To construct slices of variants, use [`vslice!`].
1615#[macro_export]
1616macro_rules! varray {
1617 // Note: use to_variant() and not Variant::from(), as that works with both references and values
1618 ($($elements:expr),* $(,)?) => {
1619 {
1620 use $crate::meta::ToGodot as _;
1621 let mut array = $crate::builtin::VariantArray::default();
1622 $(
1623 array.push(&$elements.to_variant());
1624 )*
1625 array
1626 }
1627 };
1628}
1629
1630/// Constructs a slice of [`Variant`] literals, useful for passing to vararg functions.
1631///
1632/// Many APIs in Godot have variable-length arguments. GDScript can call such functions by simply passing more arguments, but in Rust,
1633/// the parameter type `&[Variant]` is used.
1634///
1635/// This macro creates a [slice](https://doc.rust-lang.org/std/primitive.slice.html) of `Variant` values.
1636///
1637/// # Examples
1638/// Variable number of arguments:
1639/// ```no_run
1640/// # use godot::prelude::*;
1641/// let slice: &[Variant] = vslice![42, "hello", true];
1642///
1643/// let concat: GString = godot::global::str(slice);
1644/// ```
1645/// _(In practice, you might want to use [`godot_str!`][crate::global::godot_str] instead of `str()`.)_
1646///
1647/// Dynamic function call via reflection. NIL can still be passed inside `vslice!`, just use `Variant::nil()`.
1648/// ```no_run
1649/// # use godot::prelude::*;
1650/// # fn some_object() -> Gd<Object> { unimplemented!() }
1651/// let mut obj: Gd<Object> = some_object();
1652/// obj.call("some_method", vslice![Vector2i::new(1, 2), Variant::nil()]);
1653/// ```
1654///
1655/// # See also
1656/// To create typed and untyped `Array`s, use the [`array!`] and [`varray!`] macros respectively.
1657///
1658/// For dictionaries, a similar macro [`vdict!`] exists.
1659#[macro_export]
1660macro_rules! vslice {
1661 // Note: use to_variant() and not Variant::from(), as that works with both references and values
1662 ($($elements:expr),* $(,)?) => {
1663 {
1664 use $crate::meta::ToGodot as _;
1665 let mut array = $crate::builtin::VariantArray::default();
1666 &[
1667 $( $elements.to_variant(), )*
1668 ]
1669 }
1670 };
1671}
1672
1673// ----------------------------------------------------------------------------------------------------------------------------------------------
1674
1675#[cfg(feature = "serde")] #[cfg_attr(published_docs, doc(cfg(feature = "serde")))]
1676mod serialize {
1677 use std::marker::PhantomData;
1678
1679 use serde::de::{SeqAccess, Visitor};
1680 use serde::ser::SerializeSeq;
1681 use serde::{Deserialize, Deserializer, Serialize, Serializer};
1682
1683 use super::*;
1684
1685 impl<T> Serialize for Array<T>
1686 where
1687 T: ArrayElement + Serialize,
1688 {
1689 #[inline]
1690 fn serialize<S>(
1691 &self,
1692 serializer: S,
1693 ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
1694 where
1695 S: Serializer,
1696 {
1697 let mut sequence = serializer.serialize_seq(Some(self.len()))?;
1698 for e in self.iter_shared() {
1699 sequence.serialize_element(&e)?
1700 }
1701 sequence.end()
1702 }
1703 }
1704
1705 impl<'de, T> Deserialize<'de> for Array<T>
1706 where
1707 T: ArrayElement + Deserialize<'de>,
1708 {
1709 #[inline]
1710 fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
1711 where
1712 D: Deserializer<'de>,
1713 {
1714 struct ArrayVisitor<T>(PhantomData<T>);
1715 impl<'de, T> Visitor<'de> for ArrayVisitor<T>
1716 where
1717 T: ArrayElement + Deserialize<'de>,
1718 {
1719 type Value = Array<T>;
1720
1721 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1722 formatter.write_str(std::any::type_name::<Self::Value>())
1723 }
1724
1725 fn visit_seq<A>(
1726 self,
1727 mut seq: A,
1728 ) -> Result<Self::Value, <A as SeqAccess<'de>>::Error>
1729 where
1730 A: SeqAccess<'de>,
1731 {
1732 let mut vec = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);
1733 while let Some(val) = seq.next_element::<T>()? {
1734 vec.push(val);
1735 }
1736 Ok(Self::Value::from(vec.as_slice()))
1737 }
1738 }
1739
1740 deserializer.deserialize_seq(ArrayVisitor::<T>(PhantomData))
1741 }
1742 }
1743}