slice_trait/
into_boxed_slice.rs

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