-
-
Save yoshuawuyts/daf2bcb1dfcbe6f2377e901103d536c1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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