Skip to content

Commit

Permalink
Remapped the lifetimes of FFISlice and FFISliceMut a bit.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Earthmark committed Jun 29, 2024
1 parent 44fa761 commit a201afb
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions core/src/patterns/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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::<u8>::empty();
let target: &mut [u8] = {
let mut some = FFISliceMut::<u8>::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]);
}
}

0 comments on commit a201afb

Please sign in to comment.