From 57ba53db8123f78d64676ac9f9eea5690a7b292d Mon Sep 17 00:00:00 2001 From: Earthmark Date: Fri, 28 Jun 2024 17:25:08 -0700 Subject: [PATCH] Remapped the lifetimes of FFISlice and FFISliceMut a bit. This allows FFISlice and FFISliceMut to 'leak' a slice of the backing data, even though the returned slice has a valid actual lifetime. This allows FFISlice to be a pass-through through type. --- core/src/patterns/slice.rs | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/core/src/patterns/slice.rs b/core/src/patterns/slice.rs index 86e40620..cf5e5860 100644 --- a/core/src/patterns/slice.rs +++ b/core/src/patterns/slice.rs @@ -74,10 +74,7 @@ impl<'a, T> FFISlice<'a, T> { } /// Tries to return a slice if the pointer was not null. - pub fn as_slice<'b>(&'b self) -> &'b [T] - where - 'a: 'b, - { + pub fn as_slice(&self) -> &'a [T] { if self.data.is_null() { &[] } else { @@ -163,10 +160,7 @@ impl<'a, T> FFISliceMut<'a, T> { } /// Tries to return a slice if the pointer was not null. - pub fn as_slice_mut<'b>(&'b mut self) -> &'b mut [T] - where - 'a: 'b, - { + pub fn as_slice_mut(&mut self) -> &'a mut [T] { if self.data.is_null() { &mut [] } else { @@ -177,10 +171,7 @@ impl<'a, T> FFISliceMut<'a, T> { } /// Tries to return a slice if the pointer was not null. - pub fn as_slice<'b>(&'b self) -> &'b [T] - where - 'a: 'b, - { + pub fn as_slice(&self) -> &'a [T] { if self.data.is_null() { &[] } else { @@ -269,4 +260,21 @@ mod test { assert_eq!(empty.as_slice(), &[]); assert_eq!(slice, &[5, 6, 2, 3, 5]); } + + #[test] + fn multi_borrow_mut_slice() { + let slice = &mut [0, 1, 2, 3, 5]; + let empty = FFISliceMut::::empty(); + let target: &mut [u8] = { + let mut some = FFISliceMut::::from_slice(slice.as_mut()); + some.as_slice_mut() + }; + let sub = &mut target[1..=2]; + + sub[0] = 6; + target[0] = 5; + + assert_eq!(empty.as_slice(), &[]); + assert_eq!(slice, &[5, 6, 2, 3, 5]); + } }