Skip to main content

libdd_common/
lock_ext.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
5
6/// Extension trait for `Mutex` to provide a method that acquires a lock, panicking if the lock is
7/// poisoned.
8///
9/// This helper function is intended to be used to avoid having to add many
10/// `#[allow(clippy::unwrap_used)]` annotations if there are a lot of usages of `Mutex`.
11///
12/// # Arguments
13///
14/// * `self` - A reference to the `Mutex` to lock.
15///
16/// # Returns
17///
18/// A `MutexGuard` that provides access to the locked data.
19///
20/// # Panics
21///
22/// This function will panic if the `Mutex` is poisoned.
23///
24/// # Examples
25///
26/// ```
27/// use libdd_common::MutexExt;
28/// use std::sync::{Arc, Mutex};
29///
30/// let data = Arc::new(Mutex::new(5));
31/// let data_clone = Arc::clone(&data);
32///
33/// std::thread::spawn(move || {
34///     let mut num = data_clone.lock_or_panic();
35///     *num += 1;
36/// })
37/// .join()
38/// .expect("Thread panicked");
39///
40/// assert_eq!(*data.lock_or_panic(), 6);
41/// ```
42pub trait MutexExt<T> {
43    fn lock_or_panic(&self) -> MutexGuard<'_, T>;
44}
45
46impl<T> MutexExt<T> for Mutex<T> {
47    #[inline(always)]
48    #[track_caller]
49    fn lock_or_panic(&self) -> MutexGuard<'_, T> {
50        #[allow(clippy::unwrap_used)]
51        self.lock().unwrap()
52    }
53}
54
55/// Extension trait for `RwLock` to provide methods that acquire read/write locks, panicking if
56/// the lock is poisoned.
57///
58/// Mirrors [`MutexExt`] for `RwLock` so callers avoid `#[allow(clippy::unwrap_used)]` at each
59/// lock site.
60///
61/// # Examples
62///
63/// ```
64/// use libdd_common::RwLockExt;
65/// use std::sync::{Arc, RwLock};
66///
67/// let data = Arc::new(RwLock::new(5));
68/// let data_clone = Arc::clone(&data);
69///
70/// std::thread::spawn(move || {
71///     let mut num = data_clone.write_or_panic();
72///     *num += 1;
73/// })
74/// .join()
75/// .expect("Thread panicked");
76///
77/// assert_eq!(*data.read_or_panic(), 6);
78/// ```
79pub trait RwLockExt<T> {
80    fn read_or_panic(&self) -> RwLockReadGuard<'_, T>;
81    fn write_or_panic(&self) -> RwLockWriteGuard<'_, T>;
82}
83
84impl<T> RwLockExt<T> for RwLock<T> {
85    #[inline(always)]
86    #[track_caller]
87    fn read_or_panic(&self) -> RwLockReadGuard<'_, T> {
88        #[allow(clippy::unwrap_used)]
89        self.read().unwrap()
90    }
91
92    #[inline(always)]
93    #[track_caller]
94    fn write_or_panic(&self) -> RwLockWriteGuard<'_, T> {
95        #[allow(clippy::unwrap_used)]
96        self.write().unwrap()
97    }
98}