use std::future::Future;
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio::time::Instant;
pub(crate) trait LockExt<T> {
fn lock_unpoisoned(&self) -> MutexGuard<'_, T>;
}
impl<T> LockExt<T> for Mutex<T> {
fn lock_unpoisoned(&self) -> MutexGuard<'_, T> {
self.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
pub(crate) fn spawn_detached<F>(future: F) -> Option<JoinHandle<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::runtime::Handle::try_current()
.ok()
.map(|runtime| runtime.spawn(future))
}
pub(crate) fn deadline_after(start: Instant, timeout: Duration) -> Instant {
start
.checked_add(timeout)
.unwrap_or_else(|| start + Duration::from_secs(86_400 * 365 * 30))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deadline_after_saturates_oversized_timeouts() {
let start = Instant::now();
let short = Duration::from_secs(5);
assert_eq!(deadline_after(start, short), start + short);
assert!(deadline_after(start, Duration::MAX) > start + short);
}
#[test]
fn lock_unpoisoned_recovers_a_poisoned_mutex() {
let mutex = std::sync::Arc::new(Mutex::new(1));
let poisoner = std::sync::Arc::clone(&mutex);
let _ = std::thread::spawn(move || {
let _guard = poisoner.lock().unwrap();
panic!("poison");
})
.join();
assert!(mutex.is_poisoned());
assert_eq!(*mutex.lock_unpoisoned(), 1);
}
#[test]
fn spawn_detached_needs_a_runtime() {
assert!(spawn_detached(async {}).is_none());
}
}