use actix_web::web::{Bytes, BytesMut};
use futures::channel::mpsc::Sender;
use futures::executor::block_on;
use futures::sink::SinkExt;
use std::io::{self, Error, ErrorKind, Write};
pub struct Pipe {
dest: Sender<io::Result<Bytes>>,
bytes: BytesMut,
}
impl Pipe {
pub fn new(destination: Sender<io::Result<Bytes>>) -> Self {
Pipe {
dest: destination,
bytes: BytesMut::new(),
}
}
}
impl Drop for Pipe {
fn drop(&mut self) {
let _ = block_on(self.dest.close());
}
}
impl Write for Pipe {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.bytes.extend_from_slice(buf);
block_on(self.dest.send(Ok(self.bytes.split().into())))
.map_err(|e| Error::new(ErrorKind::UnexpectedEof, e))?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
block_on(self.dest.flush()).map_err(|e| Error::new(ErrorKind::UnexpectedEof, e))
}
}