io: add AsyncFd::try_io() and try_io_mut() #6967
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This allows to provide APIs like
try_recv()
andtry_send()
in custom types built on top ofAsyncFd
.Closes #4719.
Motivation
Custom types built on top of
AsyncFd
may want to provide functions liketry_recv()
andtry_send()
. Currently, I don't think this can be done cleanly, because thepoll_[read|write]_ready()
functions will register the current task to be woken. They use the reserved waker slot, so they would interfere with other users ofpoll_{ready,write}_ready()
, such asAsyncRead
andAsyncWrite
implementations.I suppose you currently could poll the future from
{read,write}_ready()
once with a fake waker. But that is quite a hacky workaround, and if the future is not ready, the fake waker would actually be registered only to be removed again directly after the polling.Solution
Add
AsyncFd::try_io()
andAsyncFd::try_io_mut()
to mirror the API fromUnixDatagram
other sockets. There is a mut and non-mut version to allow mut or const access to the wrapped resource as required, just likeAsyncFd::async_io[_mut]()
.Example
To illustrate why this is useful, consider the current implementation of a
try_recv()
function:Or, if we have
try_io
:No unnecessary wakers being registered, no unsafe code to avoid Arcs in the waker.