slice_trait/
into_boxed_slice.rs1use crate::AsSlice;
2
3use alloc::{boxed::Box, vec::Vec, alloc::Global};
4
5pub const trait IntoBoxedSlice: ~const AsSlice + Sized
7{
8 fn into_boxed_slice(self) -> Box<[Self::Elem]>;
10}
11
12impl<T, const N: usize> IntoBoxedSlice for [T; N]
13{
14 fn into_boxed_slice(self) -> Box<[Self::Elem]>
15 {
16 let mut boxed = Box::new_in(self, Global);
17 let ptr = boxed.as_mut_ptr();
18 core::mem::forget(boxed);
19 unsafe {
20 Box::from_raw_in(core::ptr::from_raw_parts_mut(ptr, N), Global)
21 }
22 }
23}
24
25impl<T> const IntoBoxedSlice for Box<[T]>
26{
27 fn into_boxed_slice(self) -> Box<[Self::Elem]>
28 {
29 self
30 }
31}
32
33impl<T> IntoBoxedSlice for Vec<T>
34{
35 fn into_boxed_slice(mut self) -> Box<[Self::Elem]>
36 {
37 self.shrink_to_fit();
38
39 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
40 assert_eq!(len, cap, "Memory leak detected");
41
42 unsafe {
43 Box::from_raw_in(core::ptr::from_raw_parts_mut(ptr, len), alloc)
44 }
45 }
46}