synchronized_writer/
synchronized_writer.rs

1use std::io::{self, ErrorKind, Write};
2use std::sync::{Arc, Mutex};
3
4pub struct SynchronizedWriter<W: Write> {
5    inner: Arc<Mutex<W>>,
6}
7
8impl<W: Write> SynchronizedWriter<W> {
9    #[inline]
10    pub fn new(writer: Arc<Mutex<W>>) -> SynchronizedWriter<W> {
11        SynchronizedWriter {
12            inner: writer,
13        }
14    }
15}
16
17impl<W: Write> Write for SynchronizedWriter<W> {
18    #[inline]
19    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
20        self.inner
21            .lock()
22            .map_err(|err| io::Error::new(ErrorKind::WouldBlock, err.to_string()))?
23            .write(buf)
24    }
25
26    #[inline]
27    fn flush(&mut self) -> Result<(), io::Error> {
28        self.inner
29            .lock()
30            .map_err(|err| io::Error::new(ErrorKind::WouldBlock, err.to_string()))?
31            .flush()
32    }
33}