Skip to content

Commit bc01b35

Browse files
authored
Merge pull request #496 from Lemiczek/try_get
Implement `try_get` on `Array`
2 parents 9016ae2 + fccc2be commit bc01b35

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

godot-core/src/builtin/array.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,18 @@ impl<T: GodotType + FromGodot> Array<T> {
404404
T::from_variant(variant)
405405
}
406406

407+
/// Returns the value at the specified index or `None` if the index is out-of-bounds.
408+
pub fn try_get(&self, index: usize) -> Option<T> {
409+
let ptr = self.ptr_or_null(index);
410+
if ptr.is_null() {
411+
None
412+
} else {
413+
// SAFETY: `ptr.is_null()` just verified that the index is not out of bounds.
414+
let variant = unsafe { &*ptr };
415+
Some(T::from_variant(variant))
416+
}
417+
}
418+
407419
/// Returns the first element in the array, or `None` if the array is empty. Equivalent of
408420
/// `front()` in GDScript.
409421
pub fn first(&self) -> Option<T> {

itest/rust/src/builtin_tests/containers/array_test.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,15 @@ fn array_get() {
168168
});
169169
}
170170

171+
#[itest]
172+
fn array_try_get() {
173+
let array = array![1, 2];
174+
175+
assert_eq!(array.try_get(0), Some(1));
176+
assert_eq!(array.try_get(1), Some(2));
177+
assert_eq!(array.try_get(2), None);
178+
}
179+
171180
#[itest]
172181
fn array_first_last() {
173182
let array = array![1, 2];

0 commit comments

Comments
 (0)