/rust/registry/src/index.crates.io-6f17d22bba15001f/bytes-1.10.1/src/buf/writer.rs
Line | Count | Source (jump to first uncovered line) |
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 | 0 | pub fn new<B>(buf: B) -> Writer<B> { |
16 | 0 | Writer { buf } |
17 | 0 | } |
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 | 0 | pub fn get_ref(&self) -> &B { |
34 | 0 | &self.buf |
35 | 0 | } |
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 | 0 | pub fn get_mut(&mut self) -> &mut B { |
53 | 0 | &mut self.buf |
54 | 0 | } |
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 | 0 | pub fn into_inner(self) -> B { |
73 | 0 | self.buf |
74 | 0 | } |
75 | | } |
76 | | |
77 | | impl<B: BufMut + Sized> io::Write for Writer<B> { |
78 | 0 | fn write(&mut self, src: &[u8]) -> io::Result<usize> { |
79 | 0 | let n = cmp::min(self.buf.remaining_mut(), src.len()); |
80 | 0 |
|
81 | 0 | self.buf.put_slice(&src[..n]); |
82 | 0 | Ok(n) |
83 | 0 | } |
84 | | |
85 | 0 | fn flush(&mut self) -> io::Result<()> { |
86 | 0 | Ok(()) |
87 | 0 | } |
88 | | } |