use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
pub struct Slice<'a, T> {
ptr: *mut T,
len: usize,
_marker: PhantomData<&'a mut T>,
}
impl<'a, T> Slice<'a, T> {
#[inline]
pub unsafe fn from_raw_parts(ptr: *mut T, len: usize) -> Self {
Slice {
ptr,
len,
_marker: PhantomData,
}
}
#[inline]
pub fn as_ptr(&self) -> *const T {
self.ptr as *const T
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.ptr
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub unsafe fn as_slice(&self) -> &[T] {
std::slice::from_raw_parts(self.as_ptr(), self.len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len)
}
}
impl<'a, T> Deref for Slice<'a, T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
unsafe { self.as_slice() }
}
}
impl<'a, T> DerefMut for Slice<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
unsafe { self.as_mut_slice() }
}
}
impl<'a, T: std::fmt::Debug> std::fmt::Debug for Slice<'a, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
unsafe { f.debug_struct("Slice")
.field("ptr", &self.as_ptr())
.field("len", &self.len)
.field("data", &self.as_slice())
.finish() }
}
}
impl<'a, T: PartialEq> PartialEq for Slice<'a, T> {
fn eq(&self, other: &Self) -> bool {
unsafe { self.as_slice() == other.as_slice() }
}
}
impl<'a, T: Eq> Eq for Slice<'a, T> {}