collenchyma/frameworks/native/
flatbox.rs1use memory::*;
4use std::fmt;
5use std::mem;
6use std::slice;
7
8pub struct FlatBox {
10 len: usize,
11 raw_box: *mut [u8]
12}
13
14impl FlatBox {
15 pub fn from_box(b: Box<[u8]>) -> FlatBox {
17 FlatBox {
18 len: b.len(),
19 raw_box: Box::into_raw(b)
20 }
21 }
22
23 pub fn as_slice<T>(&self) -> &[T] {
27 unsafe {
28 slice::from_raw_parts_mut(
29 self.raw_box as *mut T,
30 self.len / mem::size_of::<T>()
31 )
32 }
33 }
34
35 pub fn as_mut_slice<T>(&mut self) -> &mut [T] {
39 unsafe {
40 slice::from_raw_parts_mut(
41 self.raw_box as *mut T,
42 self.len / mem::size_of::<T>()
43 )
44 }
45 }
46
47 pub fn byte_size(&self) -> usize {
49 self.len
50 }
51}
52
53impl Drop for FlatBox {
54 fn drop(&mut self) {
55 unsafe {
56 Box::from_raw(self.raw_box);
57 }
58 }
59}
60
61impl fmt::Debug for FlatBox {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 write!(f, "FlatBox of length {}", &self.len)
64 }
65}
66
67impl IMemory for FlatBox {}