console_subscriber/
sync.rs
1#![allow(dead_code, unused_imports)]
3
4#[cfg(feature = "parking_lot")]
5pub(crate) use parking_lot::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
6
7#[cfg(not(feature = "parking_lot"))]
8pub(crate) use self::std_impl::*;
9
10#[cfg(not(feature = "parking_lot"))]
11mod std_impl {
12 use std::sync::{self, PoisonError, TryLockError};
13 pub use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
14
15 #[derive(Debug, Default)]
16 pub(crate) struct Mutex<T: ?Sized>(sync::Mutex<T>);
17
18 impl<T> Mutex<T> {
19 pub(crate) fn new(data: T) -> Self {
20 Self(sync::Mutex::new(data))
21 }
22 }
23
24 impl<T: ?Sized> Mutex<T> {
25 pub(crate) fn lock(&self) -> MutexGuard<'_, T> {
26 self.0.lock().unwrap_or_else(PoisonError::into_inner)
27 }
28 }
29
30 #[derive(Debug, Default)]
31 pub(crate) struct RwLock<T: ?Sized>(sync::RwLock<T>);
32
33 impl<T> RwLock<T> {
34 pub(crate) fn new(data: T) -> Self {
35 Self(sync::RwLock::new(data))
36 }
37 }
38
39 impl<T: ?Sized> RwLock<T> {
40 pub(crate) fn read(&self) -> RwLockReadGuard<'_, T> {
41 self.0.read().unwrap_or_else(PoisonError::into_inner)
42 }
43
44 pub(crate) fn try_read(&self) -> Option<RwLockReadGuard<'_, T>> {
45 match self.0.try_read() {
46 Ok(guard) => Some(guard),
47 Err(TryLockError::Poisoned(p)) => Some(p.into_inner()),
48 Err(TryLockError::WouldBlock) => None,
49 }
50 }
51
52 pub(crate) fn write(&self) -> RwLockWriteGuard<'_, T> {
53 self.0.write().unwrap_or_else(PoisonError::into_inner)
54 }
55
56 pub(crate) fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>> {
57 match self.0.try_write() {
58 Ok(guard) => Some(guard),
59 Err(TryLockError::Poisoned(p)) => Some(p.into_inner()),
60 Err(TryLockError::WouldBlock) => None,
61 }
62 }
63 }
64}