dynify now has a macro for heapless async traits

50 points loichyan 3 comments

Hello, fellow Rustaceans!

dynify is another crate to make async traits dyn compatible. The main selling point is that dynify doesn't require async methods to return a boxed Future.

Recently, I added an attribute macro #[dynify] to make using dynify as straightforward as #[async_trait]. Basically, you only need to place #[dynify] to the target trait, and it will generate a dyn compatible variant for that trait:

#[dynify::dynify]
trait AsyncRead {
    async fn read_to_string(&mut self) -> String;
}

To invoke an async method, you need to choose where its return value is allocated, stack or heap:

async fn dynamic_dispatch(reader: &mut dyn DynAsyncRead) {
    let mut stack = [MaybeUninit::<u8>::uninit(); 16];
    let mut heap = Vec::<MaybeUninit<u8>>::new();
    // Initialize the trait object on the stack if not too large, otherwise the heap
    let fut = reader.read_to_string().init2(&mut stack, &mut heap);
    let content = fut.await;
    // ...
}