cros_async: Add AsyncWrapper type

This makes it easier to implement IntoAsync for foreign types.

BUG=none
TEST=Use it in a later change

Change-Id: I070fe3b63ac7458e21fa38b3a1b1bdb318c44d5b
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/2891120
Tested-by: kokoro <noreply+kokoro@google.com>
Commit-Queue: Chirantan Ekbote <chirantan@chromium.org>
Reviewed-by: Noah Gold <nkgold@google.com>
Reviewed-by: Keiichi Watanabe <keiichiw@chromium.org>
This commit is contained in:
Chirantan Ekbote 2021-05-12 19:24:21 +09:00 committed by Commit Bot
parent d8e37614d9
commit d2399b7d6f
2 changed files with 41 additions and 2 deletions

View file

@ -16,7 +16,8 @@
//! `URingExecutor` documentation for an explaination of why.
use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::ops::{Deref, DerefMut};
use std::os::unix::io::{AsRawFd, RawFd};
use std::sync::Arc;
use async_trait::async_trait;
@ -119,6 +120,43 @@ impl IntoAsync for File {}
impl IntoAsync for UnixSeqpacket {}
impl IntoAsync for &UnixSeqpacket {}
/// Simple wrapper struct to implement IntoAsync on foreign types.
pub struct AsyncWrapper<T>(T);
impl<T> AsyncWrapper<T> {
/// Create a new `AsyncWrapper` that wraps `val`.
pub fn new(val: T) -> Self {
AsyncWrapper(val)
}
/// Consumes the `AsyncWrapper`, returning the inner struct.
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> Deref for AsyncWrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for AsyncWrapper<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T: AsRawFd> AsRawFd for AsyncWrapper<T> {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl<T: AsRawFd> IntoAsync for AsyncWrapper<T> {}
#[cfg(test)]
mod tests {
use std::fs::{File, OpenOptions};

View file

@ -77,7 +77,8 @@ pub use event::EventAsync;
pub use executor::Executor;
pub use fd_executor::FdExecutor;
pub use io_ext::{
Error as AsyncError, IntoAsync, IoSourceExt, ReadAsync, Result as AsyncResult, WriteAsync,
AsyncWrapper, Error as AsyncError, IntoAsync, IoSourceExt, ReadAsync, Result as AsyncResult,
WriteAsync,
};
pub use mem::{BackingMemory, MemRegion};
pub use poll_source::PollSource;