-
-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy patharray.rs
1387 lines (1232 loc) · 51.5 KB
/
array.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) godot-rust; Bromeon and contributors.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
use std::borrow::Borrow;
use std::fmt;
use std::marker::PhantomData;
use crate::builtin::*;
use crate::meta::error::{ConvertError, FromGodotError, FromVariantError};
use crate::meta::{
ArrayElement, ArrayTypeInfo, FromGodot, GodotConvert, GodotFfiVariant, GodotType,
PropertyHintInfo, RefArg, ToGodot,
};
use crate::registry::property::{Export, Var};
use godot_ffi as sys;
use sys::{ffi_methods, interface_fn, GodotFfi};
/// Godot's `Array` type.
///
/// Unlike GDScript, all indices and sizes are unsigned, so negative indices are not supported.
///
/// # Typed arrays
///
/// Godot's `Array` can be either typed or untyped.
///
/// An untyped array can contain any kind of [`Variant`], even different types in the same array.
/// We represent this in Rust as `VariantArray`, which is just a type alias for `Array<Variant>`.
///
/// Godot also supports typed arrays, which are also just `Variant` arrays under the hood, but with
/// runtime checks, so that no values of the wrong type are inserted into the array. We represent this as
/// `Array<T>`, where the type `T` must implement `ArrayElement`. Some types like `Array<T>` cannot
/// be stored inside arrays, as Godot prevents nesting.
///
/// If you plan to use any integer or float types apart from `i64` and `f64`, read
/// [this documentation](../meta/trait.ArrayElement.html#integer-and-float-types).
///
/// # Reference semantics
///
/// Like in GDScript, `Array` acts as a reference type: multiple `Array` instances may
/// refer to the same underlying array, and changes to one are visible in the other.
///
/// To create a copy that shares data with the original array, use [`Clone::clone()`].
/// If you want to create a copy of the data, use [`duplicate_shallow()`][Self::duplicate_shallow]
/// or [`duplicate_deep()`][Self::duplicate_deep].
///
/// # Typed array example
///
/// ```no_run
/// # use godot::prelude::*;
/// // Create typed Array<i64> and add values.
/// let mut array = Array::new();
/// array.push(10);
/// array.push(20);
/// array.push(30);
///
/// // Or create the same array in a single expression.
/// let array = array![10, 20, 30];
///
/// // Access elements.
/// let value: i64 = array.at(0); // 10
/// let maybe: Option<i64> = array.get(3); // None
///
/// // Iterate over i64 elements.
/// for value in array.iter_shared() {
/// println!("{value}");
/// }
///
/// // Clone array (shares the reference), and overwrite elements through clone.
/// let mut cloned = array.clone();
/// cloned.set(0, 50); // [50, 20, 30]
/// cloned.remove(1); // [50, 30]
/// cloned.pop(); // [50]
///
/// // Changes will be reflected in the original array.
/// assert_eq!(array.len(), 1);
/// assert_eq!(array.front(), Some(50));
/// ```
///
/// # Untyped array example
///
/// ```no_run
/// # use godot::prelude::*;
/// // VariantArray allows dynamic element types.
/// let mut array = VariantArray::new();
/// array.push(10.to_variant());
/// array.push("Hello".to_variant());
///
/// // Or equivalent, use the `varray!` macro which converts each element.
/// let array = varray![10, "Hello"];
///
/// // Access elements.
/// let value: Variant = array.at(0);
/// let value: i64 = array.at(0).to(); // Variant::to() extracts i64.
/// let maybe: Result<i64, _> = array.at(1).try_to(); // "Hello" is not i64 -> Err.
/// let maybe: Option<Variant> = array.get(3);
///
/// // ...and so on.
/// ```
///
/// # Thread safety
///
/// Usage is safe if the `Array` is used on a single thread only. Concurrent reads on
/// different threads are also safe, but any writes must be externally synchronized. The Rust
/// compiler will enforce this as long as you use only Rust threads, but it cannot protect against
/// concurrent modification on other threads (e.g. created through GDScript).
///
/// # Godot docs
///
/// [`Array[T]` (stable)](https://docs.godotengine.org/en/stable/classes/class_array.html)
pub struct Array<T: ArrayElement> {
// Safety Invariant: The type of all values in `opaque` matches the type `T`.
opaque: sys::types::OpaqueArray,
_phantom: PhantomData<T>,
}
/// Guard that can only call immutable methods on the array.
struct ImmutableInnerArray<'a> {
inner: inner::InnerArray<'a>,
}
impl<'a> std::ops::Deref for ImmutableInnerArray<'a> {
type Target = inner::InnerArray<'a>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
/// A Godot `Array` without an assigned type.
pub type VariantArray = Array<Variant>;
// TODO check if these return a typed array
impl_builtin_froms!(VariantArray;
PackedByteArray => array_from_packed_byte_array,
PackedColorArray => array_from_packed_color_array,
PackedFloat32Array => array_from_packed_float32_array,
PackedFloat64Array => array_from_packed_float64_array,
PackedInt32Array => array_from_packed_int32_array,
PackedInt64Array => array_from_packed_int64_array,
PackedStringArray => array_from_packed_string_array,
PackedVector2Array => array_from_packed_vector2_array,
PackedVector3Array => array_from_packed_vector3_array,
);
#[cfg(since_api = "4.3")]
impl_builtin_froms!(VariantArray;
PackedVector4Array => array_from_packed_vector4_array,
);
impl<T: ArrayElement> Array<T> {
fn from_opaque(opaque: sys::types::OpaqueArray) -> Self {
// Note: type is not yet checked at this point, because array has not yet been initialized!
Self {
opaque,
_phantom: PhantomData,
}
}
/// Constructs an empty `Array`.
pub fn new() -> Self {
Self::default()
}
/// ⚠️ Returns the value at the specified index.
///
/// This replaces the `Index` trait, which cannot be implemented for `Array` as references are not guaranteed to remain valid.
///
/// # Panics
///
/// If `index` is out of bounds. If you want to handle out-of-bounds access, use [`get()`](Self::get) instead.
pub fn at(&self, index: usize) -> T {
// Panics on out-of-bounds.
let ptr = self.ptr(index);
// SAFETY: `ptr` is a live pointer to a variant since `ptr.is_null()` just verified that the index is not out of bounds.
let variant = unsafe { Variant::borrow_var_sys(ptr) };
T::from_variant(variant)
}
/// Returns the value at the specified index, or `None` if the index is out-of-bounds.
///
/// If you know the index is correct, use [`at()`](Self::at) instead.
pub fn get(&self, index: usize) -> Option<T> {
let ptr = self.ptr_or_null(index);
if ptr.is_null() {
None
} else {
// SAFETY: `ptr` is a live pointer to a variant since `ptr.is_null()` just verified that the index is not out of bounds.
let variant = unsafe { Variant::borrow_var_sys(ptr) };
Some(T::from_variant(variant))
}
}
/// Returns `true` if the array contains the given value. Equivalent of `has` in GDScript.
pub fn contains(&self, value: &T) -> bool {
self.as_inner().has(&value.to_variant())
}
/// Returns the number of times a value is in the array.
pub fn count(&self, value: &T) -> usize {
to_usize(self.as_inner().count(&value.to_variant()))
}
/// Returns the number of elements in the array. Equivalent of `size()` in Godot.
///
/// Retrieving the size incurs an FFI call. If you know the size hasn't changed, you may consider storing
/// it in a variable. For loops, prefer iterators.
#[doc(alias = "size")]
pub fn len(&self) -> usize {
to_usize(self.as_inner().size())
}
/// Returns `true` if the array is empty.
///
/// Checking for emptiness incurs an FFI call. If you know the size hasn't changed, you may consider storing
/// it in a variable. For loops, prefer iterators.
pub fn is_empty(&self) -> bool {
self.as_inner().is_empty()
}
/// Returns a 32-bit integer hash value representing the array and its contents.
///
/// Note: Arrays with equal content will always produce identical hash values. However, the
/// reverse is not true. Returning identical hash values does not imply the arrays are equal,
/// because different arrays can have identical hash values due to hash collisions.
pub fn hash(&self) -> u32 {
// The GDExtension interface only deals in `i64`, but the engine's own `hash()` function
// actually returns `uint32_t`.
self.as_inner().hash().try_into().unwrap()
}
/// Returns the first element in the array, or `None` if the array is empty.
#[doc(alias = "first")]
pub fn front(&self) -> Option<T> {
(!self.is_empty()).then(|| {
let variant = self.as_inner().front();
T::from_variant(&variant)
})
}
/// Returns the last element in the array, or `None` if the array is empty.
#[doc(alias = "last")]
pub fn back(&self) -> Option<T> {
(!self.is_empty()).then(|| {
let variant = self.as_inner().back();
T::from_variant(&variant)
})
}
/// Clears the array, removing all elements.
pub fn clear(&mut self) {
// SAFETY: No new values are written to the array, we only remove values from the array.
unsafe { self.as_inner_mut() }.clear();
}
/// Sets the value at the specified index.
///
/// `value` uses `Borrow<T>` to accept either by value or by reference.
///
/// # Panics
///
/// If `index` is out of bounds.
pub fn set(&mut self, index: usize, value: impl Borrow<T>) {
let ptr_mut = self.ptr_mut(index);
let variant = value.borrow().to_variant();
// SAFETY: `ptr_mut` just checked that the index is not out of bounds.
unsafe { variant.move_into_var_ptr(ptr_mut) };
}
/// Appends an element to the end of the array.
///
/// `value` uses `Borrow<T>` to accept either by value or by reference.
///
/// _Godot equivalents: `append` and `push_back`_
#[doc(alias = "append")]
#[doc(alias = "push_back")]
pub fn push(&mut self, value: impl Borrow<T>) {
// SAFETY: The array has type `T` and we're writing a value of type `T` to it.
let mut inner = unsafe { self.as_inner_mut() };
inner.push_back(&value.borrow().to_variant());
}
/// Adds an element at the beginning of the array, in O(n).
///
/// On large arrays, this method is much slower than [`push()`][Self::push], as it will move all the array's elements.
/// The larger the array, the slower `push_front()` will be.
pub fn push_front(&mut self, value: T) {
// SAFETY: The array has type `T` and we're writing a value of type `T` to it.
unsafe { self.as_inner_mut() }.push_front(&value.to_variant());
}
/// Removes and returns the last element of the array. Returns `None` if the array is empty.
///
/// _Godot equivalent: `pop_back`_
#[doc(alias = "pop_back")]
pub fn pop(&mut self) -> Option<T> {
(!self.is_empty()).then(|| {
// SAFETY: We do not write any values to the array, we just remove one.
let variant = unsafe { self.as_inner_mut() }.pop_back();
T::from_variant(&variant)
})
}
/// Removes and returns the first element of the array, in O(n). Returns `None` if the array is empty.
///
/// Note: On large arrays, this method is much slower than `pop()` as it will move all the
/// array's elements. The larger the array, the slower `pop_front()` will be.
pub fn pop_front(&mut self) -> Option<T> {
(!self.is_empty()).then(|| {
// SAFETY: We do not write any values to the array, we just remove one.
let variant = unsafe { self.as_inner_mut() }.pop_front();
T::from_variant(&variant)
})
}
/// ⚠️ Inserts a new element before the index. The index must be valid or the end of the array (`index == len()`).
///
/// 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.
/// The larger the array, the slower `insert()` will be.
///
/// # Panics
/// If `index > len()`.
pub fn insert(&mut self, index: usize, value: T) {
let len = self.len();
assert!(
index <= len,
"Array insertion index {index} is out of bounds: length is {len}",
);
// SAFETY: The array has type `T` and we're writing a value of type `T` to it.
unsafe { self.as_inner_mut() }.insert(to_i64(index), &value.to_variant());
}
/// ⚠️ Removes and returns the element at the specified index. Equivalent of `pop_at` in GDScript.
///
/// On large arrays, this method is much slower than [`pop()`][Self::pop] as it will move all the array's
/// elements after the removed element. The larger the array, the slower `remove()` will be.
///
/// # Panics
///
/// If `index` is out of bounds.
#[doc(alias = "pop_at")]
pub fn remove(&mut self, index: usize) -> T {
self.check_bounds(index);
// SAFETY: We do not write any values to the array, we just remove one.
let variant = unsafe { self.as_inner_mut() }.pop_at(to_i64(index));
T::from_variant(&variant)
}
/// Removes the first occurrence of a value from the array.
///
/// If the value does not exist in the array, nothing happens. To remove an element by index, use [`remove()`][Self::remove] instead.
///
/// On large arrays, this method is much slower than [`pop()`][Self::pop], as it will move all the array's
/// elements after the removed element.
pub fn erase(&mut self, value: &T) {
// SAFETY: We don't write anything to the array.
unsafe { self.as_inner_mut() }.erase(&value.to_variant());
}
/// Assigns the given value to all elements in the array. This can be used together with
/// `resize` to create an array with a given size and initialized elements.
pub fn fill(&mut self, value: &T) {
// SAFETY: The array has type `T` and we're writing values of type `T` to it.
unsafe { self.as_inner_mut() }.fill(&value.to_variant());
}
/// Resizes the array to contain a different number of elements.
///
/// 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
/// then the new elements are set to `value`.
///
/// If you know that the new size is smaller, then consider using [`shrink`](Array::shrink) instead.
pub fn resize(&mut self, new_size: usize, value: &T) {
let original_size = self.len();
// 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
// array are of type `T` still.
unsafe { self.as_inner_mut() }.resize(to_i64(new_size));
// If new_size < original_size then this is an empty iterator and does nothing.
for i in original_size..new_size {
self.set(i, value);
}
}
/// Shrinks the array down to `new_size`.
///
/// 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.
///
/// If you want to increase the size of the array, use [`resize`](Array::resize) instead.
#[doc(alias = "resize")]
pub fn shrink(&mut self, new_size: usize) -> bool {
if new_size >= self.len() {
return false;
}
// SAFETY: Since `new_size` is less than the current size, we'll only be removing elements from the array.
unsafe { self.as_inner_mut() }.resize(to_i64(new_size));
true
}
/// Appends another array at the end of this array. Equivalent of `append_array` in GDScript.
pub fn extend_array(&mut self, other: &Array<T>) {
// SAFETY: `append_array` will only read values from `other`, and all types can be converted to `Variant`.
let other: &VariantArray = unsafe { other.assume_type_ref::<Variant>() };
// SAFETY: `append_array` will only write values gotten from `other` into `self`, and all values in `other` are guaranteed
// to be of type `T`.
let mut inner_self = unsafe { self.as_inner_mut() };
inner_self.append_array(other);
}
/// Returns a shallow copy of the array. All array elements are copied, but any reference types
/// (such as `Array`, `Dictionary` and `Object`) will still refer to the same value.
///
/// To create a deep copy, use [`duplicate_deep()`][Self::duplicate_deep] instead.
/// To create a new reference to the same array data, use [`clone()`][Clone::clone].
pub fn duplicate_shallow(&self) -> Self {
// SAFETY: We never write to the duplicated array, and all values read are read as `Variant`.
let duplicate: VariantArray = unsafe { self.as_inner().duplicate(false) };
// SAFETY: duplicate() returns a typed array with the same type as Self, and all values are taken from `self` so have the right type.
unsafe { duplicate.assume_type() }
}
/// Returns a deep copy of the array. All nested arrays and dictionaries are duplicated and
/// will not be shared with the original array. Note that any `Object`-derived elements will
/// still be shallow copied.
///
/// To create a shallow copy, use [`duplicate_shallow()`][Self::duplicate_shallow] instead.
/// To create a new reference to the same array data, use [`clone()`][Clone::clone].
pub fn duplicate_deep(&self) -> Self {
// SAFETY: We never write to the duplicated array, and all values read are read as `Variant`.
let duplicate: VariantArray = unsafe { self.as_inner().duplicate(true) };
// SAFETY: duplicate() returns a typed array with the same type as Self, and all values are taken from `self` so have the right type.
unsafe { duplicate.assume_type() }
}
/// Returns a sub-range `begin..end`, as a new array.
///
/// The values of `begin` (inclusive) and `end` (exclusive) will be clamped to the array size.
///
/// If specified, `step` is the relative index between source elements. It can be negative,
/// in which case `begin` must be higher than `end`. For example,
/// `Array::from(&[0, 1, 2, 3, 4, 5]).slice(5, 1, -2)` returns `[5, 3]`.
///
/// Array elements are copied to the slice, but any reference types (such as `Array`,
/// `Dictionary` and `Object`) will still refer to the same value. To create a deep copy, use
/// [`subarray_deep()`][Self::subarray_deep] instead.
#[doc(alias = "slice")]
pub fn subarray_shallow(&self, begin: usize, end: usize, step: Option<isize>) -> Self {
self.subarray_impl(begin, end, step, false)
}
/// Returns a sub-range `begin..end`, as a new `Array`.
///
/// The values of `begin` (inclusive) and `end` (exclusive) will be clamped to the array size.
///
/// If specified, `step` is the relative index between source elements. It can be negative,
/// in which case `begin` must be higher than `end`. For example,
/// `Array::from(&[0, 1, 2, 3, 4, 5]).slice(5, 1, -2)` returns `[5, 3]`.
///
/// All nested arrays and dictionaries are duplicated and will not be shared with the original
/// array. Note that any `Object`-derived elements will still be shallow copied. To create a
/// shallow copy, use [`subarray_shallow()`][Self::subarray_shallow] instead.
#[doc(alias = "slice")]
pub fn subarray_deep(&self, begin: usize, end: usize, step: Option<isize>) -> Self {
self.subarray_impl(begin, end, step, true)
}
fn subarray_impl(&self, begin: usize, end: usize, step: Option<isize>, deep: bool) -> Self {
assert_ne!(step, Some(0), "subarray: step cannot be zero");
let len = self.len();
let begin = begin.min(len);
let end = end.min(len);
let step = step.unwrap_or(1);
// SAFETY: The type of the array is `T` and we convert the returned array to an `Array<T>` immediately.
let subarray: VariantArray = unsafe {
self.as_inner()
.slice(to_i64(begin), to_i64(end), step.try_into().unwrap(), deep)
};
// SAFETY: slice() returns a typed array with the same type as Self
unsafe { subarray.assume_type() }
}
/// Returns an iterator over the elements of the `Array`. Note that this takes the array
/// by reference but returns its elements by value, since they are internally converted from
/// `Variant`.
///
/// Notice that it's possible to modify the `Array` through another reference while
/// iterating over it. This will not result in unsoundness or crashes, but will cause the
/// iterator to behave in an unspecified way.
pub fn iter_shared(&self) -> Iter<'_, T> {
Iter {
array: self,
next_idx: 0,
}
}
/// Returns the minimum value contained in the array if all elements are of comparable types.
///
/// If the elements can't be compared or the array is empty, `None` is returned.
pub fn min(&self) -> Option<T> {
let min = self.as_inner().min();
(!min.is_nil()).then(|| T::from_variant(&min))
}
/// Returns the maximum value contained in the array if all elements are of comparable types.
///
/// If the elements can't be compared or the array is empty, `None` is returned.
pub fn max(&self) -> Option<T> {
let max = self.as_inner().max();
(!max.is_nil()).then(|| T::from_variant(&max))
}
/// Returns a random element from the array, or `None` if it is empty.
pub fn pick_random(&self) -> Option<T> {
(!self.is_empty()).then(|| {
let variant = self.as_inner().pick_random();
T::from_variant(&variant)
})
}
/// Searches the array for the first occurrence of a value and returns its index, or `None` if
/// not found. Starts searching at index `from`; pass `None` to search the entire array.
pub fn find(&self, value: &T, from: Option<usize>) -> Option<usize> {
let from = to_i64(from.unwrap_or(0));
let index = self.as_inner().find(&value.to_variant(), from);
if index >= 0 {
Some(index.try_into().unwrap())
} else {
None
}
}
/// Searches the array backwards for the last occurrence of a value and returns its index, or
/// `None` if not found. Starts searching at index `from`; pass `None` to search the entire
/// array.
pub fn rfind(&self, value: &T, from: Option<usize>) -> Option<usize> {
let from = from.map(to_i64).unwrap_or(-1);
let index = self.as_inner().rfind(&value.to_variant(), from);
// It's not documented, but `rfind` returns -1 if not found.
if index >= 0 {
Some(to_usize(index))
} else {
None
}
}
/// Finds the index of an existing value in a sorted array using binary search.
/// Equivalent of `bsearch` in GDScript.
///
/// If the value is not present in the array, returns the insertion index that
/// would maintain sorting order.
///
/// Calling `bsearch` on an unsorted array results in unspecified behavior.
pub fn bsearch(&self, value: &T) -> usize {
to_usize(self.as_inner().bsearch(&value.to_variant(), true))
}
/// Finds the index of an existing value in a sorted array using binary search.
/// Equivalent of `bsearch_custom` in GDScript.
///
/// Takes a `Callable` and uses the return value of it to perform binary search.
///
/// If the value is not present in the array, returns the insertion index that
/// would maintain sorting order.
///
/// Calling `bsearch_custom` on an unsorted array results in unspecified behavior.
///
/// Consider using `sort_custom()` to ensure the sorting order is compatible with
/// your callable's ordering
pub fn bsearch_custom(&self, value: &T, func: Callable) -> usize {
to_usize(
self.as_inner()
.bsearch_custom(&value.to_variant(), func, true),
)
}
/// Reverses the order of the elements in the array.
pub fn reverse(&mut self) {
// SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
unsafe { self.as_inner_mut() }.reverse();
}
/// Sorts the array.
///
/// Note: The sorting algorithm used is not [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
/// This means that values considered equal may have their order changed when using `sort_unstable`.
#[doc(alias = "sort")]
pub fn sort_unstable(&mut self) {
// SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
unsafe { self.as_inner_mut() }.sort();
}
/// Sorts the array.
///
/// Uses the provided `Callable` to determine ordering.
///
/// Note: The sorting algorithm used is not [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability).
/// This means that values considered equal may have their order changed when using `sort_unstable_custom`.
#[doc(alias = "sort_custom")]
pub fn sort_unstable_custom(&mut self, func: Callable) {
// SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
unsafe { self.as_inner_mut() }.sort_custom(func);
}
/// Shuffles the array such that the items will have a random order. This method uses the
/// global random number generator common to methods such as `randi`. Call `randomize` to
/// ensure that a new seed will be used each time if you want non-reproducible shuffling.
pub fn shuffle(&mut self) {
// SAFETY: We do not write any values that don't already exist in the array, so all values have the correct type.
unsafe { self.as_inner_mut() }.shuffle();
}
/// Asserts that the given index refers to an existing element.
///
/// # Panics
///
/// If `index` is out of bounds.
fn check_bounds(&self, index: usize) {
let len = self.len();
assert!(
index < len,
"Array index {index} is out of bounds: length is {len}",
);
}
/// Returns a pointer to the element at the given index.
///
/// # Panics
///
/// If `index` is out of bounds.
fn ptr(&self, index: usize) -> sys::GDExtensionConstVariantPtr {
let ptr = self.ptr_or_null(index);
assert!(
!ptr.is_null(),
"Array index {index} out of bounds (len {len})",
len = self.len(),
);
ptr
}
/// Returns a pointer to the element at the given index, or null if out of bounds.
fn ptr_or_null(&self, index: usize) -> sys::GDExtensionConstVariantPtr {
// SAFETY: array_operator_index_const returns null for invalid indexes.
let variant_ptr = unsafe {
let index = to_i64(index);
interface_fn!(array_operator_index_const)(self.sys(), index)
};
// Signature is wrong in GDExtension, semantically this is a const ptr
sys::SysPtr::as_const(variant_ptr)
}
/// Returns a mutable pointer to the element at the given index.
///
/// # Panics
///
/// If `index` is out of bounds.
fn ptr_mut(&mut self, index: usize) -> sys::GDExtensionVariantPtr {
let ptr = self.ptr_mut_or_null(index);
assert!(
!ptr.is_null(),
"Array index {index} out of bounds (len {len})",
len = self.len(),
);
ptr
}
/// Returns a pointer to the element at the given index, or null if out of bounds.
fn ptr_mut_or_null(&mut self, index: usize) -> sys::GDExtensionVariantPtr {
// SAFETY: array_operator_index returns null for invalid indexes.
unsafe {
let index = to_i64(index);
interface_fn!(array_operator_index)(self.sys_mut(), index)
}
}
/// # Safety
///
/// This has the same safety issues as doing `self.assume_type::<Variant>()` and so the relevant safety invariants from
/// [`assume_type`](Self::assume_type) must be upheld.
///
/// In particular this means that all reads are fine, since all values can be converted to `Variant`. However, writes are only OK
/// if they match the type `T`.
#[doc(hidden)]
pub unsafe fn as_inner_mut(&self) -> inner::InnerArray {
// The memory layout of `Array<T>` does not depend on `T`.
inner::InnerArray::from_outer_typed(self)
}
fn as_inner(&self) -> ImmutableInnerArray {
ImmutableInnerArray {
// SAFETY: We can only read from the array.
inner: unsafe { self.as_inner_mut() },
}
}
/// Changes the generic type on this array, without changing its contents. Needed for API
/// functions that return a variant array even though we know its type, and for API functions
/// that take a variant array even though we want to pass a typed one.
///
/// # Safety
///
/// - Any values written to the array must match the runtime type of the array.
/// - Any values read from the array must be convertible to the type `U`.
///
/// If the safety invariant of `Array` is intact, which it must be for any publicly accessible arrays, then `U` must match
/// the runtime type of the array. This then implies that both of the conditions above hold. This means that you only need
/// to keep the above conditions in mind if you are intentionally violating the safety invariant of `Array`.
///
/// Note also that any `GodotType` can be written to a `Variant` array.
///
/// In the current implementation, both cases will produce a panic rather than undefined behavior, but this should not be relied upon.
unsafe fn assume_type<U: ArrayElement>(self) -> Array<U> {
// The memory layout of `Array<T>` does not depend on `T`.
std::mem::transmute::<Array<T>, Array<U>>(self)
}
/// # Safety
/// See [`assume_type`](Self::assume_type).
unsafe fn assume_type_ref<U: ArrayElement>(&self) -> &Array<U> {
// The memory layout of `Array<T>` does not depend on `T`.
std::mem::transmute::<&Array<T>, &Array<U>>(self)
}
#[cfg(debug_assertions)]
pub(crate) fn debug_validate_elements(&self) -> Result<(), ConvertError> {
// SAFETY: every element is internally represented as Variant.
let canonical_array = unsafe { self.assume_type_ref::<Variant>() };
// If any element is not convertible, this will return an error.
for elem in canonical_array.iter_shared() {
elem.try_to::<T>().map_err(|_err| {
FromGodotError::BadArrayTypeInt {
expected: self.type_info(),
value: elem
.try_to::<i64>()
.expect("origin must be i64 compatible; this is a bug"),
}
.into_error(self.clone())
})?;
}
Ok(())
}
// No-op in Release. Avoids O(n) conversion checks, but still panics on access.
#[cfg(not(debug_assertions))]
pub(crate) fn debug_validate_elements(&self) -> Result<(), ConvertError> {
Ok(())
}
/// Returns the runtime type info of this array.
fn type_info(&self) -> ArrayTypeInfo {
let variant_type = VariantType::from_sys(
self.as_inner().get_typed_builtin() as sys::GDExtensionVariantType
);
let class_name = if variant_type == VariantType::OBJECT {
Some(self.as_inner().get_typed_class_name())
} else {
None
};
ArrayTypeInfo {
variant_type,
class_name,
}
}
/// Checks that the inner array has the correct type set on it for storing elements of type `T`.
fn with_checked_type(self) -> Result<Self, ConvertError> {
let self_ty = self.type_info();
let target_ty = ArrayTypeInfo::of::<T>();
if self_ty == target_ty {
Ok(self)
} else {
Err(FromGodotError::BadArrayType {
expected: target_ty,
actual: self_ty,
}
.into_error(self))
}
}
/// Sets the type of the inner array.
///
/// # Safety
///
/// Must only be called once, directly after creation.
unsafe fn init_inner_type(&mut self) {
debug_assert!(self.is_empty());
debug_assert!(!self.type_info().is_typed());
let type_info = ArrayTypeInfo::of::<T>();
if type_info.is_typed() {
let script = Variant::nil();
// A bit contrived because empty StringName is lazy-initialized but must also remain valid.
#[allow(unused_assignments)]
let mut empty_string_name = None;
let class_name = if let Some(class_name) = &type_info.class_name {
class_name.string_sys()
} else {
empty_string_name = Some(StringName::default());
// as_ref() crucial here -- otherwise the StringName is dropped.
empty_string_name.as_ref().unwrap().string_sys()
};
// SAFETY: The array is a newly created empty untyped array.
unsafe {
interface_fn!(array_set_typed)(
self.sys_mut(),
type_info.variant_type.sys(),
class_name, // must be empty if variant_type != OBJECT.
script.var_sys(),
);
}
}
}
/// Returns a clone of the array without checking the resulting type.
///
/// # Safety
/// Should be used only in scenarios where the caller can guarantee that the resulting array will have the correct type,
/// or when an incorrect Rust type is acceptable (passing raw arrays to Godot FFI).
unsafe fn clone_unchecked(&self) -> Self {
Self::new_with_uninit(|self_ptr| {
let ctor = sys::builtin_fn!(array_construct_copy);
let args = [self.sys()];
ctor(self_ptr, args.as_ptr());
})
}
/// Whether this array is untyped and holds `Variant` elements (compile-time check).
///
/// Used as `if` statement in trait impls. Avoids defining yet another trait or non-local overridden function just for this case;
/// `Variant` is the only Godot type that has variant type NIL and can be used as an array element.
fn has_variant_t() -> bool {
T::Ffi::variant_type() == VariantType::NIL
}
}
impl VariantArray {
/// # Safety
/// - Variant must have type `VariantType::ARRAY`.
/// - Subsequent operations on this array must not rely on the type of the array.
pub(crate) unsafe fn from_variant_unchecked(variant: &Variant) -> Self {
// See also ffi_from_variant().
Self::new_with_uninit(|self_ptr| {
let array_from_variant = sys::builtin_fn!(array_from_variant);
array_from_variant(self_ptr, sys::SysPtr::force_mut(variant.var_sys()));
})
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Traits
// Godot has some inconsistent behavior around NaN values. In GDScript, `NAN == NAN` is `false`,
// but `[NAN] == [NAN]` is `true`. If they decide to make all NaNs equal, we can implement `Eq` and
// `Ord`; if they decide to make all NaNs unequal, we can remove this comment.
//
// impl<T> Eq for Array<T> {}
//
// impl<T> Ord for Array<T> {
// ...
// }
// SAFETY:
// - `move_return_ptr`
// Nothing special needs to be done beyond a `std::mem::swap` when returning an Array.
// So we can just use `ffi_methods`.
//
// - `from_arg_ptr`
// Arrays are properly initialized through a `from_sys` call, but the ref-count should be incremented
// as that is the callee's responsibility. Which we do by calling `std::mem::forget(array.clone())`.
unsafe impl<T: ArrayElement> GodotFfi for Array<T> {
fn variant_type() -> VariantType {
VariantType::ARRAY
}
ffi_methods! { type sys::GDExtensionTypePtr = *mut Opaque; .. }
}
// Only implement for untyped arrays; typed arrays cannot be nested in Godot.
impl ArrayElement for VariantArray {}
impl<T: ArrayElement> GodotConvert for Array<T> {
type Via = Self;
}
impl<T: ArrayElement> ToGodot for Array<T> {
type ToVia<'v> = Self::Via;
fn to_godot(&self) -> Self::ToVia<'_> {
// SAFETY: only safe when passing to FFI in a context where Rust-side type doesn't matter.
// TODO: avoid unsafety with either of the following:
// * OutArray -- https://github.com/godot-rust/gdext/pull/806.
// * Instead of cloning, use ArgRef<Array<T>>.
unsafe { self.clone_unchecked() }
//self.clone()
}
fn to_variant(&self) -> Variant {
self.ffi_to_variant()
}
}
impl<T: ArrayElement> FromGodot for Array<T> {
fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
T::debug_validate_elements(&via)?;
Ok(via)
}
}
impl<T: ArrayElement> fmt::Debug for Array<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Going through `Variant` because there doesn't seem to be a direct way.
// Reuse Display.
write!(f, "{}", self.to_variant().stringify())
}
}
impl<T: ArrayElement + fmt::Display> fmt::Display for Array<T> {
/// Formats `Array` to match Godot's string representation.
///
/// # Example
/// ```no_run
/// # use godot::prelude::*;
/// let a = array![1,2,3,4];
/// assert_eq!(format!("{a}"), "[1, 2, 3, 4]");
/// ```
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (count, v) in self.iter_shared().enumerate() {
if count != 0 {
write!(f, ", ")?;
}
write!(f, "{v}")?;
}
write!(f, "]")
}
}
/// Creates a new reference to the data in this array. Changes to the original array will be
/// reflected in the copy and vice versa.
///
/// To create a (mostly) independent copy instead, see [`Array::duplicate_shallow()`] and
/// [`Array::duplicate_deep()`].
impl<T: ArrayElement> Clone for Array<T> {
fn clone(&self) -> Self {
// SAFETY: `self` is a valid array, since we have a reference that keeps it alive.
// Type-check follows below.
let copy = unsafe { self.clone_unchecked() };
// Double-check copy's runtime type in Debug mode.
if cfg!(debug_assertions) {
copy.with_checked_type()
.expect("copied array should have same type as original array")
} else {
copy
}
}
}
impl<T: ArrayElement> Var for Array<T> {
fn get_property(&self) -> Self::Via {
self.to_godot()
}
fn set_property(&mut self, value: Self::Via) {
*self = FromGodot::from_godot(value)
}
fn var_hint() -> PropertyHintInfo {
// For array #[var], the hint string is "PackedInt32Array", "Node" etc. for typed arrays, and "" for untyped arrays.
if Self::has_variant_t() {
PropertyHintInfo::none()
} else if sys::GdextBuild::since_api("4.2") {
PropertyHintInfo::var_array_element::<T>()
} else {
// Godot 4.1 was not using PropertyHint::ARRAY_TYPE, but the empty hint instead.
PropertyHintInfo::none()
}