collenchyma/frameworks/native/
flatbox.rs

1//! Provides a Box without any knowledge of its underlying type.
2
3use memory::*;
4use std::fmt;
5use std::mem;
6use std::slice;
7
8/// A Box without any knowledge of its underlying type.
9pub struct FlatBox {
10    len: usize,
11    raw_box: *mut [u8]
12}
13
14impl FlatBox {
15    /// Create FlatBox from Box, consuming it.
16    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    /// Access memory as slice.
24    ///
25    /// The preffered way to access native memory.
26    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    /// Access memory as mutable slice.
36    ///
37    /// The preffered way to access native memory.
38    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    /// Returns memory size of the Flatbox.
48    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 {}