aboutsummaryrefslogtreecommitdiffstats
path: root/src/pipe.rs
diff options
context:
space:
mode:
authorAlexandre Bury <alexandre.bury@gmail.com>2019-06-24 00:46:46 +0000
committerAlexandre Bury <alexandre.bury@gmail.com>2019-06-24 00:46:46 +0000
commitb4fc1fc57fb973ee856d97079918b0051c93858b (patch)
tree47a2505a9b14dad13d28c1c6cefdc7b1a4a87c0c /src/pipe.rs
parentEnable streaming tarball download (diff)
downloadminiserve-b4fc1fc57fb973ee856d97079918b0051c93858b.tar.gz
miniserve-b4fc1fc57fb973ee856d97079918b0051c93858b.zip
Add doc and comments
Diffstat (limited to '')
-rw-r--r--src/pipe.rs21
1 files changed, 17 insertions, 4 deletions
diff --git a/src/pipe.rs b/src/pipe.rs
index 710be1f..2fd9fac 100644
--- a/src/pipe.rs
+++ b/src/pipe.rs
@@ -3,12 +3,18 @@ use futures::sink::{Sink, Wait};
use futures::sync::mpsc::Sender;
use std::io::{Error, ErrorKind, Result, Write};
+/// Adapter to implement the `std::io::Write` trait on a `Sender<Bytes>` from a futures channel.
+///
+/// It uses an intermediate buffer to transfer packets.
pub struct Pipe {
+ // Wrapping the sender in `Wait` makes it blocking, so we can implement blocking-style
+ // io::Write over the async-style Sender.
dest: Wait<Sender<Bytes>>,
bytes: BytesMut,
}
impl Pipe {
+ /// Wrap the given sender in a `Pipe`.
pub fn new(destination: Sender<Bytes>) -> Self {
Pipe {
dest: destination.wait(),
@@ -19,17 +25,24 @@ impl Pipe {
impl Drop for Pipe {
fn drop(&mut self) {
+ // This is the correct thing to do, but is not super important since the `Sink`
+ // implementation of `Sender` just returns `Ok` without doing anything else.
let _ = self.dest.close();
}
}
impl Write for Pipe {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
+ // We are given a slice of bytes we do not own, so we must start by copying it.
self.bytes.extend_from_slice(buf);
- match self.dest.send(self.bytes.take().into()) {
- Ok(_) => Ok(buf.len()),
- Err(e) => Err(Error::new(ErrorKind::UnexpectedEof, e)),
- }
+
+ // Then, take the buffer and send it in the channel.
+ self.dest
+ .send(self.bytes.take().into())
+ .map_err(|e| Error::new(ErrorKind::UnexpectedEof, e))?;
+
+ // Return how much we sent - all of it.
+ Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {