Skip to main content

asyncband/mutex/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18// Portions of the owned and mapped guard APIs originated from Tokio 1.41.0's Mutex implementation.
19// Copyright (c) Tokio Contributors
20// The Tokio-derived portions remain licensed under the MIT License.
21// Asyncband independently built the mutex on its own semaphore and substantially changed the
22// incorporated guard implementation: the try-lock error type and support for closing the semaphore
23// are absent, projected guards use NonNull pointers with explicit invariance, and projected guards
24// can be mapped repeatedly in both borrowed and owned forms.
25// Upstream source:
26// https://github.com/tokio-rs/tokio/blob/01e04daaa162ce6122bb894fdda0b6803dd32093/tokio/src/sync/mutex.rs
27
28//! Mutual exclusion that yields the current task while waiting.
29//!
30//! A successful lock operation returns a guard that provides exclusive access to the protected
31//! value and releases the lock when dropped. The guard may be held across `.await` points. When
32//! that is unnecessary, a synchronous mutex is usually cheaper.
33//!
34//! Lock requests complete in the order they begin waiting. Cancelling a pending request loses its
35//! place, so a later attempt waits behind requests already in progress. A panic while holding a
36//! guard releases the lock without poisoning it.
37//!
38//! # Examples
39//!
40//! ```
41//! # #[tokio::main]
42//! # async fn main() {
43//! use std::sync::Arc;
44//!
45//! use asyncband::mutex::Mutex;
46//!
47//! let counter = Arc::new(Mutex::new(0));
48//! let mut tasks = vec![];
49//!
50//! for _ in 0..3 {
51//!     let counter = counter.clone();
52//!     tasks.push(tokio::spawn(async move {
53//!         *counter.lock().await += 1;
54//!     }));
55//! }
56//!
57//! for task in tasks {
58//!     task.await.unwrap();
59//! }
60//!
61//! assert_eq!(*counter.lock().await, 3);
62//!
63//! # }
64//! ```
65
66use std::cell::UnsafeCell;
67use std::fmt;
68use std::marker::PhantomData;
69use std::mem::ManuallyDrop;
70use std::ops::Deref;
71use std::ops::DerefMut;
72use std::ptr;
73use std::ptr::NonNull;
74use std::sync::Arc;
75
76use crate::internal::semaphore;
77
78/// An asynchronous mutex that grants exclusive access in request order.
79///
80/// See the [module level documentation](self) for more.
81pub struct Mutex<T: ?Sized> {
82    s: semaphore::Semaphore,
83    c: UnsafeCell<T>,
84}
85
86unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
87unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
88
89impl<T> From<T> for Mutex<T> {
90    fn from(t: T) -> Self {
91        Self::new(t)
92    }
93}
94
95impl<T: Default> Default for Mutex<T> {
96    fn default() -> Self {
97        Self::new(T::default())
98    }
99}
100
101impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        let mut d = f.debug_struct("Mutex");
104        match self.try_lock() {
105            Some(inner) => d.field("data", &&*inner),
106            None => d.field("data", &format_args!("<locked>")),
107        };
108        d.finish()
109    }
110}
111
112impl<T> Mutex<T> {
113    /// Wraps `t` in an unlocked mutex.
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// use asyncband::mutex::Mutex;
119    ///
120    /// let mutex = Mutex::new(5);
121    /// ```
122    pub const fn new(t: T) -> Self {
123        let s = semaphore::Semaphore::new(1);
124        let c = UnsafeCell::new(t);
125        Self { s, c }
126    }
127
128    /// Unwraps the protected value.
129    ///
130    /// # Examples
131    ///
132    /// ```
133    /// use asyncband::mutex::Mutex;
134    ///
135    /// let mutex = Mutex::new(1);
136    /// let n = mutex.into_inner();
137    /// assert_eq!(n, 1);
138    /// ```
139    pub fn into_inner(self) -> T {
140        self.c.into_inner()
141    }
142}
143
144impl<T: ?Sized> Mutex<T> {
145    /// Waits for exclusive access and returns a borrowed guard.
146    ///
147    /// # Cancel safety
148    ///
149    /// Pending lock requests complete in order. Cancelling this call loses its place among them.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// # #[tokio::main]
155    /// # async fn main() {
156    /// use asyncband::mutex::Mutex;
157    ///
158    /// let mutex = Mutex::new(1);
159    ///
160    /// let mut n = mutex.lock().await;
161    /// *n = 2;
162    /// # }
163    /// ```
164    pub async fn lock(&self) -> MutexGuard<'_, T> {
165        self.s.acquire(1).await;
166        MutexGuard { lock: self }
167    }
168
169    /// Acquires the mutex without waiting, or returns `None` when it is already held.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use asyncband::mutex::Mutex;
175    ///
176    /// let mutex = Mutex::new(1);
177    /// let mut guard = mutex.try_lock().expect("mutex is locked");
178    /// *guard += 1;
179    /// assert_eq!(2, *guard);
180    /// ```
181    pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
182        if self.s.try_acquire(1) {
183            let guard = MutexGuard { lock: self };
184            Some(guard)
185        } else {
186            None
187        }
188    }
189
190    /// Waits for exclusive access and returns a guard that owns this [`Arc`].
191    ///
192    /// The owned guard keeps the mutex alive instead of borrowing it, which allows the guard to be
193    /// moved wherever a `'static` value is required.
194    ///
195    /// # Cancel safety
196    ///
197    /// Pending lock requests complete in order. Cancelling this call loses its place among them.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// # #[tokio::main]
203    /// # async fn main() {
204    /// use std::sync::Arc;
205    ///
206    /// use asyncband::mutex::Mutex;
207    ///
208    /// let mutex = Arc::new(Mutex::new(1));
209    ///
210    /// let mut n = mutex.clone().lock_owned().await;
211    /// *n = 2;
212    /// # }
213    /// ```
214    pub async fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T> {
215        self.s.acquire(1).await;
216        OwnedMutexGuard { lock: self }
217    }
218
219    /// Acquires the mutex without waiting and returns a guard that owns this [`Arc`].
220    ///
221    /// Returns `None` when another guard currently holds the mutex.
222    ///
223    /// # Examples
224    ///
225    /// ```
226    /// use std::sync::Arc;
227    ///
228    /// use asyncband::mutex::Mutex;
229    ///
230    /// let mutex = Arc::new(Mutex::new(1));
231    /// let mut guard = mutex.clone().try_lock_owned().expect("mutex is locked");
232    /// *guard += 1;
233    /// assert_eq!(2, *guard);
234    /// ```
235    pub fn try_lock_owned(self: Arc<Self>) -> Option<OwnedMutexGuard<T>> {
236        if self.s.try_acquire(1) {
237            let guard = OwnedMutexGuard { lock: self };
238            Some(guard)
239        } else {
240            None
241        }
242    }
243
244    /// Borrows the protected value mutably without locking.
245    ///
246    /// The exclusive borrow of the mutex already prevents any guard from existing at the same
247    /// time.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// use asyncband::mutex::Mutex;
253    ///
254    /// let mut mutex = Mutex::new(1);
255    /// let n = mutex.get_mut();
256    /// *n = 2;
257    /// ```
258    pub fn get_mut(&mut self) -> &mut T {
259        self.c.get_mut()
260    }
261}
262
263/// A borrowed proof of exclusive access to a [`Mutex`].
264///
265/// [`Mutex::lock`] and [`Mutex::try_lock`] create this guard. It dereferences to the protected
266/// value and releases the lock when dropped.
267#[must_use = "dropping the guard releases the mutex immediately"]
268pub struct MutexGuard<'a, T: ?Sized> {
269    lock: &'a Mutex<T>,
270}
271
272#[cfg(feature = "condvar")]
273pub(crate) fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a Mutex<T> {
274    guard.lock
275}
276
277unsafe impl<T: ?Sized + Send + Sync> Sync for MutexGuard<'_, T> {}
278
279impl<T: ?Sized> Drop for MutexGuard<'_, T> {
280    fn drop(&mut self) {
281        self.lock.s.release_with_lock(1);
282    }
283}
284
285impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        fmt::Debug::fmt(&**self, f)
288    }
289}
290
291impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        fmt::Display::fmt(&**self, f)
294    }
295}
296
297impl<T: ?Sized> Deref for MutexGuard<'_, T> {
298    type Target = T;
299    fn deref(&self) -> &Self::Target {
300        unsafe { &*self.lock.c.get() }
301    }
302}
303
304impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
305    fn deref_mut(&mut self) -> &mut Self::Target {
306        unsafe { &mut *self.lock.c.get() }
307    }
308}
309
310impl<'a, T: ?Sized> MutexGuard<'a, T> {
311    /// Projects this guard to a mutable component of the protected value.
312    ///
313    /// The returned guard keeps the same mutex locked. Call this as
314    /// `MutexGuard::map(...)` so a method named `map` on `T` remains accessible through deref.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// # #[tokio::main]
320    /// # async fn main() {
321    /// use asyncband::mutex::Mutex;
322    /// use asyncband::mutex::MutexGuard;
323    ///
324    /// #[derive(Debug)]
325    /// struct User {
326    ///     id: u32,
327    ///     profile: UserProfile,
328    /// }
329    ///
330    /// #[derive(Debug)]
331    /// struct UserProfile {
332    ///     email: String,
333    ///     name: String,
334    /// }
335    ///
336    /// let user = User {
337    ///     id: 1,
338    ///     profile: UserProfile {
339    ///         email: "user@example.com".to_owned(),
340    ///         name: "Alice".to_owned(),
341    ///     },
342    /// };
343    ///
344    /// let mutex = Mutex::new(user);
345    /// let guard = mutex.lock().await;
346    ///
347    /// // Map to only access the user's profile, allowing fine-grained locking
348    /// let profile_guard = MutexGuard::map(guard, |user| &mut user.profile);
349    /// assert_eq!(profile_guard.email, "user@example.com");
350    /// # }
351    /// ```
352    pub fn map<U, F>(mut orig: Self, f: F) -> MappedMutexGuard<'a, U>
353    where
354        F: FnOnce(&mut T) -> &mut U,
355        U: ?Sized,
356    {
357        let d = NonNull::from(f(&mut *orig));
358        let orig = ManuallyDrop::new(orig);
359        MappedMutexGuard {
360            d,
361            s: &orig.lock.s,
362            variance: PhantomData,
363        }
364    }
365
366    /// Attempts to project this guard to a mutable component of the protected value.
367    ///
368    /// The original guard is returned when `f` returns `None`. Call this as
369    /// `MutexGuard::filter_map(...)` so a method with the same name on `T` remains accessible.
370    ///
371    /// # Examples
372    ///
373    /// ```
374    /// # #[tokio::main]
375    /// # async fn main() {
376    /// use std::collections::HashMap;
377    ///
378    /// use asyncband::mutex::Mutex;
379    /// use asyncband::mutex::MutexGuard;
380    ///
381    /// #[derive(Debug)]
382    /// struct Database {
383    ///     users: HashMap<u32, String>,
384    ///     admin_user_id: Option<u32>,
385    /// }
386    ///
387    /// let mut db = Database {
388    ///     users: HashMap::new(),
389    ///     admin_user_id: Some(1),
390    /// };
391    /// db.users.insert(1, "admin@example.com".to_owned());
392    ///
393    /// let mutex = Mutex::new(db);
394    /// let guard = mutex.lock().await;
395    ///
396    /// // Try to map to admin user's email if admin exists
397    /// let admin_email_guard = MutexGuard::filter_map(guard, |db| {
398    ///     if let Some(admin_id) = db.admin_user_id {
399    ///         db.users.get_mut(&admin_id)
400    ///     } else {
401    ///         None
402    ///     }
403    /// })
404    /// .expect("admin user should exist");
405    ///
406    /// assert_eq!(&*admin_email_guard, "admin@example.com");
407    /// # }
408    /// ```
409    pub fn filter_map<U, F>(mut orig: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
410    where
411        F: FnOnce(&mut T) -> Option<&mut U>,
412        U: ?Sized,
413    {
414        match f(&mut *orig) {
415            Some(d) => {
416                let d = NonNull::from(d);
417                let orig = ManuallyDrop::new(orig);
418                Ok(MappedMutexGuard {
419                    d,
420                    s: &orig.lock.s,
421                    variance: PhantomData,
422                })
423            }
424            None => Err(orig),
425        }
426    }
427}
428
429/// A proof of exclusive access that owns an [`Arc`] containing its [`Mutex`].
430///
431/// [`Mutex::lock_owned`] and [`Mutex::try_lock_owned`] create this guard. Owning the `Arc` lets the
432/// guard outlive the reference used to acquire it; dropping the guard releases the lock and its
433/// share of the `Arc`.
434#[must_use = "dropping the guard releases the mutex immediately"]
435pub struct OwnedMutexGuard<T: ?Sized> {
436    lock: Arc<Mutex<T>>,
437}
438
439#[cfg(feature = "condvar")]
440pub(crate) fn owned_guard_lock<T: ?Sized>(guard: &OwnedMutexGuard<T>) -> Arc<Mutex<T>> {
441    guard.lock.clone()
442}
443
444unsafe impl<T: ?Sized + Send + Sync> Sync for OwnedMutexGuard<T> {}
445
446impl<T: ?Sized> Drop for OwnedMutexGuard<T> {
447    fn drop(&mut self) {
448        self.lock.s.release_with_lock(1);
449    }
450}
451
452impl<T: ?Sized + fmt::Debug> fmt::Debug for OwnedMutexGuard<T> {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        fmt::Debug::fmt(&**self, f)
455    }
456}
457
458impl<T: ?Sized + fmt::Display> fmt::Display for OwnedMutexGuard<T> {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        fmt::Display::fmt(&**self, f)
461    }
462}
463
464impl<T: ?Sized> Deref for OwnedMutexGuard<T> {
465    type Target = T;
466    fn deref(&self) -> &Self::Target {
467        unsafe { &*self.lock.c.get() }
468    }
469}
470
471impl<T: ?Sized> DerefMut for OwnedMutexGuard<T> {
472    fn deref_mut(&mut self) -> &mut Self::Target {
473        unsafe { &mut *self.lock.c.get() }
474    }
475}
476
477impl<T: ?Sized> OwnedMutexGuard<T> {
478    /// Projects this guard to a mutable component of the protected value.
479    ///
480    /// The returned guard retains the same `Arc` and keeps the mutex locked. Call this as
481    /// `OwnedMutexGuard::map(...)` so a method named `map` on `T` remains accessible through deref.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// # #[tokio::main]
487    /// # async fn main() {
488    /// use std::sync::Arc;
489    ///
490    /// use asyncband::mutex::Mutex;
491    /// use asyncband::mutex::OwnedMutexGuard;
492    ///
493    /// struct Config {
494    ///     name: String,
495    ///     value: u32,
496    /// }
497    ///
498    /// let config = Config {
499    ///     name: "front size".to_owned(),
500    ///     value: 42,
501    /// };
502    ///
503    /// let mutex = Arc::new(Mutex::new(config));
504    /// let guard = mutex.clone().lock_owned().await;
505    ///
506    /// // Map to access only the value field
507    /// let value_guard = OwnedMutexGuard::map(guard, |config| &mut config.value);
508    /// assert_eq!(*value_guard, 42);
509    /// # }
510    /// ```
511    pub fn map<U, F>(mut orig: Self, f: F) -> OwnedMappedMutexGuard<T, U>
512    where
513        F: FnOnce(&mut T) -> &mut U,
514        U: ?Sized,
515    {
516        let d = NonNull::from(f(&mut *orig));
517
518        let guard = ManuallyDrop::new(orig);
519
520        // SAFETY: The guard is wrapped in `ManuallyDrop` and will not be dropped,
521        // so the `Arc` can be moved out to transfer lock ownership to the new guard.
522        let lock = unsafe { ptr::read(&guard.lock) };
523
524        OwnedMappedMutexGuard {
525            lock,
526            d,
527            variance: PhantomData,
528        }
529    }
530
531    /// Attempts to project this guard to a mutable component of the protected value.
532    ///
533    /// The original guard is returned when `f` returns `None`. Call this as
534    /// `OwnedMutexGuard::filter_map(...)` so a method with the same name on `T` remains accessible.
535    ///
536    /// # Examples
537    ///
538    /// ```
539    /// # #[tokio::main]
540    /// # async fn main() {
541    /// use std::sync::Arc;
542    ///
543    /// use asyncband::mutex::Mutex;
544    /// use asyncband::mutex::OwnedMutexGuard;
545    ///
546    /// let data = vec![1, 2, 3, 4, 5];
547    /// let mutex = Arc::new(Mutex::new(data));
548    /// let guard = mutex.clone().lock_owned().await;
549    ///
550    /// // Map to the first element
551    /// let first_guard =
552    ///     OwnedMutexGuard::filter_map(guard, |vec| vec.get_mut(0)).expect("vec should not be empty");
553    ///
554    /// assert_eq!(*first_guard, 1);
555    /// # }
556    /// ```
557    pub fn filter_map<U, F>(mut orig: Self, f: F) -> Result<OwnedMappedMutexGuard<T, U>, Self>
558    where
559        F: FnOnce(&mut T) -> Option<&mut U>,
560        U: ?Sized,
561    {
562        match f(&mut *orig) {
563            Some(d) => {
564                let d = NonNull::from(d);
565                let guard = ManuallyDrop::new(orig);
566
567                // SAFETY: The guard is wrapped in `ManuallyDrop` and will not be dropped,
568                // so the `Arc` can be moved out to transfer lock ownership to the new guard.
569                let lock = unsafe { ptr::read(&guard.lock) };
570
571                Ok(OwnedMappedMutexGuard {
572                    lock,
573                    d,
574                    variance: PhantomData,
575                })
576            }
577            None => Err(orig),
578        }
579    }
580}
581
582/// A borrowed mutex guard projected to a mutable component of the protected value.
583///
584/// [`MutexGuard::map`] and [`MutexGuard::filter_map`] create this guard. It keeps the mutex locked
585/// while exposing only the projected component.
586///
587/// # Examples
588///
589/// ```
590/// # #[tokio::main]
591/// # async fn main() {
592/// use asyncband::mutex::Mutex;
593/// use asyncband::mutex::MutexGuard;
594///
595/// #[derive(Debug)]
596/// struct User {
597///     id: u32,
598///     profile: UserProfile,
599/// }
600///
601/// #[derive(Debug)]
602/// struct UserProfile {
603///     email: String,
604///     name: String,
605/// }
606///
607/// let user = User {
608///     id: 1,
609///     profile: UserProfile {
610///         email: "user@example.com".to_owned(),
611///         name: "Alice".to_owned(),
612///     },
613/// };
614///
615/// let mutex = Mutex::new(user);
616/// let guard = mutex.lock().await;
617/// let profile_guard = MutexGuard::map(guard, |user| &mut user.profile);
618///
619/// // Now we can only access the user's profile
620/// assert_eq!(profile_guard.email, "user@example.com");
621/// # }
622/// ```
623#[must_use = "dropping the guard releases the mutex immediately"]
624pub struct MappedMutexGuard<'a, T: ?Sized> {
625    d: NonNull<T>,
626    s: &'a semaphore::Semaphore,
627    // Mutable access requires invariance over T.
628    variance: PhantomData<&'a mut T>,
629}
630
631// SAFETY: MappedMutexGuard can be safely sent between threads when T: Send.
632// The guard holds exclusive access to the data protected by the mutex lock,
633// and the NonNull<T> pointer remains valid for the guard's lifetime.
634// This is essential for async tasks that may be moved between threads at .await points.
635unsafe impl<T: ?Sized + Send> Send for MappedMutexGuard<'_, T> {}
636
637// SAFETY: MappedMutexGuard can be safely shared between threads (Sync) when T: Sync.
638// Through &MappedMutexGuard, you can only get &T, so if T itself allows sharing references
639// across threads, then sharing MappedMutexGuard references is also safe.
640unsafe impl<T: ?Sized + Sync> Sync for MappedMutexGuard<'_, T> {}
641
642impl<T: ?Sized> Drop for MappedMutexGuard<'_, T> {
643    fn drop(&mut self) {
644        self.s.release_with_lock(1);
645    }
646}
647
648impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedMutexGuard<'_, T> {
649    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650        fmt::Debug::fmt(&**self, f)
651    }
652}
653
654impl<T: ?Sized + fmt::Display> fmt::Display for MappedMutexGuard<'_, T> {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        fmt::Display::fmt(&**self, f)
657    }
658}
659
660impl<T: ?Sized> Deref for MappedMutexGuard<'_, T> {
661    type Target = T;
662    fn deref(&self) -> &Self::Target {
663        // SAFETY: we hold the lock and the NonNull pointer is valid for the guard's lifetime
664        unsafe { self.d.as_ref() }
665    }
666}
667
668impl<T: ?Sized> DerefMut for MappedMutexGuard<'_, T> {
669    fn deref_mut(&mut self) -> &mut Self::Target {
670        // SAFETY: we hold the lock and the NonNull pointer is valid for the guard's lifetime
671        unsafe { self.d.as_mut() }
672    }
673}
674
675impl<'a, T: ?Sized> MappedMutexGuard<'a, T> {
676    /// Projects an already mapped guard to a deeper mutable component.
677    ///
678    /// The returned guard keeps the same mutex locked. Call this as
679    /// `MappedMutexGuard::map(...)` so a method named `map` on `T` remains accessible through
680    /// deref.
681    ///
682    /// # Examples
683    ///
684    /// ```
685    /// # #[tokio::main]
686    /// # async fn main() {
687    /// use asyncband::mutex::MappedMutexGuard;
688    /// use asyncband::mutex::Mutex;
689    /// use asyncband::mutex::MutexGuard;
690    ///
691    /// #[derive(Debug)]
692    /// struct User {
693    ///     id: u32,
694    ///     profile: UserProfile,
695    /// }
696    ///
697    /// #[derive(Debug)]
698    /// struct UserProfile {
699    ///     email: String,
700    ///     name: String,
701    /// }
702    ///
703    /// let user = User {
704    ///     id: 1,
705    ///     profile: UserProfile {
706    ///         email: "user@example.com".to_owned(),
707    ///         name: "Alice".to_owned(),
708    ///     },
709    /// };
710    ///
711    /// let mutex = Mutex::new(user);
712    /// let guard = mutex.lock().await;
713    ///
714    /// // First map to user profile
715    /// let profile_guard = MutexGuard::map(guard, |user| &mut user.profile);
716    /// // Then map to the email field specifically
717    /// let email_guard = MappedMutexGuard::map(profile_guard, |profile| &mut profile.email);
718    ///
719    /// assert_eq!(&*email_guard, "user@example.com");
720    /// # }
721    /// ```
722    pub fn map<U, F>(mut orig: Self, f: F) -> MappedMutexGuard<'a, U>
723    where
724        F: FnOnce(&mut T) -> &mut U,
725        U: ?Sized,
726    {
727        let d = NonNull::from(f(&mut *orig));
728        let orig = ManuallyDrop::new(orig);
729        MappedMutexGuard {
730            d,
731            s: orig.s,
732            variance: PhantomData,
733        }
734    }
735
736    /// Attempts to project an already mapped guard to a deeper mutable component.
737    ///
738    /// The original mapped guard is returned when `f` returns `None`. Call this as
739    /// `MappedMutexGuard::filter_map(...)` so a method with the same name on `T` remains
740    /// accessible.
741    ///
742    /// # Examples
743    ///
744    /// ```
745    /// # #[tokio::main]
746    /// # async fn main() {
747    /// use asyncband::mutex::MappedMutexGuard;
748    /// use asyncband::mutex::Mutex;
749    /// use asyncband::mutex::MutexGuard;
750    ///
751    /// #[derive(Debug)]
752    /// struct Data {
753    ///     id: u32,
754    ///     value: Option<String>,
755    /// }
756    ///
757    /// let data = Data {
758    ///     id: 1,
759    ///     value: Some("hello".to_owned()),
760    /// };
761    ///
762    /// let mutex = Mutex::new(data);
763    /// let guard = mutex.lock().await;
764    ///
765    /// // First map to the value field
766    /// let value_guard = MutexGuard::map(guard, |data| &mut data.value);
767    /// // Then try to map to the inner string if it exists
768    /// let string_guard =
769    ///     MappedMutexGuard::filter_map(value_guard, |opt| opt.as_mut()).expect("value should exist");
770    ///
771    /// assert_eq!(&*string_guard, "hello");
772    /// # }
773    /// ```
774    pub fn filter_map<U, F>(mut orig: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
775    where
776        F: FnOnce(&mut T) -> Option<&mut U>,
777        U: ?Sized,
778    {
779        match f(&mut *orig) {
780            Some(d) => {
781                let d = NonNull::from(d);
782                let orig = ManuallyDrop::new(orig);
783                Ok(MappedMutexGuard {
784                    d,
785                    s: orig.s,
786                    variance: PhantomData,
787                })
788            }
789            None => Err(orig),
790        }
791    }
792}
793
794/// An owned mutex guard projected to a mutable component of the protected value.
795///
796/// [`OwnedMutexGuard::map`] and [`OwnedMutexGuard::filter_map`] create this guard. It keeps the
797/// original mutex alive and locked while exposing only the projected component.
798///
799/// # Examples
800///
801/// ```
802/// # #[tokio::main]
803/// # async fn main() {
804/// use std::sync::Arc;
805///
806/// use asyncband::mutex::Mutex;
807/// use asyncband::mutex::OwnedMutexGuard;
808///
809/// struct Data {
810///     value: u32,
811/// }
812///
813/// let data = Data { value: 42 };
814/// let mutex = Arc::new(Mutex::new(data));
815/// let guard = mutex.clone().lock_owned().await;
816/// let value_guard = OwnedMutexGuard::map(guard, |data| &mut data.value);
817///
818/// assert_eq!(*value_guard, 42);
819/// # }
820/// ```
821#[must_use = "dropping the guard releases the mutex immediately"]
822pub struct OwnedMappedMutexGuard<T: ?Sized, U: ?Sized> {
823    lock: Arc<Mutex<T>>,
824    d: NonNull<U>,
825    // Mutable access requires invariance over U.
826    variance: PhantomData<*mut U>,
827}
828
829// SAFETY: OwnedMappedMutexGuard can be safely sent between threads when T: Send and U: Send.
830// It holds exclusive access to the data protected by the mutex lock, and the raw pointer
831// remains valid for the guard's lifetime. This is essential for async tasks that may be
832// moved between threads at .await points.
833unsafe impl<T: ?Sized + Send, U: ?Sized + Send> Send for OwnedMappedMutexGuard<T, U> {}
834
835// SAFETY: OwnedMappedMutexGuard can be safely shared between threads (Sync) when T: Send + Sync and
836// U: Send + Sync. Through &OwnedMappedMutexGuard, you can only get &U, so if U itself allows
837// sharing references across threads, then sharing OwnedMappedMutexGuard references is also safe.
838// We require T: Send + Sync for maximum safety and ecosystem compatibility.
839unsafe impl<T: ?Sized + Send + Sync, U: ?Sized + Send + Sync> Sync for OwnedMappedMutexGuard<T, U> {}
840
841impl<T: ?Sized, U: ?Sized> Drop for OwnedMappedMutexGuard<T, U> {
842    fn drop(&mut self) {
843        self.lock.s.release_with_lock(1);
844    }
845}
846
847impl<T: ?Sized, U: ?Sized + fmt::Debug> fmt::Debug for OwnedMappedMutexGuard<T, U> {
848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849        fmt::Debug::fmt(&**self, f)
850    }
851}
852
853impl<T: ?Sized, U: ?Sized + fmt::Display> fmt::Display for OwnedMappedMutexGuard<T, U> {
854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855        fmt::Display::fmt(&**self, f)
856    }
857}
858
859impl<T: ?Sized, U: ?Sized> Deref for OwnedMappedMutexGuard<T, U> {
860    type Target = U;
861    fn deref(&self) -> &Self::Target {
862        // SAFETY: we hold the lock and the NonNull pointer is valid for the guard's lifetime
863        // The Arc ensures the underlying data remains valid
864        unsafe { self.d.as_ref() }
865    }
866}
867
868impl<T: ?Sized, U: ?Sized> DerefMut for OwnedMappedMutexGuard<T, U> {
869    fn deref_mut(&mut self) -> &mut Self::Target {
870        // SAFETY: we hold the lock and the NonNull pointer is valid for the guard's lifetime
871        // The Arc ensures the underlying data remains valid
872        unsafe { self.d.as_mut() }
873    }
874}
875
876impl<T: ?Sized, U: ?Sized> OwnedMappedMutexGuard<T, U> {
877    /// Projects an owned mapped guard to a deeper mutable component.
878    ///
879    /// The returned guard retains the same `Arc` and keeps the mutex locked. Call this as
880    /// `OwnedMappedMutexGuard::map(...)` so a method named `map` on `U` remains accessible through
881    /// deref.
882    ///
883    /// # Examples
884    ///
885    /// ```
886    /// # #[tokio::main]
887    /// # async fn main() {
888    /// use std::sync::Arc;
889    ///
890    /// use asyncband::mutex::Mutex;
891    /// use asyncband::mutex::OwnedMappedMutexGuard;
892    /// use asyncband::mutex::OwnedMutexGuard;
893    ///
894    /// #[derive(Debug)]
895    /// struct Config {
896    ///     host: String,
897    ///     port: u16,
898    /// }
899    ///
900    /// let config = Config {
901    ///     host: "localhost".to_owned(),
902    ///     port: 8080,
903    /// };
904    ///
905    /// let mutex = Arc::new(Mutex::new(config));
906    /// let guard = mutex.clone().lock_owned().await;
907    ///
908    /// // First map to config
909    /// let config_guard = OwnedMutexGuard::map(guard, |config| &mut config.host);
910    /// // Then map to the host string specifically
911    /// let host_guard = OwnedMappedMutexGuard::map(config_guard, |host| host.as_mut_str());
912    ///
913    /// assert_eq!(&*host_guard, "localhost");
914    /// # }
915    /// ```
916    pub fn map<V, F>(mut orig: Self, f: F) -> OwnedMappedMutexGuard<T, V>
917    where
918        F: FnOnce(&mut U) -> &mut V,
919        V: ?Sized,
920    {
921        let d = NonNull::from(f(&mut *orig));
922        let orig = ManuallyDrop::new(orig);
923
924        // SAFETY: The guard is wrapped in `ManuallyDrop` and will not be dropped,
925        // so the `Arc` can be moved out to transfer lock ownership to the new guard.
926        let lock = unsafe { ptr::read(&orig.lock) };
927
928        OwnedMappedMutexGuard {
929            lock,
930            d,
931            variance: PhantomData,
932        }
933    }
934
935    /// Attempts to project an owned mapped guard to a deeper mutable component.
936    ///
937    /// The original mapped guard is returned when `f` returns `None`. Call this as
938    /// `OwnedMappedMutexGuard::filter_map(...)` so a method with the same name on `U` remains
939    /// accessible through deref.
940    ///
941    /// # Examples
942    ///
943    /// ```
944    /// # #[tokio::main]
945    /// # async fn main() {
946    /// use std::sync::Arc;
947    ///
948    /// use asyncband::mutex::Mutex;
949    /// use asyncband::mutex::OwnedMappedMutexGuard;
950    /// use asyncband::mutex::OwnedMutexGuard;
951    ///
952    /// #[derive(Debug)]
953    /// struct Node {
954    ///     value: i32,
955    ///     left: Option<Box<Node>>,
956    ///     right: Option<Box<Node>>,
957    /// }
958    ///
959    /// let node = Node {
960    ///     value: 10,
961    ///     left: Some(Box::new(Node {
962    ///         value: 5,
963    ///         left: None,
964    ///         right: None,
965    ///     })),
966    ///     right: None,
967    /// };
968    ///
969    /// let mutex = Arc::new(Mutex::new(node));
970    /// let guard = mutex.clone().lock_owned().await;
971    ///
972    /// // First map to left child
973    /// let left_guard = OwnedMutexGuard::map(guard, |node| &mut node.left);
974    /// // Try to access the left child if it exists
975    /// let child_guard = OwnedMappedMutexGuard::filter_map(left_guard, |left| {
976    ///     left.as_mut().map(|boxed| boxed.as_mut())
977    /// })
978    /// .expect("left child should exist");
979    ///
980    /// assert_eq!(child_guard.value, 5);
981    /// # }
982    /// ```
983    pub fn filter_map<V, F>(mut orig: Self, f: F) -> Result<OwnedMappedMutexGuard<T, V>, Self>
984    where
985        F: FnOnce(&mut U) -> Option<&mut V>,
986        V: ?Sized,
987    {
988        match f(&mut *orig) {
989            Some(d) => {
990                let d = NonNull::from(d);
991                let orig = ManuallyDrop::new(orig);
992
993                // SAFETY: The guard is wrapped in `ManuallyDrop` and will not be dropped,
994                // so the `Arc` can be moved out to transfer lock ownership to the new guard.
995                let lock = unsafe { ptr::read(&orig.lock) };
996
997                Ok(OwnedMappedMutexGuard {
998                    lock,
999                    d,
1000                    variance: PhantomData,
1001                })
1002            }
1003            None => Err(orig),
1004        }
1005    }
1006}
1007
1008#[cfg(doctest)]
1009mod compile_fail_tests {
1010    /// ```compile_fail
1011    /// use asyncband::mutex::MutexGuard;
1012    ///
1013    /// fn shorten<'lock, 'short: 'lock>(
1014    ///     guard: MutexGuard<'lock, &'static str>,
1015    ///     value: &'short str,
1016    /// ) -> MutexGuard<'lock, &'short str> {
1017    ///     let mut guard: MutexGuard<'lock, &'short str> = guard;
1018    ///     *guard = value;
1019    ///     guard
1020    /// }
1021    /// ```
1022    struct MutexGuardIsInvariant;
1023
1024    /// ```compile_fail
1025    /// use asyncband::mutex::OwnedMutexGuard;
1026    ///
1027    /// fn shorten<'short>(
1028    ///     guard: OwnedMutexGuard<&'static str>,
1029    ///     value: &'short str,
1030    /// ) -> OwnedMutexGuard<&'short str> {
1031    ///     let mut guard: OwnedMutexGuard<&'short str> = guard;
1032    ///     *guard = value;
1033    ///     guard
1034    /// }
1035    /// ```
1036    struct OwnedMutexGuardIsInvariant;
1037
1038    /// ```compile_fail
1039    /// use asyncband::mutex::MappedMutexGuard;
1040    ///
1041    /// fn shorten<'lock, 'short: 'lock>(
1042    ///     guard: MappedMutexGuard<'lock, &'static str>,
1043    ///     value: &'short str,
1044    /// ) -> MappedMutexGuard<'lock, &'short str> {
1045    ///     let mut guard: MappedMutexGuard<'lock, &'short str> = guard;
1046    ///     *guard = value;
1047    ///     guard
1048    /// }
1049    /// ```
1050    struct MappedMutexGuardIsInvariant;
1051
1052    /// ```compile_fail
1053    /// use asyncband::mutex::OwnedMappedMutexGuard;
1054    ///
1055    /// fn shorten<'short>(
1056    ///     guard: OwnedMappedMutexGuard<(), &'static str>,
1057    ///     value: &'short str,
1058    /// ) -> OwnedMappedMutexGuard<(), &'short str> {
1059    ///     let mut guard: OwnedMappedMutexGuard<(), &'short str> = guard;
1060    ///     *guard = value;
1061    ///     guard
1062    /// }
1063    /// ```
1064    struct OwnedMappedMutexGuardIsInvariant;
1065}