1use zx::sys;
6
7extern "C" {
8 fn sync_mutex_lock(lock: *const sys::zx_futex_t);
9 fn sync_mutex_trylock(lock: *const sys::zx_futex_t) -> sys::zx_status_t;
10 fn sync_mutex_unlock(lock: *const sys::zx_futex_t);
11}
12
13const SYNC_MUTEX_INIT: i32 = 0;
15
16#[repr(transparent)]
17pub struct RawSyncMutex(sys::zx_futex_t);
18
19impl RawSyncMutex {
20 #[inline]
21 fn as_futex_ptr(&self) -> *const sys::zx_futex_t {
22 std::ptr::addr_of!(self.0)
23 }
24}
25
26unsafe impl lock_api::RawMutex for RawSyncMutex {
30 const INIT: RawSyncMutex = RawSyncMutex(sys::zx_futex_t::new(SYNC_MUTEX_INIT));
31
32 type GuardMarker = lock_api::GuardSend;
34
35 #[inline]
36 fn lock(&self) {
37 unsafe {
40 sync_mutex_lock(self.as_futex_ptr());
41 }
42 }
43
44 #[inline]
45 fn try_lock(&self) -> bool {
46 unsafe { sync_mutex_trylock(self.as_futex_ptr()) == sys::ZX_OK }
49 }
50
51 #[inline]
52 unsafe fn unlock(&self) {
53 sync_mutex_unlock(self.as_futex_ptr())
54 }
55}
56
57pub type Mutex<T> = lock_api::Mutex<RawSyncMutex, T>;
58pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawSyncMutex, T>;
59pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawSyncMutex, T>;
60
61#[cfg(test)]
62mod test {
63 use super::*;
64
65 #[test]
66 fn test_lock_and_unlock() {
67 let value = Mutex::<u32>::new(5);
68 let mut guard = value.lock();
69 assert_eq!(*guard, 5);
70 *guard = 6;
71 assert_eq!(*guard, 6);
72 std::mem::drop(guard);
73 }
74
75 #[test]
76 fn test_try_lock() {
77 let value = Mutex::<u32>::new(5);
78 let _guard = value.lock();
79 assert!(value.try_lock().is_none());
80 }
81}