| 1 |
use std::fmt; |
| 2 |
|
| 3 |
pub struct AutoRelease<T> { |
| 4 |
ptr: *mut T, |
| 5 |
release_func: unsafe extern "C" fn(*mut T), |
| 6 |
} |
| 7 |
|
| 8 |
impl<T> AutoRelease<T> { |
| 9 |
pub fn new(ptr: *mut T, release_func: unsafe extern "C" fn(*mut T)) -> Self { |
| 10 |
Self { ptr, release_func } |
| 11 |
} |
| 12 |
|
| 13 |
pub fn reset(&mut self, ptr: *mut T) { |
| 14 |
self.release(); |
| 15 |
self.ptr = ptr; |
| 16 |
} |
| 17 |
|
| 18 |
pub fn as_ref(&self) -> &T { |
| 19 |
assert!(!self.ptr.is_null()); |
| 20 |
unsafe { &*self.ptr } |
| 21 |
} |
| 22 |
|
| 23 |
pub fn as_mut(&mut self) -> &mut T { |
| 24 |
assert!(!self.ptr.is_null()); |
| 25 |
unsafe { &mut *self.ptr } |
| 26 |
} |
| 27 |
|
| 28 |
pub fn as_ptr(&self) -> *const T { |
| 29 |
self.ptr |
| 30 |
} |
| 31 |
|
| 32 |
fn release(&self) { |
| 33 |
if !self.ptr.is_null() { |
| 34 |
unsafe { |
| 35 |
(self.release_func)(self.ptr); |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
impl<T> Drop for AutoRelease<T> { |
| 42 |
fn drop(&mut self) { |
| 43 |
self.release(); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
// Explicit Debug impl to work for the type T |
| 48 |
// that doesn't implement Debug trait. |
| 49 |
impl<T> fmt::Debug for AutoRelease<T> { |
| 50 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 51 |
f.debug_struct("AutoRelease") |
| 52 |
.field("ptr", &self.ptr) |
| 53 |
.field("release_func", &self.release_func) |
| 54 |
.finish() |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
#[test] |
| 59 |
fn test_auto_release() { |
| 60 |
use std::mem; |
| 61 |
use std::ptr; |
| 62 |
|
| 63 |
unsafe extern "C" fn allocate() -> *mut libc::c_void { |
| 64 |
// println!("Allocate!"); |
| 65 |
libc::calloc(1, mem::size_of::<u32>()) |
| 66 |
} |
| 67 |
|
| 68 |
unsafe extern "C" fn deallocate(ptr: *mut libc::c_void) { |
| 69 |
// println!("Deallocate!"); |
| 70 |
libc::free(ptr); |
| 71 |
} |
| 72 |
|
| 73 |
let mut auto_release = AutoRelease::new(ptr::null_mut(), deallocate); |
| 74 |
let ptr = unsafe { allocate() }; |
| 75 |
auto_release.reset(ptr); |
| 76 |
assert_eq!(auto_release.as_ptr(), ptr); |
| 77 |
} |