I wrote some thoughts about this topic. Would appreciate any correctness or your ideas!
What's wanted?
pub trait AsyncRead {
async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
}
async fn call(file: &mut dyn AsyncRead /* 👈 */) -> io::Result<usize> {
file.read(&mut vec![]).await
}
- call
async fn
in a trait object - no heap allocation on return value, i.e. no
-> Pin<Box<dyn ...>>
Send
and Sync
problems are not considered for now.
Summary
The code is in examples
folder:
# | file name | is directly dispatchable | no head allocated return value | extra description |
---|---|---|---|---|
1 | returns-box-trait-object.rs |
widely used; simple | ||
2 | returns-stack-future.rs |
simple; fixed allocation size but heap allocation as a fallback | ||
3 | returns-future-in-trait-with-supertrait.rs |
used in async-std ; the pattern is an inspiration |
||
4 | afit-with-supertrait.rs |
takes the inspiration above with AFIT | ||
5 | dynosaur.rs |
promising idea and APIs to support referenced erased types |