diff --git a/src/arrayvec.rs b/src/arrayvec.rs index a21bbb3..a3b3e11 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -579,6 +579,19 @@ impl ArrayVec { Ok(()) } + /// Leak the contents of the vector and return a reference to them as 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] { + let orig_len = self.len(); + unsafe { + self.set_len(0); + slice::from_raw_parts_mut(self.as_mut_ptr(), orig_len) + } + } + /// 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. diff --git a/tests/tests.rs b/tests/tests.rs index 2f8a5ef..1e4de0f 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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]);