libdb/dbt.rs
1use std::slice;
2use std::ops::Deref;
3use libc;
4use libc::c_void;
5use std::fmt;
6
7use libdb_sys::ffi;
8
9pub enum DBT<'a> {
10 Owned(&'a [u8]),
11 Ptr(ffi::DBT),
12}
13
14// impl<'a> DBT<'a> {
15
16// fn as_bytes(&self) -> [u8] {
17// *self
18// }
19// }
20
21impl<'a> DBT<'a> {
22
23 pub fn as_slice(&self) -> &[u8] {
24 match self {
25 &DBT::Owned(s) => s,
26 &DBT::Ptr(ptr) => unsafe { slice::from_raw_parts(ptr.data as *const u8, ptr.size as usize) }
27 }
28 }
29}
30
31impl<'a> fmt::Debug for DBT<'a> {
32 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33 write!(f, "{:?}", self.as_slice())
34 }
35}
36
37impl<'a> Drop for DBT<'a> {
38 fn drop(&mut self) {
39 if let &mut DBT::Ptr(ptr) = self {
40 unsafe { libc::free(ptr.data as *mut c_void); }
41 }
42 }
43}
44
45impl<'a> Deref for DBT<'a> {
46 type Target = [u8];
47
48 fn deref(&self) -> &[u8] {
49 self.as_slice()
50 }
51}
52
53impl<'a> From<ffi::DBT> for DBT<'a> {
54 fn from(ptr: ffi::DBT) -> Self {
55 DBT::Ptr(ptr)
56 }
57}
58
59
60
61// / A database thang
62// /
63// /
64// pub struct DBT<'a> {
65// /// Pointer to the data.
66// data: *mut u8,
67
68// // Length of the data.
69// size: u32,
70
71// // Length of a user-supplied buffer.
72// ulen: u32,
73
74// // dlen and doff are used by BDB for partial reads/updates
75// dlen: u32,
76// doff: u32,
77// }
78
79// impl DBT {
80
81// pub fn from_raw_parts(data: *mut u8, len: u32) -> DBT {
82// DBT {
83// data: data,
84// size: len,
85// ulen: len,
86// dlen: 0,
87// doff: 0,
88// }
89// }
90
91// pub fn len(&self) -> u32 {
92// self.size
93// }
94
95// pub fn as_mut_ptr(&mut self) -> *mut u8 {
96// self.data
97// }
98// }
99
100// impl From<&mut [u8]> for DBT {
101// fn from(data: &mut [u8]) -> Self {
102
103// }
104// }
105
106// impl Deref for DBT {
107// type Target = [u8];
108
109// fn deref(&self) -> &[u8] {
110// unsafe { slice::from_raw_parts(self.data, self.size as usize) }
111// }
112// }
113
114// impl Drop for DBT {
115// fn drop(&mut self) {
116// unsafe {
117// libc::free(self.data as *mut c_void);
118// }
119// }
120// }