synchronized_writer/
synchronized_option_writer.rs1use std::io::{self, ErrorKind, Write};
2use std::ops::DerefMut;
3use std::sync::{Arc, Mutex};
4
5pub struct SynchronizedOptionWriter<W: Write> {
6 inner: Arc<Mutex<Option<W>>>,
7}
8
9impl<W: Write> SynchronizedOptionWriter<W> {
10 #[inline]
11 pub fn new(writer: Arc<Mutex<Option<W>>>) -> SynchronizedOptionWriter<W> {
12 SynchronizedOptionWriter {
13 inner: writer,
14 }
15 }
16}
17
18impl<W: Write> Write for SynchronizedOptionWriter<W> {
19 #[inline]
20 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
21 match self
22 .inner
23 .lock()
24 .map_err(|err| io::Error::new(ErrorKind::WouldBlock, err.to_string()))?
25 .deref_mut()
26 {
27 Some(writer) => writer.write(buf),
28 None => Err(io::Error::new(ErrorKind::BrokenPipe, "the writer has been removed out")),
29 }
30 }
31
32 #[inline]
33 fn flush(&mut self) -> Result<(), io::Error> {
34 match self
35 .inner
36 .lock()
37 .map_err(|err| io::Error::new(ErrorKind::WouldBlock, err.to_string()))?
38 .deref_mut()
39 {
40 Some(writer) => writer.flush(),
41 None => Err(io::Error::new(ErrorKind::BrokenPipe, "the writer has been removed out")),
42 }
43 }
44}