Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion crates/libs/core/src/handles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
///
/// 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 {
pub trait Free : Clone {
/// Calls the handle's free function.
///
/// # Safety
Expand All @@ -24,6 +24,14 @@ impl<T: Free> Owned<T> {
pub unsafe fn new(x: T) -> Self {
Self(x)
}

/// Consumes the `Owned<T>` and relinquishes ownership of the handle.
/// The caller is now responsible for freeing the returned handle.
#[must_use = "losing the handle will leak it"]
pub fn into_raw(o: Self) -> T {
let o = core::mem::ManuallyDrop::new(o);
o.0.clone()
}
}

impl<T: Free> Drop for Owned<T> {
Expand Down
47 changes: 47 additions & 0 deletions crates/tests/libs/core/tests/handles.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use std::cell::Cell;
use std::rc::Rc;

use windows::core::Free;
use windows::core::Owned;

#[derive(Clone)]
struct FreeCounter {
pub count: Rc<Cell<u32>>,
}

impl Free for FreeCounter {
unsafe fn free(&mut self) {
self.count.update(|c| c + 1);
}
}

#[test]
fn into_raw() {
let free_count: Rc<Cell<u32>> = Rc::new(Cell::new(0));
let counter = FreeCounter {
count: free_count.clone(),
};

{
let owned = unsafe { Owned::new(counter) };
let _counter = Owned::into_raw(owned);
assert!(free_count.get() == 0);
}

assert!(free_count.get() == 0);
}

#[test]
fn drop() {
let free_count: Rc<Cell<u32>> = Rc::new(Cell::new(0));
let counter = FreeCounter {
count: free_count.clone(),
};

{
let _owned = unsafe { Owned::new(counter) };
assert!(free_count.get() == 0);
}

assert!(free_count.get() == 1);
}