Skip to content

Commit bd10be5

Browse files
committed
Add Vec::leak
1 parent 8ebd67e commit bd10be5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/liballoc/vec.rs

+32
Original file line numberDiff line numberDiff line change
@@ -1367,6 +1367,38 @@ impl<T> Vec<T> {
13671367
self.truncate(new_len);
13681368
}
13691369
}
1370+
1371+
/// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1372+
/// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1373+
/// `'a`. If the type has only static references, or none at all, then this
1374+
/// may be chosen to be `'static`.
1375+
///
1376+
/// This function is similar to the `leak` function on `Box`.
1377+
///
1378+
/// This function is mainly useful for data that lives for the remainder of
1379+
/// the program's life. Dropping the returned reference will cause a memory
1380+
/// leak.
1381+
///
1382+
/// # Examples
1383+
///
1384+
/// Simple usage:
1385+
///
1386+
/// ```
1387+
/// fn main() {
1388+
/// let x = vec![1, 2, 3];
1389+
/// let static_ref: &'static mut [usize] = Vec::leak(x);
1390+
/// static_ref[0] += 1;
1391+
/// assert_eq!(static_ref, &[2, 2, 3]);
1392+
/// }
1393+
/// ```
1394+
#[unstable(feature = "vec_leak", issue = "62195")]
1395+
#[inline]
1396+
pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1397+
where
1398+
T: 'a // Technically not needed, but kept to be explicit.
1399+
{
1400+
Box::leak(vec.into_boxed_slice())
1401+
}
13701402
}
13711403

13721404
impl<T: Clone> Vec<T> {

0 commit comments

Comments
 (0)