Skip to content

API to check whether we are inside a simulation#258

Merged
mcches merged 1 commit intotokio-rs:mainfrom
teskje:in_simulation
Jan 6, 2026
Merged

API to check whether we are inside a simulation#258
mcches merged 1 commit intotokio-rs:mainfrom
teskje:in_simulation

Conversation

@teskje
Copy link
Contributor

@teskje teskje commented Dec 24, 2025

This adds turmoil::in_simulation, an API that allows checking whether the caller is currently running inside a simulation.

The same information was already obtainable by turmoil::sim_elapsed().is_some(), but it seems good to have a less obscure way to do this.


For context, my reason for wanting this is that I have a TcpStream wrapper that supports both tokio and turmoil streams and decides which type to use at runtime. Roughly:

enum TcpStream {
    Tokio(tokio::net::TcpStream),
    Turmoil(turmoil::net::TcpStream),
}

impl TcpStream {
    async fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
        if turmoil::in_simulation() {
            turmoil::net::TcpStream::connect(addr).await.map(Self::Turmoil)
        } else {
            tokio::net::TcpStream::connect(addr).await.map(Self::Tokio)
        }
    }
}

This is for situations where I can't decide this at compile time, for example because I'm using turmoil in Rust tests and there are other tests in the same binary that want to use the tokio types instead.

Happy to discuss other ways of doing this, if folks have ideas!

Copy link
Contributor

@mcches mcches left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple alternatives...but the proposed is also Ok.

Option 1: Use try_current

pub fn in_simulation() -> bool {
    World::try_current(|_| ()).is_ok()
}

This uses the existing try_current method which already checks CURRENT.is_set() and returns a Result.

Option 2: Add a dedicated is_set() method to World

In src/world.rs:

pub(crate) fn is_set() -> bool {
    CURRENT.is_set()
}

Then in src/lib.rs:

pub fn in_simulation() -> bool {
    World::is_set()
}

@teskje
Copy link
Contributor Author

teskje commented Jan 5, 2026

Changed to option 1. I initially avoided this because I didn't like the additional overhead, but it's probably silly to worry about that here.

@teskje teskje requested a review from mcches January 5, 2026 09:51
@mcches mcches merged commit 9b30a84 into tokio-rs:main Jan 6, 2026
6 checks passed
@teskje teskje deleted the in_simulation branch January 9, 2026 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants