I have a function that looks like:
pub async fn read_timeout(stream: &mut TcpStream, buffer: &mut [u8], timeout_secs: u64) -> Result<usize, IoError> {
let duration = Duration::from_secs(timeout_secs);
match timeout(duration, stream.read(buffer)).await {
Ok(result) => match result {
Ok(read_length) => Ok(read_length),
Err(error) => Err(error),
},
Err(error) => Err(IoError::new(ErrorKind::TimedOut, error)),
}
}
Now, I would like to extend this function to accept TcpStream
or File
, and maybe other types that implement the AsyncReadEx
trait:
pub async fn read_timeout(stream: &mut impl AsyncReadExt, buffer: &mut [u8], timeout_secs: u64) -> Result<usize, IoError> {
let duration = Duration::from_secs(timeout_secs);
match timeout(duration, stream.read(buffer)).await {
Ok(result) => match result {
Ok(read_length) => Ok(read_length),
Err(error) => Err(error),
},
Err(error) => Err(IoError::new(ErrorKind::TimedOut, error)),
}
}
But this does not compile!
It says that AsyncReadEx
does not implement Unpin
and that I'm supposed to use the pin!
macro or Box::pin()
. But I don't know how to use the pin!
macro. The examples haven't really been helpful for my situation. I also tried using Box::pin()
, but this still does not work:
pub async fn read_timeout(stream: &mut impl AsyncReadExt, buffer: &mut [u8], timeout_secs: u64) -> Result<usize, IoError> {
let duration = Duration::from_secs(timeout_secs);
let pinned_stream = Box::pin(stream);
match timeout(duration, pinned_stream.read(buffer)).await {
Ok(result) => match result {
Ok(read_length) => Ok(read_length),
Err(error) => Err(error),
},
Err(error) => Err(IoError::new(ErrorKind::TimedOut, error)),
}
}
Any hints would be very welcome!