Last active
April 12, 2025 00:07
-
-
Save evaporei/9182f5dad18240419b423985e97c99e1 to your computer and use it in GitHub Desktop.
Odin's Small_Array in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct SmallArray<const N: usize, T> { | |
data: [T; N], | |
count: usize, | |
} | |
impl<const N: usize, T> Default for SmallArray<N, T> { | |
fn default() -> Self { | |
Self { | |
data: std::array::from_fn(|_| unsafe { std::mem::zeroed() }), | |
count: 0, | |
} | |
} | |
} | |
impl<const N: usize, T> SmallArray<N, T> { | |
pub fn new() -> Self { | |
Self::default() | |
} | |
pub fn push(&mut self, elem: T) { | |
assert!(self.count < N); | |
self.data[self.count] = elem; | |
self.count += 1; | |
} | |
#[inline(always)] | |
pub fn len(&self) -> usize { | |
self.count | |
} | |
#[inline(always)] | |
pub fn is_empty(&self) -> bool { | |
self.count == 0 | |
} | |
} | |
use std::ops::Index; | |
impl<const N: usize, T> Index<usize> for SmallArray<N, T> { | |
type Output = T; | |
fn index(&self, i: usize) -> &Self::Output { | |
assert!(i < N); | |
&self.data[i] | |
} | |
} | |
use std::ops::IndexMut; | |
impl<const N: usize, T> IndexMut<usize> for SmallArray<N, T> { | |
fn index_mut(&mut self, i: usize) -> &mut Self::Output { | |
assert!(i < N); | |
&mut self.data[i] | |
} | |
} | |
use std::ops::Deref; | |
impl<const N: usize, T> Deref for SmallArray<N, T> { | |
type Target = [T; N]; | |
fn deref(&self) -> &Self::Target { | |
&self.data | |
} | |
} | |
use std::ops::DerefMut; | |
impl<const N: usize, T> DerefMut for SmallArray<N, T> { | |
fn deref_mut(&mut self) -> &mut Self::Target { | |
&mut self.data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can only be used with types that are safe to use with
std::mem::zeroed
.Also, those asserts are not necessary, indexing out of bounds in the slice will already do that.
And with
Deref
/DerefMut
you can access the pointer directly to the array (std::slice::as_ptr()
) so you can pass the raw data to a graphics API for example (eg: OpenGL).