embedrs_bytes/buf/
writer.rs

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