Skip to content

Commit fccc2be

Browse files
committed
Implement try_get on Array
1 parent 13ab375 commit fccc2be

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
@@ -394,6 +394,18 @@ impl<T: GodotType + FromGodot> Array<T> {
394394
T::from_variant(variant)
395395
}
396396

397+
/// Returns the value at the specified index or `None` if the index is out-of-bounds.
398+
pub fn try_get(&self, index: usize) -> Option<T> {
399+
let ptr = self.ptr_or_null(index);
400+
if ptr.is_null() {
401+
None
402+
} else {
403+
// SAFETY: `ptr.is_null()` just verified that the index is not out of bounds.
404+
let variant = unsafe { &*ptr };
405+
Some(T::from_variant(variant))
406+
}
407+
}
408+
397409
/// Returns the first element in the array, or `None` if the array is empty. Equivalent of
398410
/// `front()` in GDScript.
399411
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
@@ -167,6 +167,15 @@ fn array_get() {
167167
});
168168
}
169169

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

0 commit comments

Comments
 (0)