Skip to content

Commit

Permalink
Migrate to windows-rs
Browse files Browse the repository at this point in the history
  • Loading branch information
pronebird authored and Andrej Mihajlov committed Feb 27, 2024
1 parent 12e705c commit a2dc494
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 28 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ thiserror = "1.0.35"
libc = "0.2.132"

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.9", features = ["handleapi", "synchapi", "winbase", "winnt", "winerror"] }
widestring = "1.0.2"
windows = { version = "0.53", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Threading"] }

[dev-dependencies]
static_assertions = "1.1.0"
Expand Down
42 changes: 16 additions & 26 deletions src/windows.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::io;
use std::ptr;
use widestring::WideCString;
use winapi::shared::winerror::WAIT_TIMEOUT;
use winapi::um::handleapi::CloseHandle;
use winapi::um::synchapi::{CreateMutexW, ReleaseMutex, WaitForSingleObject};
use winapi::um::winbase::{INFINITE, WAIT_ABANDONED, WAIT_OBJECT_0};
use winapi::um::winnt::HANDLE;
use windows::core::HSTRING;
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_TIMEOUT};
use windows::Win32::Foundation::{WAIT_ABANDONED, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{
CreateMutexW, ReleaseMutex, WaitForSingleObject, INFINITE,
};

use crate::error::*;

Expand All @@ -19,16 +17,14 @@ unsafe impl Send for RawNamedLock {}

impl RawNamedLock {
pub(crate) fn create(name: &str) -> Result<RawNamedLock> {
let name = WideCString::from_str(name).unwrap();
let handle = unsafe { CreateMutexW(ptr::null_mut(), 0, name.as_ptr()) };

if handle.is_null() {
Err(Error::CreateFailed(io::Error::last_os_error()))
} else {
Ok(RawNamedLock {
handle,
})
}
let handle = unsafe {
CreateMutexW(None, false, &HSTRING::from(name))
.map_err(|e| Error::CreateFailed(std::io::Error::from(e)))?
};

Ok(RawNamedLock {
handle,
})
}

pub(crate) fn try_lock(&self) -> Result<()> {
Expand All @@ -54,20 +50,14 @@ impl RawNamedLock {
}

pub(crate) fn unlock(&self) -> Result<()> {
let rc = unsafe { ReleaseMutex(self.handle) };

if rc == 0 {
Err(Error::UnlockFailed)
} else {
Ok(())
}
unsafe { ReleaseMutex(self.handle).map_err(|_| Error::UnlockFailed) }
}
}

impl Drop for RawNamedLock {
fn drop(&mut self) {
unsafe {
CloseHandle(self.handle);
let _ = CloseHandle(self.handle);
}
}
}

0 comments on commit a2dc494

Please sign in to comment.