maybe_fut/api/sync/rwlock/
write_guard.rs

1use std::fmt::Display;
2use std::ops::{Deref, DerefMut};
3
4/// RAII structure used to release the shared write access of a lock when dropped.
5///
6/// This structure is created by the [`super::RwLock::write`] and [`super::RwLock::try_write`] methods on [`super::RwLock`].
7#[derive(Debug)]
8pub struct RwLockWriteGuard<'a, T: ?Sized + 'a>(InnerRwLockWriteGuard<'a, T>);
9
10#[derive(Debug)]
11enum InnerRwLockWriteGuard<'a, T: ?Sized + 'a> {
12    Std(std::sync::RwLockWriteGuard<'a, T>),
13    #[cfg(tokio_sync)]
14    #[cfg_attr(docsrs, doc(cfg(feature = "tokio-sync")))]
15    Tokio(tokio::sync::RwLockWriteGuard<'a, T>),
16}
17
18impl<'a, T> From<std::sync::RwLockWriteGuard<'a, T>> for RwLockWriteGuard<'a, T> {
19    fn from(guard: std::sync::RwLockWriteGuard<'a, T>) -> Self {
20        Self(InnerRwLockWriteGuard::Std(guard))
21    }
22}
23
24#[cfg(tokio_sync)]
25#[cfg_attr(docsrs, doc(cfg(feature = "tokio-sync")))]
26impl<'a, T> From<tokio::sync::RwLockWriteGuard<'a, T>> for RwLockWriteGuard<'a, T> {
27    fn from(guard: tokio::sync::RwLockWriteGuard<'a, T>) -> Self {
28        Self(InnerRwLockWriteGuard::Tokio(guard))
29    }
30}
31
32impl<'a, T> Deref for RwLockWriteGuard<'a, T>
33where
34    T: ?Sized,
35{
36    type Target = T;
37
38    fn deref(&self) -> &Self::Target {
39        match &self.0 {
40            InnerRwLockWriteGuard::Std(guard) => guard.deref(),
41            #[cfg(tokio_sync)]
42            InnerRwLockWriteGuard::Tokio(guard) => guard.deref(),
43        }
44    }
45}
46
47impl<'a, T> DerefMut for RwLockWriteGuard<'a, T>
48where
49    T: ?Sized,
50{
51    fn deref_mut(&mut self) -> &mut Self::Target {
52        match &mut self.0 {
53            InnerRwLockWriteGuard::Std(guard) => guard.deref_mut(),
54            #[cfg(tokio_sync)]
55            InnerRwLockWriteGuard::Tokio(guard) => guard.deref_mut(),
56        }
57    }
58}
59
60impl Display for RwLockWriteGuard<'_, str> {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match &self.0 {
63            InnerRwLockWriteGuard::Std(guard) => guard.fmt(f),
64            #[cfg(tokio_sync)]
65            InnerRwLockWriteGuard::Tokio(guard) => guard.fmt(f),
66        }
67    }
68}