Debian Codegraph @

third_party/rust/windows-core/src/handles.rs

raw
1 /// Custom code to free a handle.
2 ///
3 /// This is similar to the [`Drop`] trait, and may be used to implement [`Drop`], but allows handles
4 /// to be dropped depending on context.
5 pub trait Free {
6 /// Calls the handle's free function.
7 ///
8 /// # Safety
9 /// The handle must be owned by the caller and safe to free.
10 unsafe fn free(&mut self);
11 }
12
13 /// A wrapper to provide ownership for handles to automatically drop via the handle's [`Free`] trait.
14 #[repr(transparent)]
15 #[derive(PartialEq, Eq, Default, Debug)]
16 pub struct Owned<T: Free>(T);
17
18 impl<T: Free> Owned<T> {
19 /// Takes ownership of the handle.
20 ///
21 /// # Safety
22 ///
23 /// The handle must be owned by the caller and safe to free.
24 pub unsafe fn new(x: T) -> Self {
25 Self(x)
26 }
27 }
28
29 impl<T: Free> Drop for Owned<T> {
30 fn drop(&mut self) {
31 unsafe { self.0.free() };
32 }
33 }
34
35 impl<T: Free> core::ops::Deref for Owned<T> {
36 type Target = T;
37 fn deref(&self) -> &Self::Target {
38 &self.0
39 }
40 }
41
42 impl<T: Free> core::ops::DerefMut for Owned<T> {
43 fn deref_mut(&mut self) -> &mut Self::Target {
44 &mut self.0
45 }
46 }