Created
July 27, 2024 23:51
-
-
Save asaaki/d3df2e81fd4b6685d0562a3cdda226b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
use std::io::Write; | |
use std::fmt::{Debug, Formatter, Error}; | |
use std::thread; | |
use std::time::Duration; | |
use std::sync::{Arc, Mutex}; | |
#[derive(Clone)] | |
struct Output<W>(Arc<Mutex<W>>); | |
impl<W: Write> Output<W> { | |
pub fn new(w: W) -> Self { | |
Output(Arc::new(Mutex::new(w))) | |
} | |
} | |
impl<W: Write> Write for Output<W> { | |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { | |
(*self.0.lock().unwrap()).write(buf) | |
} | |
fn flush(&mut self) -> io::Result<()> { | |
(*self.0.lock().unwrap()).flush() | |
} | |
} | |
impl<W: Debug> Debug for Output<W> { | |
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> { | |
(*self.0.lock().unwrap()).fmt(fmt) | |
} | |
} | |
fn main() { | |
let buffer = Output::new(Vec::new()); | |
write_to(buffer.clone()); | |
thread::sleep(Duration::new(1, 0)); | |
println!("{:?}", buffer); | |
} | |
fn write_to<W: Write + Send + 'static>(mut buffer: W) { | |
thread::spawn(move || buffer.write(b"hello").unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment