Skip to content

Instantly share code, notes, and snippets.

@evaporei
Last active April 12, 2025 00:07
Show Gist options
  • Save evaporei/9182f5dad18240419b423985e97c99e1 to your computer and use it in GitHub Desktop.
Save evaporei/9182f5dad18240419b423985e97c99e1 to your computer and use it in GitHub Desktop.
Odin's Small_Array in Rust
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
}
}
@evaporei
Copy link
Author

evaporei commented Apr 11, 2025

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment