Search code examples
rustrust-tokio

Why does the implementation of AsyncRead on Box have an Unpin trait bound?


The implementation of AsyncRead (tokio) on Boxed types has the following signature:

impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T>

Why is Unpin required here by the trait bound? Why isn't the address stability ensured by Box enough?


Solution

  • Why is Unpin required here by the trait bound?

    Plain old Box<T> is not pinned, so any async operations it generates will require that the underlying T does not care about pinning (i.e. is Unpin).

    Why isn't the address stability ensured by Box enough?

    You can move or replace the object in a plain Box, which would break the stability guarantee. Pin does not allow mut access without unsafe, preventing the value from escaping.