Skip to content
This repository was archived by the owner on Aug 12, 2022. It is now read-only.
This repository was archived by the owner on Aug 12, 2022. It is now read-only.

Implement Environment for real tokio runtime #11

@LegNeato

Description

@LegNeato

I want to make my functions generic over an Environment. I can do that over the runtimes in this crate but when I pass in the real tokio runtime I cannot due to orphan rules. If I wrap and implement, I get that Environment requires Clone and tokio::runtime::Runtime does not implement it.

I ended up doing this (not sure if I need Mutex or not, I guess not because Runtime is Send and Sync):

/// A runtime that uses real network and clock.
#[derive(Clone)]
pub struct RealRuntime(Arc<tokio::runtime::Runtime>);

#[async_trait]
impl Environment for RealRuntime {
    type TcpStream = tokio::net::TcpStream;
    type TcpListener = tokio::net::TcpListener;

    fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        self.0.clone().spawn(future);
    }
    fn now(&self) -> std::time::Instant {
        std::time::Instant::now()
    }
    fn delay(&self, deadline: std::time::Instant) -> tokio::timer::Delay {
        tokio::timer::delay(deadline)
    }
    fn timeout<T>(&self, value: T, timeout: std::time::Duration) -> tokio::timer::Timeout<T> {
        tokio::timer::Timeout::new(value, timeout)
    }
    async fn bind<A>(&self, addr: A) -> std::io::Result<Self::TcpListener>
    where
        A: Into<std::net::SocketAddr> + Send + Sync,
    {
        tokio::net::TcpListener::bind(&addr.into()).await
    }

    async fn connect<A>(&self, addr: A) -> std::io::Result<Self::TcpStream>
    where
        A: Into<std::net::SocketAddr> + Send + Sync,
    {
        tokio::net::TcpStream::connect(&addr.into()).await
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions