| 1 |
extern crate libc; |
| 2 |
|
| 3 |
use std::marker::PhantomData; |
| 4 |
use std::ops::Deref; |
| 5 |
use std::slice; |
| 6 |
use libc::c_void; |
| 7 |
|
| 8 |
struct MallocPtr(*mut c_void); |
| 9 |
|
| 10 |
impl Drop for MallocPtr { |
| 11 |
fn drop(&mut self) { |
| 12 |
unsafe { |
| 13 |
libc::free(self.0); |
| 14 |
} |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
/// A type that represents a `malloc`'d chunk of memory. |
| 19 |
pub struct MallocBuffer<T> { |
| 20 |
ptr: MallocPtr, |
| 21 |
len: usize, |
| 22 |
items: PhantomData<[T]>, |
| 23 |
} |
| 24 |
|
| 25 |
impl<T: Copy> MallocBuffer<T> { |
| 26 |
/// Constructs a new `MallocBuffer` for a `malloc`'d buffer |
| 27 |
/// with the given length at the given pointer. |
| 28 |
/// Returns `None` if the given pointer is null and the length is not 0. |
| 29 |
/// |
| 30 |
/// When this `MallocBuffer` drops, the buffer will be `free`'d. |
| 31 |
/// |
| 32 |
/// Unsafe because there must be `len` contiguous, valid instances of `T` |
| 33 |
/// at `ptr`. |
| 34 |
pub unsafe fn new(ptr: *mut T, len: usize) -> Option<MallocBuffer<T>> { |
| 35 |
if len > 0 && ptr.is_null() { |
| 36 |
None |
| 37 |
} else { |
| 38 |
Some(MallocBuffer { |
| 39 |
ptr: MallocPtr(ptr as *mut c_void), |
| 40 |
len: len, |
| 41 |
items: PhantomData, |
| 42 |
}) |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
impl<T> Deref for MallocBuffer<T> { |
| 48 |
type Target = [T]; |
| 49 |
|
| 50 |
fn deref(&self) -> &[T] { |
| 51 |
let ptr = if self.len == 0 && self.ptr.0.is_null() { |
| 52 |
// Even a 0-size slice cannot be null, so just use another pointer |
| 53 |
0x1 as *const T |
| 54 |
} else { |
| 55 |
self.ptr.0 as *const T |
| 56 |
}; |
| 57 |
unsafe { |
| 58 |
slice::from_raw_parts(ptr, self.len) |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
#[cfg(test)] |
| 64 |
mod tests { |
| 65 |
use std::ptr; |
| 66 |
use libc; |
| 67 |
|
| 68 |
use super::MallocBuffer; |
| 69 |
|
| 70 |
#[test] |
| 71 |
fn test_null_buf() { |
| 72 |
let buf = unsafe { |
| 73 |
MallocBuffer::<u32>::new(ptr::null_mut(), 0).unwrap() |
| 74 |
}; |
| 75 |
assert!(&*buf == []); |
| 76 |
assert!(Some(&*buf) == Some(&[])); |
| 77 |
|
| 78 |
let buf = unsafe { |
| 79 |
MallocBuffer::<u32>::new(ptr::null_mut(), 7) |
| 80 |
}; |
| 81 |
assert!(buf.is_none()); |
| 82 |
} |
| 83 |
|
| 84 |
#[test] |
| 85 |
fn test_buf() { |
| 86 |
let buf = unsafe { |
| 87 |
let ptr = libc::malloc(12) as *mut u32; |
| 88 |
*ptr = 1; |
| 89 |
*ptr.offset(1) = 2; |
| 90 |
*ptr.offset(2) = 3; |
| 91 |
MallocBuffer::new(ptr, 3).unwrap() |
| 92 |
}; |
| 93 |
assert!(&*buf == [1, 2, 3]); |
| 94 |
} |
| 95 |
} |