You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@HeroicKatora stated in #8 (comment) and the following comments, that it might be possible to capture the lifetime of the original allocation and store with it the base-pointer and length. We can the check the base-pointer and length against the to-be-concatenated subsliced. The captured lifetime ensures that the allocation still exists, is valid and hasn't been changed. (playground
pubstructSameAllocation<'a,T>{phantom:PhantomData<&'a [T]>,base:usize,bytes:usize,}impl<'a,T>SameAllocation<'a,T>{pubfnnew(ptr:&'a [T]) -> Self{SameAllocation{phantom:PhantomData,base: ptr.as_ptr()asusize,bytes: ptr.len()* mem::size_of::<T>(),}}// Pretend to borrow but return the complete array.pubfnnew_mut(ptr:&'a mut[T]) -> (Self,&'a mut[T]){let result = SameAllocation{phantom:PhantomData,base: ptr.as_ptr()asusize,bytes: ptr.len()* mem::size_of::<T>(),};(result, ptr)}// Possible `unsafe fn new_unchecked` variant omitted// Join two slices that must be part of the allocation used in the construction.pubfnjoin<'b:'a>(&self,a:&'b mut[T],b:&'b mut[T]) -> Result<&'b mut[T],Error>{// Assert the beginning is within the allocation. Instead of asserting we could error.// This guarantees each complete slice is within the same allocation.assert!(self.base <= a.as_ptr()asusize && a.as_ptr()asusize <= self.base + self.bytes);assert!(self.base <= b.as_ptr()asusize && b.as_ptr()asusize <= self.base + self.bytes);unsafe{// SAFETY: Guaranteed the exact check we need for the current method.concat_slice_unchecked(a, b)}}}// usage:fnmain(){letmut data = [0xa;16];let(allocation, data) = SameAllocation::new_mut(&mut data[..]);let(a, b) = data.split_at_mut(10);let rejoined = allocation.join(a, b).unwrap();assert_eq!(rejoined,&[0xa;16]);}
The text was updated successfully, but these errors were encountered:
A crucial difference is that the above code does not use the stored pointer as a reference so no other mutable borrows are invalidated. Thus the caller need not unsafely ensure that no such borrows exist.
@HeroicKatora stated in #8 (comment) and the following comments, that it might be possible to capture the lifetime of the original allocation and store with it the base-pointer and length. We can the check the base-pointer and length against the to-be-concatenated subsliced. The captured lifetime ensures that the allocation still exists, is valid and hasn't been changed. (playground
The text was updated successfully, but these errors were encountered: