• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::Buf;
2 
3 use std::{cmp, io};
4 
5 /// A `Buf` adapter which implements `io::Read` for the inner value.
6 ///
7 /// This struct is generally created by calling `reader()` on `Buf`. See
8 /// documentation of [`reader()`](trait.Buf.html#method.reader) for more
9 /// details.
10 #[derive(Debug)]
11 pub struct Reader<B> {
12     buf: B,
13 }
14 
new<B>(buf: B) -> Reader<B>15 pub fn new<B>(buf: B) -> Reader<B> {
16     Reader { buf }
17 }
18 
19 impl<B: Buf> Reader<B> {
20     /// Gets a reference to the underlying `Buf`.
21     ///
22     /// It is inadvisable to directly read from the underlying `Buf`.
23     ///
24     /// # Examples
25     ///
26     /// ```rust
27     /// use bytes::Buf;
28     ///
29     /// let buf = b"hello world".reader();
30     ///
31     /// assert_eq!(b"hello world", buf.get_ref());
32     /// ```
get_ref(&self) -> &B33     pub fn get_ref(&self) -> &B {
34         &self.buf
35     }
36 
37     /// Gets a mutable reference to the underlying `Buf`.
38     ///
39     /// It is inadvisable to directly read from the underlying `Buf`.
get_mut(&mut self) -> &mut B40     pub fn get_mut(&mut self) -> &mut B {
41         &mut self.buf
42     }
43 
44     /// Consumes this `Reader`, returning the underlying value.
45     ///
46     /// # Examples
47     ///
48     /// ```rust
49     /// use bytes::Buf;
50     /// use std::io;
51     ///
52     /// let mut buf = b"hello world".reader();
53     /// let mut dst = vec![];
54     ///
55     /// io::copy(&mut buf, &mut dst).unwrap();
56     ///
57     /// let buf = buf.into_inner();
58     /// assert_eq!(0, buf.remaining());
59     /// ```
into_inner(self) -> B60     pub fn into_inner(self) -> B {
61         self.buf
62     }
63 }
64 
65 impl<B: Buf + Sized> io::Read for Reader<B> {
read(&mut self, dst: &mut [u8]) -> io::Result<usize>66     fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
67         let len = cmp::min(self.buf.remaining(), dst.len());
68 
69         Buf::copy_to_slice(&mut self.buf, &mut dst[0..len]);
70         Ok(len)
71     }
72 }
73 
74 impl<B: Buf + Sized> io::BufRead for Reader<B> {
fill_buf(&mut self) -> io::Result<&[u8]>75     fn fill_buf(&mut self) -> io::Result<&[u8]> {
76         Ok(self.buf.chunk())
77     }
consume(&mut self, amt: usize)78     fn consume(&mut self, amt: usize) {
79         self.buf.advance(amt)
80     }
81 }
82