#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(missing_docs)]
#![doc(test(attr(warn(unused))))]
#![allow(clippy::needless_question_mark)] #![allow(clippy::manual_range_contains)] #![allow(clippy::needless_borrows_for_generic_args)] #[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "std")]
mod bridge;
mod error;
mod macros;
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::vec::Vec;
use core::cmp;
#[cfg(feature = "std")]
pub use bridge::{FromStd, ToStd};
#[rustfmt::skip] pub use self::error::{Error, ErrorKind};
pub type Result<T> = core::result::Result<T, Error>;
pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
#[inline]
fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
while !buf.is_empty() {
match self.read(buf) {
Ok(0) => return Err(ErrorKind::UnexpectedEof.into()),
Ok(len) => buf = &mut buf[len..],
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
#[inline]
fn take(&mut self, limit: u64) -> Take<Self> { Take { reader: self, remaining: limit } }
#[doc(alias = "read_to_end")]
#[cfg(feature = "alloc")]
#[inline]
fn read_to_limit(&mut self, buf: &mut Vec<u8>, limit: u64) -> Result<usize> {
self.take(limit).read_to_end(buf)
}
}
pub trait BufRead: Read {
fn fill_buf(&mut self) -> Result<&[u8]>;
fn consume(&mut self, amount: usize);
}
pub struct Take<'a, R: Read + ?Sized> {
reader: &'a mut R,
remaining: u64,
}
impl<'a, R: Read + ?Sized> Take<'a, R> {
#[cfg(feature = "alloc")]
#[inline]
pub fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
let mut read: usize = 0;
let mut chunk = [0u8; 64];
loop {
match self.read(&mut chunk) {
Ok(0) => break,
Ok(n) => {
buf.extend_from_slice(&chunk[0..n]);
read += n;
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e),
};
}
Ok(read)
}
}
impl<'a, R: Read + ?Sized> Read for Take<'a, R> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let len = cmp::min(buf.len(), self.remaining.try_into().unwrap_or(buf.len()));
let read = self.reader.read(&mut buf[..len])?;
self.remaining -= read.try_into().unwrap_or(self.remaining);
Ok(read)
}
}
impl<'a, R: BufRead + ?Sized> BufRead for Take<'a, R> {
#[inline]
fn fill_buf(&mut self) -> Result<&[u8]> {
if self.remaining == 0 {
return Ok(&[]);
}
let buf = self.reader.fill_buf()?;
let cap = cmp::min(buf.len() as u64, self.remaining) as usize;
Ok(&buf[..cap])
}
#[inline]
fn consume(&mut self, amount: usize) {
assert!(amount as u64 <= self.remaining);
self.remaining -= amount as u64;
self.reader.consume(amount);
}
}
impl<T: Read> Read for &'_ mut T {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> { (**self).read(buf) }
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { (**self).read_exact(buf) }
}
impl<T: BufRead> BufRead for &'_ mut T {
#[inline]
fn fill_buf(&mut self) -> Result<&[u8]> { (**self).fill_buf() }
#[inline]
fn consume(&mut self, amount: usize) { (**self).consume(amount) }
}
impl Read for &[u8] {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let cnt = cmp::min(self.len(), buf.len());
buf[..cnt].copy_from_slice(&self[..cnt]);
*self = &self[cnt..];
Ok(cnt)
}
}
impl BufRead for &[u8] {
#[inline]
fn fill_buf(&mut self) -> Result<&[u8]> { Ok(self) }
#[inline]
fn consume(&mut self, amount: usize) { *self = &self[amount..] }
}
pub struct Cursor<T> {
inner: T,
pos: u64,
}
impl<T: AsRef<[u8]>> Cursor<T> {
#[inline]
pub fn new(inner: T) -> Self { Cursor { inner, pos: 0 } }
#[inline]
pub fn position(&self) -> u64 { self.pos }
#[inline]
pub fn set_position(&mut self, position: u64) { self.pos = position; }
#[inline]
pub fn into_inner(self) -> T { self.inner }
#[inline]
pub fn inner(&self) -> &T { &self.inner }
}
impl<T: AsRef<[u8]>> Read for Cursor<T> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let inner: &[u8] = self.inner.as_ref();
let start_pos = self.pos.try_into().unwrap_or(inner.len());
let read = core::cmp::min(inner.len().saturating_sub(start_pos), buf.len());
buf[..read].copy_from_slice(&inner[start_pos..start_pos + read]);
self.pos = self.pos.saturating_add(read.try_into().unwrap_or(u64::MAX ));
Ok(read)
}
}
impl<T: AsRef<[u8]>> BufRead for Cursor<T> {
#[inline]
fn fill_buf(&mut self) -> Result<&[u8]> {
let inner: &[u8] = self.inner.as_ref();
Ok(&inner[self.pos as usize..])
}
#[inline]
fn consume(&mut self, amount: usize) {
assert!(amount <= self.inner.as_ref().len());
self.pos += amount as u64;
}
}
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn flush(&mut self) -> Result<()>;
#[inline]
fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
while !buf.is_empty() {
match self.write(buf) {
Ok(0) => return Err(ErrorKind::UnexpectedEof.into()),
Ok(len) => buf = &buf[len..],
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
}
impl<T: Write> Write for &'_ mut T {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize> { (**self).write(buf) }
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<()> { (**self).write_all(buf) }
#[inline]
fn flush(&mut self) -> Result<()> { (**self).flush() }
}
#[cfg(feature = "alloc")]
impl Write for alloc::vec::Vec<u8> {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.extend_from_slice(buf);
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> Result<()> { Ok(()) }
}
impl<'a> Write for &'a mut [u8] {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let cnt = core::cmp::min(self.len(), buf.len());
self[..cnt].copy_from_slice(&buf[..cnt]);
*self = &mut core::mem::take(self)[cnt..];
Ok(cnt)
}
#[inline]
fn flush(&mut self) -> Result<()> { Ok(()) }
}
pub struct Sink;
impl Write for Sink {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize> { Ok(buf.len()) }
#[inline]
fn write_all(&mut self, _: &[u8]) -> Result<()> { Ok(()) }
#[inline]
fn flush(&mut self) -> Result<()> { Ok(()) }
}
#[inline]
pub fn sink() -> Sink { Sink }
#[cfg(feature = "std")]
#[inline]
pub const fn from_std<T>(std_io: T) -> FromStd<T> { FromStd::new(std_io) }
#[cfg(feature = "std")]
#[inline]
pub fn from_std_mut<T>(std_io: &mut T) -> &mut FromStd<T> { FromStd::new_mut(std_io) }
#[cfg(test)]
mod tests {
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{string::ToString, vec};
use super::*;
#[test]
fn buf_read_fill_and_consume_slice() {
let data = [0_u8, 1, 2];
let mut slice = &data[..];
let fill = BufRead::fill_buf(&mut slice).unwrap();
assert_eq!(fill.len(), 3);
assert_eq!(fill, &[0_u8, 1, 2]);
slice.consume(2);
let fill = BufRead::fill_buf(&mut slice).unwrap();
assert_eq!(fill.len(), 1);
assert_eq!(fill, &[2_u8]);
slice.consume(1);
let fill = BufRead::fill_buf(&mut slice).unwrap();
assert!(fill.is_empty());
}
#[test]
#[cfg(feature = "alloc")]
fn read_to_limit_greater_than_total_length() {
let s = "16-byte-string!!".to_string();
let mut reader = Cursor::new(&s);
let mut buf = vec![];
let read = reader.read_to_limit(&mut buf, 32).expect("failed to read to limit");
assert_eq!(read, s.len());
assert_eq!(&buf, s.as_bytes())
}
#[test]
#[cfg(feature = "alloc")]
fn read_to_limit_less_than_total_length() {
let s = "16-byte-string!!".to_string();
let mut reader = Cursor::new(&s);
let mut buf = vec![];
let read = reader.read_to_limit(&mut buf, 2).expect("failed to read to limit");
assert_eq!(read, 2);
assert_eq!(&buf, "16".as_bytes())
}
}