Skip to content

Commit d720c42

Browse files
committed
feat: mutable array iter
1 parent 42f99ed commit d720c42

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

src/game/core.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,24 @@ impl<T> TArray<T> {
105105
Some(item)
106106
}
107107

108+
/// Gets a reference to specific element by index
109+
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
110+
if index >= self.len() {
111+
return None;
112+
}
113+
114+
// Get a pointer to the data at the provided index
115+
let item = unsafe { self.data.add(index) };
116+
117+
let item = match unsafe { item.as_mut() } {
118+
Some(value) => value,
119+
// Will only occur if array was created from an invalid data ptr
120+
None => panic!("Array item at index {index} was a nullptr"),
121+
};
122+
123+
Some(item)
124+
}
125+
108126
/// Returns the length of the array
109127
pub fn len(&self) -> usize {
110128
self.count as usize
@@ -143,6 +161,14 @@ impl<T> TArray<T> {
143161
}
144162
}
145163

164+
/// Creates a reference iterator for the values within the array
165+
pub fn iter_mut(&mut self) -> TArrayIterMut<'_, T> {
166+
TArrayIterMut {
167+
arr: self,
168+
index: 0,
169+
}
170+
}
171+
146172
/// Creates a [Vec] from the array, they are the same type
147173
/// just have a different memory structure.
148174
///
@@ -280,6 +306,35 @@ impl<'a, T> Iterator for TArrayIter<'a, T> {
280306
Some(item)
281307
}
282308
}
309+
/// Iterator for a [TArray]
310+
pub struct TArrayIterMut<'a, T> {
311+
arr: &'a mut TArray<T>,
312+
index: usize,
313+
}
314+
315+
impl<'a, T> Iterator for TArrayIterMut<'a, T> {
316+
type Item = &'a mut T;
317+
318+
fn next(&mut self) -> Option<Self::Item> {
319+
// Reached end of array
320+
if self.index >= self.arr.len() {
321+
return None;
322+
}
323+
324+
// Get a pointer to the data at the provided index
325+
let item = unsafe { self.arr.data.add(self.index) };
326+
327+
let item = match unsafe { item.as_mut() } {
328+
Some(value) => value,
329+
// Will only occur if array was created from an invalid data ptr
330+
None => panic!("Array item at index {} was a nullptr", self.index),
331+
};
332+
333+
self.index += 1;
334+
335+
Some(item)
336+
}
337+
}
283338

284339
/// Unreal engine UTF-16 string based on a [TArray] of [u16] the string
285340
/// values present are null terminated

0 commit comments

Comments
 (0)