1#[cfg(feature = "alloc")]
2use alloc::{boxed::Box, collections::VecDeque, vec::Vec};
3use core::{cmp, fmt, io::BorrowedCursor, mem};
4
5use crate::{Error, Result, Write};
6
7impl<W: Write + ?Sized> Write for &mut W {
11 #[inline]
12 fn write(&mut self, buf: &[u8]) -> Result<usize> {
13 (**self).write(buf)
14 }
15
16 #[inline]
17 fn flush(&mut self) -> Result<()> {
18 (**self).flush()
19 }
20
21 #[inline]
22 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
23 (**self).write_all(buf)
24 }
25
26 #[inline]
27 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
28 (**self).write_fmt(fmt)
29 }
30}
31
32#[cfg(feature = "alloc")]
33impl<W: Write + ?Sized> Write for Box<W> {
34 #[inline]
35 fn write(&mut self, buf: &[u8]) -> Result<usize> {
36 (**self).write(buf)
37 }
38
39 #[inline]
40 fn flush(&mut self) -> Result<()> {
41 (**self).flush()
42 }
43
44 #[inline]
45 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
46 (**self).write_all(buf)
47 }
48
49 #[inline]
50 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
51 (**self).write_fmt(fmt)
52 }
53}
54
55impl Write for &mut [u8] {
59 #[inline]
60 fn write(&mut self, data: &[u8]) -> Result<usize> {
61 let amt = cmp::min(data.len(), self.len());
62 let (a, b) = mem::take(self).split_at_mut(amt);
63 a.copy_from_slice(&data[..amt]);
64 *self = b;
65 Ok(amt)
66 }
67
68 #[inline]
69 fn flush(&mut self) -> Result<()> {
70 Ok(())
71 }
72
73 #[inline]
74 fn write_all(&mut self, data: &[u8]) -> Result<()> {
75 if self.write(data)? < data.len() {
76 Err(Error::WriteZero)
77 } else {
78 Ok(())
79 }
80 }
81}
82
83#[cfg(feature = "alloc")]
84impl Write for Vec<u8> {
85 #[inline]
86 fn write(&mut self, buf: &[u8]) -> Result<usize> {
87 self.extend_from_slice(buf);
88 Ok(buf.len())
89 }
90
91 #[inline]
92 fn flush(&mut self) -> Result<()> {
93 Ok(())
94 }
95
96 #[inline]
97 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
98 self.extend_from_slice(buf);
99 Ok(())
100 }
101}
102
103#[cfg(feature = "alloc")]
104impl Write for VecDeque<u8> {
105 #[inline]
106 fn write(&mut self, buf: &[u8]) -> Result<usize> {
107 self.extend(buf);
108 Ok(buf.len())
109 }
110
111 #[inline]
112 fn flush(&mut self) -> Result<()> {
113 Ok(())
114 }
115
116 #[inline]
117 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
118 self.extend(buf);
119 Ok(())
120 }
121}
122
123impl Write for BorrowedCursor<'_> {
124 #[inline]
125 fn write(&mut self, buf: &[u8]) -> Result<usize> {
126 let amt = cmp::min(buf.len(), self.capacity());
127 self.append(&buf[..amt]);
128 Ok(amt)
129 }
130
131 #[inline]
132 fn flush(&mut self) -> Result<()> {
133 Ok(())
134 }
135
136 #[inline]
137 fn write_all(&mut self, buf: &[u8]) -> Result<()> {
138 if self.write(buf)? < buf.len() {
139 Err(Error::WriteZero)
140 } else {
141 Ok(())
142 }
143 }
144}