gemstone/bytes/
box_byte_slice.rs1use super::*;
2use core::mem;
3use core::ops::{Deref, DerefMut};
4use std::alloc::{alloc_zeroed, dealloc, Layout};
5
6#[derive(Clone)]
7pub struct BoxByteSlice(mem::ManuallyDrop<Box<[u8]>>);
8
9impl BoxByteSlice {
10 #[inline]
11 pub fn new_zeroed(len: usize) -> Self {
12 let layout = Layout::from_size_align((len + 7) & !7, 8).unwrap();
13 unsafe {
14 BoxByteSlice(mem::ManuallyDrop::new(Box::from_raw(
15 core::slice::from_raw_parts_mut(alloc_zeroed(layout), len),
16 )))
17 }
18 }
19
20 #[inline]
21 pub fn as_byte_slice(&self) -> ByteSlice {
22 ByteSlice::new(&self[..])
23 }
24
25 #[inline]
26 pub fn as_byte_mut_slice(&mut self) -> ByteMutSlice {
27 ByteMutSlice::new(&mut self[..])
28 }
29}
30
31impl Deref for BoxByteSlice {
32 type Target = [u8];
33 #[inline]
34 fn deref(&self) -> &Self::Target {
35 &self.0
36 }
37}
38
39impl DerefMut for BoxByteSlice {
40 #[inline]
41 fn deref_mut(&mut self) -> &mut Self::Target {
42 &mut self.0
43 }
44}
45
46impl Drop for BoxByteSlice {
47 #[inline]
48 fn drop(&mut self) {
49 let layout = Layout::from_size_align((self.0.len() + 7) & !7, 8).unwrap();
50 unsafe {
51 dealloc(
52 Box::into_raw(mem::ManuallyDrop::take(&mut self.0)) as *mut u8,
53 layout,
54 )
55 }
56 }
57}
58
59impl_byteorder!(BoxByteSlice);