Skip to content

Commit bf02360

Browse files
author
Lukas Sandström
committed
Add ArrayVec::leak
1 parent 0e131fd commit bf02360

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/arrayvec.rs

+13
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,19 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
579579
Ok(())
580580
}
581581

582+
/// Leak the contents of the vector and return a reference to them as a mutable slice.
583+
///
584+
/// This sets len() to zero. The elements will not be dropped. The backing memory will
585+
/// not be lost however, as the ArrayVec can be used again as soon as the returned slice
586+
/// is dropped.
587+
pub fn leak(&mut self) -> &mut [T] {
588+
let orig_len = self.len();
589+
unsafe {
590+
self.set_len(0);
591+
slice::from_raw_parts_mut(self.as_mut_ptr(), orig_len)
592+
}
593+
}
594+
582595
/// Create a draining iterator that removes the specified range in the vector
583596
/// and yields the removed items from start to end. The element range is
584597
/// removed even if the iterator is not consumed until the end.

tests/tests.rs

+9
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,15 @@ fn test_still_works_with_option_arrayvec() {
331331
println!("{:?}", array);
332332
}
333333

334+
#[test]
335+
fn test_leak() {
336+
let mut v = ArrayVec::from([1,2,3,4,5,6,7,8]);
337+
assert_eq!(v.leak(), [1,2,3,4,5,6,7,8]);
338+
assert_eq!(v.len(), 0);
339+
v.try_extend_from_slice(&[1,2,3]).unwrap();
340+
assert_eq!(v.as_ref(), [1,2,3]);
341+
}
342+
334343
#[test]
335344
fn test_drain() {
336345
let mut v = ArrayVec::from([0; 8]);

0 commit comments

Comments
 (0)