anstyle_stream/
lockable.rs

1#[cfg(all(windows, feature = "wincon"))]
2use crate::RawStream;
3
4/// Explicitly lock a [`std::io::Write`]able
5pub trait Lockable {
6    type Locked;
7
8    /// Get exclusive access to the `AutoStream`
9    ///
10    /// Why?
11    /// - Faster performance when writing in a loop
12    /// - Avoid other threads interleaving output with the current thread
13    fn lock(self) -> Self::Locked;
14}
15
16impl Lockable for std::io::Stdout {
17    type Locked = std::io::StdoutLock<'static>;
18
19    #[inline]
20    fn lock(self) -> Self::Locked {
21        #[allow(clippy::needless_borrow)] // Its needed to avoid recursion
22        (&self).lock()
23    }
24}
25
26impl Lockable for std::io::Stderr {
27    type Locked = std::io::StderrLock<'static>;
28
29    #[inline]
30    fn lock(self) -> Self::Locked {
31        #[allow(clippy::needless_borrow)] // Its needed to avoid recursion
32        (&self).lock()
33    }
34}
35
36#[cfg(all(windows, feature = "wincon"))]
37impl<S> Lockable for anstyle_wincon::Console<S>
38where
39    S: RawStream + Lockable,
40    <S as Lockable>::Locked: RawStream,
41{
42    type Locked = anstyle_wincon::Console<<S as Lockable>::Locked>;
43
44    #[inline]
45    fn lock(self) -> Self::Locked {
46        self.map(|s| s.lock())
47    }
48}