Skip to main content

streamparser/read/
mod.rs

1use core::{
2    pin::Pin,
3    task::{Context, Poll},
4};
5
6#[cfg(feature = "alloc")]
7mod read_source;
8#[cfg(feature = "alloc")]
9pub use read_source::*;
10
11/// A helper trait for stream input.
12///
13/// This trait is modeled on std's `Read`, but is separate so it's usable with `no_std`. When the
14/// `std` feature is enabled (it is by default), this trait has a blanket implementation for every
15/// type that implements std's `Read`.
16pub trait Read {
17    /// The error type returned by read operations.
18    type Error;
19
20    /// Read bytes into the provided buffer, up to its length, and return the number of bytes read.
21    ///
22    /// This function may read fewer bytes. If no more input is available, it should not modify the
23    /// buffer and merely return 0.
24    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;
25}
26
27/// Blanket implementation for `std::io::Read`.
28#[cfg(feature = "std")]
29impl<R: std::io::Read + ?Sized> Read for R {
30    type Error = std::io::Error;
31
32    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
33        self.read(buf)
34    }
35}
36
37/// A helper trait for async stream input.
38///
39/// This trait is modeled on `futures::io::AsyncRead`, but is separate so it's usable in `no_std`
40/// environments. When the `std` feature is enabled (it is by default), this trait has a blanket
41/// implementation for every type that implements `futures::io::AsyncRead`.
42pub trait AsyncRead {
43    /// The error type returned by read operations.
44    type Error;
45
46    /// Attempt to read bytes into the provided buffer.
47    ///
48    /// On success, returns `Poll::Ready` with the number of bytes read. This function may read
49    /// fewer bytes. If no data is available for reading, the method returns `Poll::Pending` and
50    /// arranges for the current task to receive a notification when the object becomes readable.
51    fn poll_read(
52        self: Pin<&mut Self>,
53        cx: &mut Context,
54        buf: &mut [u8],
55    ) -> Poll<Result<usize, Self::Error>>;
56}
57
58/// Blanket implementation for `futures::io::AsyncRead`.
59#[cfg(feature = "std")]
60impl<R: futures_io::AsyncRead + ?Sized> AsyncRead for R {
61    type Error = futures_io::Error;
62
63    fn poll_read(
64        self: Pin<&mut Self>,
65        cx: &mut Context,
66        buf: &mut [u8],
67    ) -> Poll<Result<usize, Self::Error>> {
68        self.poll_read(cx, buf)
69    }
70}