null-vec 0.1.0

A specialized vector that stores nullable values.
#![feature(alloc)]
#![feature(const_fn)]

extern crate alloc;

#[cfg(test)] mod tests;

use alloc::raw_vec::RawVec;
use std::{mem, ptr};

/// A type with a null value.
pub trait Nullable {
    const NULL: Self;

    fn is_null(&self) -> bool;
}

impl<T> Nullable for *const T {
    const NULL: Self = ptr::null();

    fn is_null(&self) -> bool {
        <*const T>::is_null(*self)
    }
}

impl<T> Nullable for *mut T {
    const NULL: Self = ptr::null_mut();

    fn is_null(&self) -> bool {
        <*mut T>::is_null(*self)
    }
}

impl<T> Nullable for Option<T> {
    const NULL: Self = None;

    fn is_null(&self) -> bool {
        self.is_none()
    }
}

/// A vector of a nullable type. Conceptually the vector is an infinite list of values, some of 
/// which are non-null. This allows constant-time removal of elements by index.
pub struct NullVec<T: Nullable> {
    raw: RawVec<T>,
}

impl<T: Nullable> NullVec<T> {
    pub fn new() -> Self {
        NullVec { raw: RawVec::new() }
    }

    pub fn with_capacity(cap: usize) -> Self {
        let mut vec = NullVec { raw: RawVec::with_capacity(cap) };
        for i in 0..vec.raw.cap() {
            unsafe {
                ptr::write(vec.index_mut(i), T::NULL);
            }
        }
        vec
    }

    /// Inserts a value into the vector, returning the old value.
    pub fn insert<U: Into<T>>(&mut self, idx: usize, val: U) -> T {
        let cap = self.raw.cap();
        if cap <= idx {
            self.raw.reserve(cap, idx - cap + 1);
            for i in cap..self.raw.cap() {
                unsafe {
                    ptr::write(self.index_mut(i), T::NULL);
                }
            }
        }

        mem::replace(unsafe { self.index_mut(idx) }, val.into())
    }

    /// Removes a value from the vector, returning its value.
    pub fn remove(&mut self, idx: usize) -> T {
        if idx < self.raw.cap() {
            mem::replace(unsafe { self.index_mut(idx) }, T::NULL)
        } else {
            T::NULL
        }
    }

    /// Returns a value in the vector.
    pub fn get(&self, idx: usize) -> T where T: Copy {
        if idx < self.raw.cap() {
            *unsafe { self.index(idx) }
        } else {
            T::NULL
        }
    }

    /// Starting from `start`, returns the index of the first null value, or `capacity()` if
    /// no value was found.
    pub fn space(&self, start: usize) -> usize {
        for i in start..self.raw.cap() {
            unsafe {
                if self.index(i).is_null() {
                    return i;
                }
            }
        }
        return self.raw.cap()
    }
    
    unsafe fn index(&self, idx: usize) -> &T {
        &*self.raw.ptr().offset(idx as isize)
    }
    
    unsafe fn index_mut(&mut self, idx: usize) -> &mut T {
        &mut *self.raw.ptr().offset(idx as isize)
    }
}