Skip to main content

diskann_platform/win/
thread_safe_handle.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6use std::{
7    io,
8    sync::{Mutex, MutexGuard},
9};
10
11use windows_sys::Win32::Foundation::HANDLE;
12
13/// `ThreadSafeHandle` struct that wraps a native Windows `HANDLE` object with a mutex to ensure thread safety.
14pub struct ThreadSafeHandle(Mutex<HANDLE>);
15
16/// Implement `Send` and `Sync` for `ThreadSafeHandle` to allow it to be shared across threads.
17unsafe impl Send for ThreadSafeHandle {}
18unsafe impl Sync for ThreadSafeHandle {}
19
20impl ThreadSafeHandle {
21    /// Lock the mutex and return a guard to the handle.
22    pub fn lock(&self) -> io::Result<MutexGuard<'_, HANDLE>> {
23        self.0.lock().map_err(|_| {
24            io::Error::new(
25                io::ErrorKind::WouldBlock,
26                "Unable to acquire lock on ThreadSafeHandle.",
27            )
28        })
29    }
30
31    /// Create a new `ThreadSafeHandle` from a native Windows `HANDLE`.
32    pub fn new(handle: HANDLE) -> Self {
33        Self(Mutex::new(handle))
34    }
35}