-
Notifications
You must be signed in to change notification settings - Fork 467
/
handles.rs
45 lines (40 loc) · 1.12 KB
/
handles.rs
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
/// Custom code to free a handle.
///
/// This is similar to the `Drop` trait, and may be used to implement `Drop`, but allows handles
/// to be dropped depending on context.
pub trait Free {
/// Calls the handle's free function.
///
/// # Safety
/// The handle must be owned by the caller and safe to free.
unsafe fn free(&mut self);
}
/// A wrapper to provide ownership for handles to automatically drop via the handle's `Free` trait.
#[repr(transparent)]
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct Owned<T: Free>(T);
impl<T: Free> Owned<T> {
/// Takes ownership of the handle.
///
/// # Safety
/// The handle must be owned by the caller and safe to free.
pub unsafe fn new(x: T) -> Self {
Self(x)
}
}
impl<T: Free> Drop for Owned<T> {
fn drop(&mut self) {
unsafe { self.0.free() };
}
}
impl<T: Free> std::ops::Deref for Owned<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: Free> std::ops::DerefMut for Owned<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}