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