1use crate::raw_mutex::RawMutex;
9use core::num::NonZeroUsize;
10use lock_api::{self, GetThreadId};
11
12pub struct RawThreadId;
14
15unsafe impl GetThreadId for RawThreadId {
16 const INIT: RawThreadId = RawThreadId;
17
18 fn nonzero_thread_id(&self) -> NonZeroUsize {
19 thread_local!(static KEY: u8 = 0);
23 KEY.with(|x| {
24 NonZeroUsize::new(x as *const _ as usize)
25 .expect("thread-local variable address is null")
26 })
27 }
28}
29
30pub type ReentrantMutex<T> = lock_api::ReentrantMutex<RawMutex, RawThreadId, T>;
42
43pub const fn const_reentrant_mutex<T>(val: T) -> ReentrantMutex<T> {
47 ReentrantMutex::const_new(
48 <RawMutex as lock_api::RawMutex>::INIT,
49 <RawThreadId as lock_api::GetThreadId>::INIT,
50 val,
51 )
52}
53
54pub type ReentrantMutexGuard<'a, T> = lock_api::ReentrantMutexGuard<'a, RawMutex, RawThreadId, T>;
60
61pub type MappedReentrantMutexGuard<'a, T> =
69 lock_api::MappedReentrantMutexGuard<'a, RawMutex, RawThreadId, T>;
70
71#[cfg(test)]
72mod tests {
73 use crate::ReentrantMutex;
74 use std::cell::RefCell;
75 use std::sync::Arc;
76 use std::thread;
77
78 #[cfg(feature = "serde")]
79 use bincode::{deserialize, serialize};
80
81 #[test]
82 fn smoke() {
83 let m = ReentrantMutex::new(2);
84 {
85 let a = m.lock();
86 {
87 let b = m.lock();
88 {
89 let c = m.lock();
90 assert_eq!(*c, 2);
91 }
92 assert_eq!(*b, 2);
93 }
94 assert_eq!(*a, 2);
95 }
96 }
97
98 #[test]
99 fn is_mutex() {
100 let m = Arc::new(ReentrantMutex::new(RefCell::new(0)));
101 let m2 = m.clone();
102 let lock = m.lock();
103 let child = thread::spawn(move || {
104 let lock = m2.lock();
105 assert_eq!(*lock.borrow(), 4950);
106 });
107 for i in 0..100 {
108 let lock = m.lock();
109 *lock.borrow_mut() += i;
110 }
111 drop(lock);
112 child.join().unwrap();
113 }
114
115 #[test]
116 fn trylock_works() {
117 let m = Arc::new(ReentrantMutex::new(()));
118 let m2 = m.clone();
119 let _lock = m.try_lock();
120 let _lock2 = m.try_lock();
121 thread::spawn(move || {
122 let lock = m2.try_lock();
123 assert!(lock.is_none());
124 })
125 .join()
126 .unwrap();
127 let _lock3 = m.try_lock();
128 }
129
130 #[test]
131 fn test_reentrant_mutex_debug() {
132 let mutex = ReentrantMutex::new(vec![0u8, 10]);
133
134 assert_eq!(format!("{:?}", mutex), "ReentrantMutex { data: [0, 10] }");
135 }
136
137 #[cfg(feature = "serde")]
138 #[test]
139 fn test_serde() {
140 let contents: Vec<u8> = vec![0, 1, 2];
141 let mutex = ReentrantMutex::new(contents.clone());
142
143 let serialized = serialize(&mutex).unwrap();
144 let deserialized: ReentrantMutex<Vec<u8>> = deserialize(&serialized).unwrap();
145
146 assert_eq!(*(mutex.lock()), *(deserialized.lock()));
147 assert_eq!(contents, *(deserialized.lock()));
148 }
149}