1

I'm using futures 0.3 and I would like to use a single trait that is implemented for both async scenarios and synchronous ones:

trait Testy {
    type FutType: Future<Output = i32>;

    fn stuff(&self) -> Self::FutType;
}

pub struct TestyImp;
impl Testy for TestyImp {
    type FutType = Ready<i32>;

    fn stuff(&self) -> Self::FutType {
        ready(3)
    }
}

How do I get from the Rust compiler's evaluation of .await on this Ready future back into the runtime (i.e. Tokio)? Was I able to get straight to a poll call with an immediate result from a stack-based future state machine, or did it cost me something along the way? Did the use of Ready introduce:

  • heap allocations?
  • a path through a chain of non-inlined function calls in the runtime?
  • a run through an event loop?
  • a thread context switch? (not synchronously scheduled is how I would think of this from a C# perspective)

Let's assume an intelligently designed runtime, or just assume Tokio if the answer is particularly dependent on it.

I've spent a lot of time in C# where we have ValueTask and Task. ValueTask provides two major advantages: an already completed value that can be on the stack, and no entry into task runtime overhead when awaited with a preexisting value. Hopefully that helps explain the motivation of my question.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Eric
  • 33
  • 2
  • Please read [What is the purpose of async/await in Rust?](https://stackoverflow.com/q/52835725/155423). Calling `.await` in an async block/function really only creates a new anonymous type that implements `Future`. No event loop or threads are involved from `.await`. – Shepmaster Jul 22 '19 at 22:49
  • So my mistake was thinking anything ever went back to the runtime with await, I see. That drastically simplifies my understanding. Thanks! That eliminates 90% of my question, happy to accept that. – Eric Jul 22 '19 at 23:15
  • What is the remaining 10%? You may want to think about rewriting your question to focus on that 10%, linking to any existing resources (like the previously linked question) that you need to to frame your question. – Shepmaster Jul 22 '19 at 23:21
  • Sorry, i mean you answered the 10%, 'How do i get from the Rust compiler's evaluation of .await...' and made the other 90% unapplicable. – Eric Jul 22 '19 at 23:24
  • Do you feel like this question has been suitably answered by the previously linked question? In that case, we can mark this as a duplicate. – Shepmaster Jul 22 '19 at 23:25

0 Answers0