bytes_expand/buf/
reader.rs

1use {Buf};
2
3use 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)]
11pub struct Reader<B> {
12    buf: B,
13}
14
15pub fn new<B>(buf: B) -> Reader<B> {
16    Reader { buf: buf }
17}
18
19impl<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    /// use std::io::{self, Cursor};
29    ///
30    /// let mut buf = Cursor::new(b"hello world").reader();
31    ///
32    /// assert_eq!(0, buf.get_ref().position());
33    /// ```
34    pub fn get_ref(&self) -> &B {
35        &self.buf
36    }
37
38    /// Gets a mutable reference to the underlying `Buf`.
39    ///
40    /// It is inadvisable to directly read from the underlying `Buf`.
41    ///
42    /// # Examples
43    ///
44    /// ```rust
45    /// use bytes::Buf;
46    /// use std::io::{self, Cursor};
47    ///
48    /// let mut buf = Cursor::new(b"hello world").reader();
49    /// let mut dst = vec![];
50    ///
51    /// buf.get_mut().set_position(2);
52    /// io::copy(&mut buf, &mut dst).unwrap();
53    ///
54    /// assert_eq!(*dst, b"llo world"[..]);
55    /// ```
56    pub fn get_mut(&mut self) -> &mut B {
57        &mut self.buf
58    }
59
60    /// Consumes this `Reader`, returning the underlying value.
61    ///
62    /// # Examples
63    ///
64    /// ```rust
65    /// use bytes::Buf;
66    /// use std::io::{self, Cursor};
67    ///
68    /// let mut buf = Cursor::new(b"hello world").reader();
69    /// let mut dst = vec![];
70    ///
71    /// io::copy(&mut buf, &mut dst).unwrap();
72    ///
73    /// let buf = buf.into_inner();
74    /// assert_eq!(0, buf.remaining());
75    /// ```
76    pub fn into_inner(self) -> B {
77        self.buf
78    }
79}
80
81impl<B: Buf + Sized> io::Read for Reader<B> {
82    fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
83        let len = cmp::min(self.buf.remaining(), dst.len());
84
85        Buf::copy_to_slice(&mut self.buf, &mut dst[0..len]);
86        Ok(len)
87    }
88}
89
90impl<B: Buf + Sized> io::BufRead for Reader<B> {
91    fn fill_buf(&mut self) -> io::Result<&[u8]> {
92        Ok(self.buf.bytes())
93    }
94    fn consume(&mut self, amt: usize) {
95        self.buf.advance(amt)
96    }
97}