Skip to content

Instantly share code, notes, and snippets.

@yoshuawuyts
Forked from rust-play/playground.rs
Created July 22, 2019 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshuawuyts/79140cd53bde52fa5bb7f7efdc2bdf4c to your computer and use it in GitHub Desktop.
Save yoshuawuyts/79140cd53bde52fa5bb7f7efdc2bdf4c to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![feature(async_await)]
use std::{cell::Cell, future::Future, io, net::SocketAddr, pin::Pin};
pub trait TcpStream {}
impl<T: TcpStream + ?Sized> TcpStream for Pin<Box<T>> {}
pub trait Runtime: Send + Sync + 'static {
type TcpStream: TcpStream;
type ConnectTcpStream: Future<Output = io::Result<Self::TcpStream>>;
fn connect_tcp_stream(&self, addr: &SocketAddr) -> Self::ConnectTcpStream;
}
impl<R: Runtime> Runtime for Box<R> {
type TcpStream = Pin<Box<dyn TcpStream>>;
type ConnectTcpStream = Pin<Box<dyn Future<Output = io::Result<Self::TcpStream>>>>;
fn connect_tcp_stream(&self, addr: &SocketAddr) -> Self::ConnectTcpStream {
let fut = R::connect_tcp_stream(&**self, addr);
Box::pin(async { Ok(Box::pin(fut.await?) as _) })
}
}
type DynRuntime = dyn Runtime<
TcpStream = Pin<Box<dyn TcpStream>>,
ConnectTcpStream = Pin<Box<dyn Future<Output = io::Result<Pin<Box<dyn TcpStream>>>>>>,
>;
thread_local! {
static RUNTIME: Cell<Option<&'static DynRuntime>> = Cell::new(None);
}
#[inline]
pub fn current_runtime() -> &'static DynRuntime {
RUNTIME.with(|r| r.get().expect("the runtime has not been set"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment