use std::{ borrow::Borrow, fmt::{self, Debug, Formatter}, hash::{Hash, Hasher}, ops::{Deref, Range}, sync::Arc, }; /// A owned slice that is backed by an `Arc`. #[derive(Clone)] pub struct ArcSlice { data: *const [T], arc: Arc<[T]>, } unsafe impl Send for ArcSlice {} unsafe impl Sync for ArcSlice {} impl From> for ArcSlice { fn from(arc: Arc<[T]>) -> Self { Self { data: &*arc as *const [T], arc, } } } impl From> for ArcSlice { fn from(b: Box<[T]>) -> Self { Self::from(Arc::from(b)) } } impl Deref for ArcSlice { type Target = [T]; fn deref(&self) -> &Self::Target { unsafe { &*self.data } } } impl Borrow<[T]> for ArcSlice { fn borrow(&self) -> &[T] { self } } impl Hash for ArcSlice { fn hash(&self, state: &mut H) { self.deref().hash(state) } } impl PartialEq for ArcSlice { fn eq(&self, other: &Self) -> bool { self.deref().eq(other.deref()) } } impl Debug for ArcSlice { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Debug::fmt(&**self, f) } } impl Eq for ArcSlice {} impl ArcSlice { /// Creates a new `ArcSlice` from a pointer to a slice and an `Arc`. /// /// # Safety /// /// The caller must ensure that the pointer is pointing to a valid slice that is kept alive by /// the `Arc`. pub unsafe fn new_unchecked(data: *const [T], arc: Arc<[T]>) -> Self { Self { data, arc } } /// Get the backing arc pub fn full_arc(this: &ArcSlice) -> Arc<[T]> { this.arc.clone() } /// Returns a new `ArcSlice` that points to a slice of the current slice. pub fn slice(self, range: Range) -> ArcSlice { let data = &*self; let data = &data[range] as *const [T]; Self { data, arc: self.arc, } } }