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