Skip to main content

serialplugin_core/
sync_util.rs

1//! Mutex helpers for background threads (recover from poison instead of panicking).
2
3use std::sync::{Mutex, MutexGuard};
4
5/// Lock a mutex, recovering the inner value if the mutex was poisoned.
6pub fn lock_or_recover<'a, T>(mutex: &'a Mutex<T>) -> MutexGuard<'a, T> {
7    mutex.lock().unwrap_or_else(|e| e.into_inner())
8}
9
10/// Serialize PTY integration tests (parallel `TTYPort::pair()` races on macOS).
11#[cfg(all(unix, not(any(target_os = "android", target_os = "ios"))))]
12static PTY_TEST_LOCK: Mutex<()> = Mutex::new(());
13
14/// Test helper: a PTY pair, with a process-wide lock held while it is alive.
15#[doc(hidden)]
16#[cfg(all(unix, not(any(target_os = "android", target_os = "ios"))))]
17pub fn pty_pair_locked() -> (
18    MutexGuard<'static, ()>,
19    serialport::TTYPort,
20    serialport::TTYPort,
21) {
22    let guard = lock_or_recover(&PTY_TEST_LOCK);
23    let (master, slave) = serialport::TTYPort::pair().expect("pty pair");
24    (guard, master, slave)
25}