Skip to content

Commit

Permalink
Add ArrayVec::leak
Browse files Browse the repository at this point in the history
  • Loading branch information
Lukas Sandström committed Apr 4, 2023
1 parent 0e131fd commit 298575d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/arrayvec.rs
Expand Up @@ -579,6 +579,19 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
Ok(())
}

/// Leak the contents of the vector and return a reference to them in a mutable slice.
///
/// This sets len() to zero. The elements will not be dropped. The backing memory will
/// not be lost however, as the ArrayVec can be used again as soon as the returned slice
/// is dropped.
pub fn leak(&mut self) -> &mut [T] {
unsafe {
let s = slice::from_raw_parts_mut(self.as_mut_ptr(), self.len());
self.set_len(0);
s
}
}

/// Create a draining iterator that removes the specified range in the vector
/// and yields the removed items from start to end. The element range is
/// removed even if the iterator is not consumed until the end.
Expand Down
9 changes: 9 additions & 0 deletions tests/tests.rs
Expand Up @@ -331,6 +331,15 @@ fn test_still_works_with_option_arrayvec() {
println!("{:?}", array);
}

#[test]
fn test_leak() {
let mut v = ArrayVec::from([1,2,3,4,5,6,7,8]);
assert_eq!(v.leak(), [1,2,3,4,5,6,7,8]);
assert_eq!(v.len(), 0);
v.try_extend_from_slice(&[1,2,3]).unwrap();
assert_eq!(v.as_ref(), [1,2,3]);
}

#[test]
fn test_drain() {
let mut v = ArrayVec::from([0; 8]);
Expand Down

0 comments on commit 298575d

Please sign in to comment.