use std::{io, task::Poll};
use bytes::{Buf, BytesMut};
use crate::io::AsyncIoRead;
pub trait AsyncBufRead {
fn poll_read_fill(&mut self, cx: &mut std::task::Context) -> Poll<io::Result<usize>>;
fn chunk(&self) -> &[u8];
fn consume(&mut self, cnt: usize);
}
impl<T: AsyncBufRead> AsyncBufRead for &mut T {
fn poll_read_fill(&mut self, cx: &mut std::task::Context) -> Poll<io::Result<usize>> {
T::poll_read_fill(self, cx)
}
fn chunk(&self) -> &[u8] {
T::chunk(self)
}
fn consume(&mut self, cnt: usize) {
T::consume(self, cnt);
}
}
#[derive(Debug)]
pub struct BufReader<IO> {
io: IO,
buf: BytesMut,
}
impl<IO> BufReader<IO> {
#[inline]
pub fn new(io: IO) -> Self {
Self { io, buf: BytesMut::new() }
}
#[inline]
pub fn with_capacity(io: IO, capacity: usize) -> Self {
Self { io, buf: BytesMut::with_capacity(capacity) }
}
}
impl<IO> AsyncBufRead for BufReader<IO>
where
IO: AsyncIoRead
{
#[inline]
fn poll_read_fill(&mut self, cx: &mut std::task::Context) -> Poll<io::Result<usize>> {
self.io.poll_read_buf(&mut self.buf, cx)
}
#[inline]
fn chunk(&self) -> &[u8] {
&self.buf
}
#[inline]
fn consume(&mut self, cnt: usize) {
self.buf.advance(cnt);
}
}