mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-24 08:22:59 +01:00
52 lines
1.3 KiB
Rust
52 lines
1.3 KiB
Rust
|
use std::{io, cmp};
|
||
|
use std::io::{Read, Write};
|
||
|
use bytes::{Buf, Bytes};
|
||
|
use futures::Poll;
|
||
|
use tokio_io::{AsyncRead, AsyncWrite};
|
||
|
|
||
|
|
||
|
struct IoWrapper<T> {
|
||
|
unread: Option<Bytes>,
|
||
|
inner: T,
|
||
|
}
|
||
|
|
||
|
impl<T: Read> Read for IoWrapper<T> {
|
||
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||
|
if let Some(mut bytes) = self.unread.take() {
|
||
|
let size = cmp::min(buf.len(), bytes.len());
|
||
|
buf.copy_from_slice(&bytes[..size]);
|
||
|
bytes.split_to(size);
|
||
|
if !bytes.is_empty() {
|
||
|
self.unread = Some(bytes);
|
||
|
}
|
||
|
Ok(size)
|
||
|
} else {
|
||
|
self.inner.read(buf)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T: Write> Write for IoWrapper<T> {
|
||
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||
|
self.inner.write(buf)
|
||
|
}
|
||
|
fn flush(&mut self) -> io::Result<()> {
|
||
|
self.inner.flush()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T: AsyncRead + 'static> AsyncRead for IoWrapper<T> {
|
||
|
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
|
||
|
self.inner.prepare_uninitialized_buffer(buf)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T: AsyncWrite + 'static> AsyncWrite for IoWrapper<T> {
|
||
|
fn shutdown(&mut self) -> Poll<(), io::Error> {
|
||
|
self.inner.shutdown()
|
||
|
}
|
||
|
fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
|
||
|
self.inner.write_buf(buf)
|
||
|
}
|
||
|
}
|