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