use std::cell::UnsafeCell;
pub struct Column<T: Copy + Default> {
data: UnsafeCell<Vec<T>>,
retired: UnsafeCell<Vec<Vec<T>>>,
}
impl<T: Copy + Default> Column<T> {
pub fn new(size: usize) -> Self {
Self { data: UnsafeCell::new(vec![T::default(); size]), retired: UnsafeCell::new(Vec::new()) }
}
pub fn from_vec(data: Vec<T>) -> Self {
Self { data: UnsafeCell::new(data), retired: UnsafeCell::new(Vec::new()) }
}
#[inline(always)]
fn vec(&self) -> &Vec<T> {
unsafe { &*self.data.get() }
}
#[inline(always)]
#[allow(clippy::mut_from_ref)]
fn vec_mut(&self) -> &mut Vec<T> {
unsafe { &mut *self.data.get() }
}
#[inline(always)]
pub fn get(&self, id: u32) -> T {
self.vec().get(id as usize).copied().unwrap_or_default()
}
#[inline(always)]
pub fn set(&self, id: u32, value: T) {
if let Some(slot) = self.vec_mut().get_mut(id as usize) {
*slot = value;
}
}
#[inline(always)]
pub fn len(&self) -> usize {
self.vec().len()
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.vec().is_empty()
}
pub fn resize(&self, size: usize) {
let vec = self.vec_mut();
if size <= vec.capacity() {
vec.resize(size, T::default());
return;
}
let mut grown = Vec::with_capacity(size);
grown.extend_from_slice(vec);
grown.resize(size, T::default());
let previous = std::mem::replace(vec, grown);
unsafe { (*self.retired.get()).push(previous) };
}
pub fn replace(&self, data: Vec<T>) -> Vec<T> {
std::mem::replace(self.vec_mut(), data)
}
pub fn to_vec(&self) -> Vec<T> {
self.vec().clone()
}
pub fn as_ptr(&self) -> *const T {
self.vec().as_ptr()
}
pub fn as_mut_ptr(&self) -> *mut T {
self.vec_mut().as_mut_ptr()
}
}