leveldb/database/
bytes.rs1use std::slice;
2
3pub struct Bytes {
8 bytes: &'static mut u8,
11 size: usize,
12 _marker: ::std::marker::PhantomData<u8>,
14}
15
16impl Bytes {
17 pub unsafe fn from_raw(ptr: *mut u8, size: usize) -> Option<Self> {
23 if ptr.is_null() {
24 None
25 } else {
26 Some(Bytes {
27 bytes: &mut *ptr,
28 size,
29 _marker: Default::default(),
30 })
31 }
32 }
33
34 pub unsafe fn from_raw_unchecked(ptr: *mut u8, size: usize) -> Self {
38 Bytes {
39 bytes: &mut *ptr,
40 size,
41 _marker: Default::default(),
42 }
43 }
44}
45
46impl Drop for Bytes {
47 fn drop(&mut self) {
48 unsafe {
49 use libc::c_void;
50
51 cruzbit_leveldb_sys::leveldb_free(self.bytes as *mut u8 as *mut c_void);
52 }
53 }
54}
55
56impl std::ops::Deref for Bytes {
57 type Target = [u8];
58
59 fn deref(&self) -> &Self::Target {
60 unsafe { slice::from_raw_parts(self.bytes, self.size) }
61 }
62}
63
64impl std::ops::DerefMut for Bytes {
65 fn deref_mut(&mut self) -> &mut Self::Target {
66 unsafe { slice::from_raw_parts_mut(self.bytes as *mut u8, self.size) }
67 }
68}
69
70impl std::borrow::Borrow<[u8]> for Bytes {
71 fn borrow(&self) -> &[u8] {
72 self
73 }
74}
75
76impl std::borrow::BorrowMut<[u8]> for Bytes {
77 fn borrow_mut(&mut self) -> &mut [u8] {
78 &mut *self
79 }
80}
81
82impl AsRef<[u8]> for Bytes {
83 fn as_ref(&self) -> &[u8] {
84 self
85 }
86}
87
88impl AsMut<[u8]> for Bytes {
89 fn as_mut(&mut self) -> &mut [u8] {
90 &mut *self
91 }
92}
93
94impl From<Bytes> for Vec<u8> {
95 fn from(bytes: Bytes) -> Self {
96 bytes.as_ref().to_owned()
97 }
98}
99
100impl From<Bytes> for Box<[u8]> {
101 fn from(bytes: Bytes) -> Self {
102 bytes.as_ref().to_owned().into_boxed_slice()
103 }
104}