fuchsia_sync/
mutex.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use 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
13// See SYNC_MUTEX_INIT in lib/sync/mutex.h
14const 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
26// SAFETY: This trait requires that "[i]mplementations of this trait must ensure
27// that the mutex is actually exclusive: a lock can't be acquired while the mutex
28// is already locked." This guarantee is provided by libsync's APIs.
29unsafe impl lock_api::RawMutex for RawSyncMutex {
30    const INIT: RawSyncMutex = RawSyncMutex(sys::zx_futex_t::new(SYNC_MUTEX_INIT));
31
32    // libsync does not require the lock / unlock operations to happen on the same thread.
33    type GuardMarker = lock_api::GuardSend;
34
35    #[inline]
36    fn lock(&self) {
37        // SAFETY: This call requires we pass a non-null pointer to a valid futex.
38        // This is guaranteed by using `self` through a shared reference.
39        unsafe {
40            sync_mutex_lock(self.as_futex_ptr());
41        }
42    }
43
44    #[inline]
45    fn try_lock(&self) -> bool {
46        // SAFETY: This call requires we pass a non-null pointer to a valid futex.
47        // This is guaranteed by using `self` through a shared reference.
48        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}