Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_platform/src/sync/mutex.rs
6849 views
1
//! Provides `Mutex` and `MutexGuard`
2
3
pub use implementation::{Mutex, MutexGuard};
4
5
#[cfg(feature = "std")]
6
use std::sync as implementation;
7
8
#[cfg(not(feature = "std"))]
9
mod implementation {
10
use crate::sync::{LockResult, TryLockError, TryLockResult};
11
use core::fmt;
12
13
pub use spin::MutexGuard;
14
15
/// Fallback implementation of `Mutex` from the standard library.
16
pub struct Mutex<T: ?Sized> {
17
inner: spin::Mutex<T>,
18
}
19
20
impl<T> Mutex<T> {
21
/// Creates a new mutex in an unlocked state ready for use.
22
///
23
/// See the standard library for further details.
24
pub const fn new(t: T) -> Self {
25
Self {
26
inner: spin::Mutex::new(t),
27
}
28
}
29
}
30
31
impl<T: ?Sized> Mutex<T> {
32
/// Acquires a mutex, blocking the current thread until it is able to do so.
33
///
34
/// See the standard library for further details.
35
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
36
Ok(self.inner.lock())
37
}
38
39
/// Attempts to acquire this lock.
40
///
41
/// See the standard library for further details.
42
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
43
self.inner.try_lock().ok_or(TryLockError::WouldBlock)
44
}
45
46
/// Determines whether the mutex is poisoned.
47
///
48
/// See the standard library for further details.
49
pub fn is_poisoned(&self) -> bool {
50
false
51
}
52
53
/// Clear the poisoned state from a mutex.
54
///
55
/// See the standard library for further details.
56
pub fn clear_poison(&self) {
57
// no-op
58
}
59
60
/// Consumes this mutex, returning the underlying data.
61
///
62
/// See the standard library for further details.
63
pub fn into_inner(self) -> LockResult<T>
64
where
65
T: Sized,
66
{
67
Ok(self.inner.into_inner())
68
}
69
70
/// Returns a mutable reference to the underlying data.
71
///
72
/// See the standard library for further details.
73
pub fn get_mut(&mut self) -> LockResult<&mut T> {
74
Ok(self.inner.get_mut())
75
}
76
}
77
78
impl<T> From<T> for Mutex<T> {
79
fn from(t: T) -> Self {
80
Mutex::new(t)
81
}
82
}
83
84
impl<T: Default> Default for Mutex<T> {
85
fn default() -> Mutex<T> {
86
Mutex::new(Default::default())
87
}
88
}
89
90
impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
91
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92
let mut d = f.debug_struct("Mutex");
93
match self.try_lock() {
94
Ok(guard) => {
95
d.field("data", &&*guard);
96
}
97
Err(TryLockError::Poisoned(err)) => {
98
d.field("data", &&**err.get_ref());
99
}
100
Err(TryLockError::WouldBlock) => {
101
d.field("data", &format_args!("<locked>"));
102
}
103
}
104
d.field("poisoned", &false);
105
d.finish_non_exhaustive()
106
}
107
}
108
}
109
110