summaryrefslogtreecommitdiff
path: root/src/tokio_util.rs
diff options
context:
space:
mode:
authorRyan Dahl <ry@tinyclouds.org>2018-10-03 23:58:29 -0400
committerGitHub <noreply@github.com>2018-10-03 23:58:29 -0400
commit0422b224e8a55bf259cdbe955d825229496a0687 (patch)
tree1bf47de8ca1a5405a40d2303cff81f72190095bb /src/tokio_util.rs
parente5e7f0f038494bfe8aa14e31c8d13d6cf481186a (diff)
First pass at support for TCP servers and clients. (#884)
Adds deno.listen(), deno.dial(), deno.Listener and deno.Conn.
Diffstat (limited to 'src/tokio_util.rs')
-rw-r--r--src/tokio_util.rs46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/tokio_util.rs b/src/tokio_util.rs
index de81620ef..0a2a34917 100644
--- a/src/tokio_util.rs
+++ b/src/tokio_util.rs
@@ -1,8 +1,15 @@
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
+use resources::Resource;
+
use futures;
use futures::Future;
+use futures::Poll;
+use std::io;
+use std::mem;
+use std::net::SocketAddr;
use tokio;
+use tokio::net::TcpStream;
use tokio_executor;
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
@@ -28,3 +35,42 @@ where
let mut enter = tokio_executor::enter().expect("Multiple executors at once");
tokio_executor::with_default(&mut executor, &mut enter, move |_enter| f());
}
+
+#[derive(Debug)]
+enum AcceptState {
+ Pending(Resource),
+ Empty,
+}
+
+/// Simply accepts a connection.
+pub fn accept(r: Resource) -> Accept {
+ Accept {
+ state: AcceptState::Pending(r),
+ }
+}
+
+/// A future which can be used to easily read available number of bytes to fill
+/// a buffer.
+///
+/// Created by the [`read`] function.
+#[derive(Debug)]
+pub struct Accept {
+ state: AcceptState,
+}
+
+impl Future for Accept {
+ type Item = (TcpStream, SocketAddr);
+ type Error = io::Error;
+
+ fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
+ let (stream, addr) = match self.state {
+ AcceptState::Pending(ref mut r) => try_ready!(r.poll_accept()),
+ AcceptState::Empty => panic!("poll Accept after it's done"),
+ };
+
+ match mem::replace(&mut self.state, AcceptState::Empty) {
+ AcceptState::Pending(_) => Ok((stream, addr).into()),
+ AcceptState::Empty => panic!("invalid internal state"),
+ }
+ }
+}