Skip to content

Commit

Permalink
Migrate to windows-rs (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
pronebird authored Feb 27, 2024
1 parent 12e705c commit c521d22
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 27 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
45 changes: 20 additions & 25 deletions src/windows.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
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,
Win32::{
Foundation::{
CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0, WAIT_TIMEOUT,
},
System::Threading::{
CreateMutexW, ReleaseMutex, WaitForSingleObject, INFINITE,
},
},
};

use crate::error::*;

Expand All @@ -19,16 +22,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()) };
let handle = unsafe {
CreateMutexW(None, false, &HSTRING::from(name))
.map_err(|e| Error::CreateFailed(std::io::Error::from(e)))?
};

if handle.is_null() {
Err(Error::CreateFailed(io::Error::last_os_error()))
} else {
Ok(RawNamedLock {
handle,
})
}
Ok(RawNamedLock {
handle,
})
}

pub(crate) fn try_lock(&self) -> Result<()> {
Expand All @@ -54,20 +55,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 c521d22

Please sign in to comment.