use rawptr::{RawPtrExt, RawMutPtrExt};
pub trait RawSlice<T>: Copy + Sized {
unsafe fn as_slice<'a>(self) -> &'a [T];
fn len(self) -> usize {
unsafe { self.as_slice().len() }
}
fn as_ptr(self) -> *const T {
unsafe { self.as_slice().as_ptr() }
}
unsafe fn read(self, index: usize) -> T {
self.as_ptr().add(index).read()
}
unsafe fn get<'a>(self, index: usize) -> &'a T {
&*self.as_ptr().add(index)
}
unsafe fn slice(self, from: usize, to: usize) -> Self;
fn slice_to(self, to: usize) -> Self {
unsafe { self.slice(0, to) }
}
unsafe fn slice_from(self, from: usize) -> Self {
self.slice(from, self.len())
}
}
pub trait RawMutSlice<T> : RawSlice<T> + Sized {
unsafe fn as_mut_slice<'a>(self) -> &'a mut[T];
fn as_mut_ptr(self) -> *mut T;
unsafe fn write(self, index: usize, val: T);
unsafe fn write_bytes(self, byte: u8);
unsafe fn copy(self, from: *const[T]);
unsafe fn copy_nonoverlapping(self, from: *const[T]);
unsafe fn get_mut<'a>(self, index: usize) -> &'a mut T;
}
pub trait SliceRawExt<T> {
fn as_raw(&self) -> *const [T];
fn as_mut_raw(&mut self) -> *mut [T];
}
impl<T> SliceRawExt<T> for [T] {
fn as_raw(&self) -> *const [T] {
self as *const [T]
}
fn as_mut_raw(&mut self) -> *mut [T] {
self as *mut [T]
}
}
impl<T> RawSlice<T> for *const [T] {
unsafe fn as_slice<'a>(self) -> &'a [T] {
&*self
}
unsafe fn slice(self, from: usize, to: usize) -> *const [T] {
self.as_ptr().add(from).as_raw_slice(to - from)
}
}
impl<T> RawSlice<T> for *mut [T] {
unsafe fn as_slice<'a>(self) -> &'a [T] {
&*self
}
unsafe fn slice(self, from: usize, to: usize) -> *mut [T] {
self.as_mut_ptr().add(from).as_raw_mut_slice(to - from)
}
}
impl<T> RawMutSlice<T> for *mut [T] {
unsafe fn as_mut_slice<'a>(self) -> &'a mut[T] {
&mut *self
}
fn as_mut_ptr(self) -> *mut T {
unsafe { self.as_mut_slice().as_mut_ptr() }
}
unsafe fn write(self, index: usize, val: T) {
self.as_mut_ptr().add(index).write(val);
}
unsafe fn write_bytes(self, byte: u8) {
let len = self.len();
self.as_mut_ptr().write_bytes(byte, len);
}
unsafe fn copy(self, from: *const[T]) {
from.as_ptr().copy(self.as_mut_ptr(), from.len());
}
unsafe fn copy_nonoverlapping(self, from: *const[T]) {
from.as_ptr().copy_nonoverlapping(self.as_mut_ptr(), from.len());
}
unsafe fn get_mut<'a>(self, index: usize) -> &'a mut T {
&mut *self.as_mut_ptr().add(index)
}
}