Skip to content

Commit 5b80c73

Browse files
committed
Add Index + IndexMut operators for PackedArray
1 parent d7bf5bd commit 5b80c73

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

godot-core/src/builtin/packed_array.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use godot_ffi as sys;
99

1010
use crate::builtin::meta::ToGodot;
1111
use crate::builtin::*;
12-
use std::fmt;
12+
use std::{fmt, ops};
1313
use sys::types::*;
1414
use sys::{ffi_methods, interface_fn, GodotFfi};
1515

@@ -394,6 +394,24 @@ macro_rules! impl_packed_array {
394394
}
395395
}
396396

397+
impl ops::Index<usize> for $PackedArray {
398+
type Output = $Element;
399+
400+
fn index(&self, index: usize) -> &Self::Output {
401+
let ptr = self.ptr(index);
402+
// SAFETY: `ptr` checked bounds.
403+
unsafe { &*ptr }
404+
}
405+
}
406+
407+
impl ops::IndexMut<usize> for $PackedArray {
408+
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
409+
let ptr = self.ptr_mut(index);
410+
// SAFETY: `ptr` checked bounds.
411+
unsafe { &mut *ptr }
412+
}
413+
}
414+
397415
#[doc = concat!("Creates a `", stringify!($PackedArray), "` from the given Rust array.")]
398416
impl<const N: usize> From<&[$Element; N]> for $PackedArray {
399417
fn from(arr: &[$Element; N]) -> Self {

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,31 @@ fn packed_array_as_mut_slice() {
130130
assert_eq!(empty.as_mut_slice(), &mut []);
131131
}
132132

133+
#[itest]
134+
fn packed_array_index() {
135+
let array = PackedByteArray::from(&[1, 2]);
136+
137+
assert_eq!(array[0], 1);
138+
assert_eq!(array[1], 2);
139+
expect_panic("Array index 2 out of bounds: length is 2", || {
140+
let _ = array[2];
141+
});
142+
143+
let mut array = PackedStringArray::new();
144+
expect_panic("Array index 0 out of bounds: length is 0", || {
145+
let _ = array[0];
146+
});
147+
148+
array.push("first".into());
149+
array.push("second".into());
150+
151+
assert_eq!(array[0], "first".into());
152+
assert_eq!(array[1], "second".into());
153+
154+
array[0] = "begin".into();
155+
assert_eq!(array[0], "begin".into());
156+
}
157+
133158
#[itest]
134159
fn packed_array_get() {
135160
let array = PackedByteArray::from(&[1, 2]);

0 commit comments

Comments
 (0)