]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/util.rs
Add a `std::io::read_to_string` function
[rust.git] / library / std / src / io / util.rs
1 #![allow(missing_copy_implementations)]
2
3 #[cfg(test)]
4 mod tests;
5
6 use crate::fmt;
7 use crate::io::{self, BufRead, Initializer, IoSlice, IoSliceMut, Read, Write};
8
9 /// A reader which is always at EOF.
10 ///
11 /// This struct is generally created by calling [`empty()`]. Please see
12 /// the documentation of [`empty()`] for more details.
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub struct Empty {
15     _priv: (),
16 }
17
18 /// Constructs a new handle to an empty reader.
19 ///
20 /// All reads from the returned reader will return [`Ok`]`(0)`.
21 ///
22 /// # Examples
23 ///
24 /// A slightly sad example of not reading anything into a buffer:
25 ///
26 /// ```
27 /// use std::io::{self, Read};
28 ///
29 /// let mut buffer = String::new();
30 /// io::empty().read_to_string(&mut buffer).unwrap();
31 /// assert!(buffer.is_empty());
32 /// ```
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
35 pub const fn empty() -> Empty {
36     Empty { _priv: () }
37 }
38
39 #[stable(feature = "rust1", since = "1.0.0")]
40 impl Read for Empty {
41     #[inline]
42     fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
43         Ok(0)
44     }
45
46     #[inline]
47     unsafe fn initializer(&self) -> Initializer {
48         Initializer::nop()
49     }
50 }
51 #[stable(feature = "rust1", since = "1.0.0")]
52 impl BufRead for Empty {
53     #[inline]
54     fn fill_buf(&mut self) -> io::Result<&[u8]> {
55         Ok(&[])
56     }
57     #[inline]
58     fn consume(&mut self, _n: usize) {}
59 }
60
61 #[stable(feature = "std_debug", since = "1.16.0")]
62 impl fmt::Debug for Empty {
63     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64         f.pad("Empty { .. }")
65     }
66 }
67
68 /// A reader which yields one byte over and over and over and over and over and...
69 ///
70 /// This struct is generally created by calling [`repeat()`]. Please
71 /// see the documentation of [`repeat()`] for more details.
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub struct Repeat {
74     byte: u8,
75 }
76
77 /// Creates an instance of a reader that infinitely repeats one byte.
78 ///
79 /// All reads from this reader will succeed by filling the specified buffer with
80 /// the given byte.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use std::io::{self, Read};
86 ///
87 /// let mut buffer = [0; 3];
88 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
89 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
90 /// ```
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
93 pub const fn repeat(byte: u8) -> Repeat {
94     Repeat { byte }
95 }
96
97 #[stable(feature = "rust1", since = "1.0.0")]
98 impl Read for Repeat {
99     #[inline]
100     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
101         for slot in &mut *buf {
102             *slot = self.byte;
103         }
104         Ok(buf.len())
105     }
106
107     #[inline]
108     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
109         let mut nwritten = 0;
110         for buf in bufs {
111             nwritten += self.read(buf)?;
112         }
113         Ok(nwritten)
114     }
115
116     #[inline]
117     fn is_read_vectored(&self) -> bool {
118         true
119     }
120
121     #[inline]
122     unsafe fn initializer(&self) -> Initializer {
123         Initializer::nop()
124     }
125 }
126
127 #[stable(feature = "std_debug", since = "1.16.0")]
128 impl fmt::Debug for Repeat {
129     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130         f.pad("Repeat { .. }")
131     }
132 }
133
134 /// A writer which will move data into the void.
135 ///
136 /// This struct is generally created by calling [`sink`]. Please
137 /// see the documentation of [`sink()`] for more details.
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct Sink {
140     _priv: (),
141 }
142
143 /// Creates an instance of a writer which will successfully consume all data.
144 ///
145 /// All calls to [`write`] on the returned instance will return `Ok(buf.len())`
146 /// and the contents of the buffer will not be inspected.
147 ///
148 /// [`write`]: Write::write
149 ///
150 /// # Examples
151 ///
152 /// ```rust
153 /// use std::io::{self, Write};
154 ///
155 /// let buffer = vec![1, 2, 3, 5, 8];
156 /// let num_bytes = io::sink().write(&buffer).unwrap();
157 /// assert_eq!(num_bytes, 5);
158 /// ```
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
161 pub const fn sink() -> Sink {
162     Sink { _priv: () }
163 }
164
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl Write for Sink {
167     #[inline]
168     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
169         Ok(buf.len())
170     }
171
172     #[inline]
173     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
174         let total_len = bufs.iter().map(|b| b.len()).sum();
175         Ok(total_len)
176     }
177
178     #[inline]
179     fn is_write_vectored(&self) -> bool {
180         true
181     }
182
183     #[inline]
184     fn flush(&mut self) -> io::Result<()> {
185         Ok(())
186     }
187 }
188
189 #[stable(feature = "write_mt", since = "1.48.0")]
190 impl Write for &Sink {
191     #[inline]
192     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
193         Ok(buf.len())
194     }
195
196     #[inline]
197     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
198         let total_len = bufs.iter().map(|b| b.len()).sum();
199         Ok(total_len)
200     }
201
202     #[inline]
203     fn is_write_vectored(&self) -> bool {
204         true
205     }
206
207     #[inline]
208     fn flush(&mut self) -> io::Result<()> {
209         Ok(())
210     }
211 }
212
213 #[stable(feature = "std_debug", since = "1.16.0")]
214 impl fmt::Debug for Sink {
215     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216         f.pad("Sink { .. }")
217     }
218 }