From 894ec4f24c1269166f14c05b2ae3f737f76dd571 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Thu, 24 Oct 2019 15:16:10 -0400 Subject: add a couple examples --- examples/input/buf.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 examples/input/buf.rs (limited to 'examples/input/buf.rs') diff --git a/examples/input/buf.rs b/examples/input/buf.rs new file mode 100644 index 0000000..768baf1 --- /dev/null +++ b/examples/input/buf.rs @@ -0,0 +1,43 @@ +use std::io::Read as _; + +pub struct Stdin { + buf: Vec, + task: futures::task::Task, +} + +#[allow(dead_code)] +impl Stdin { + pub fn new() -> Self { + Self { + buf: vec![], + task: futures::task::current(), + } + } + + pub fn send(&mut self, buf: &[u8]) { + self.buf.extend(buf.iter()); + self.task.notify(); + } +} + +impl std::io::Read for Stdin { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let len = self.buf.len().min(buf.len()); + buf[..len].clone_from_slice(&self.buf[..len]); + self.buf = self.buf.iter().copied().skip(len).collect(); + Ok(len) + } +} + +impl tokio::io::AsyncRead for Stdin { + fn poll_read( + &mut self, + buf: &mut [u8], + ) -> std::result::Result, tokio::io::Error> { + if self.buf.is_empty() { + return Ok(futures::Async::NotReady); + } + let n = self.read(buf)?; + Ok(futures::Async::Ready(n)) + } +} -- cgit v1.2.3-54-g00ecf