]>
Commit | Line | Data |
---|---|---|
85aaf69f | 1 | //! Traits, helpers, and type definitions for core I/O functionality. |
c1a9b12d SL |
2 | //! |
3 | //! The `std::io` module contains a number of common things you'll need | |
4 | //! when doing input and output. The most core part of this module is | |
c30ab7b3 | 5 | //! the [`Read`] and [`Write`] traits, which provide the |
c1a9b12d SL |
6 | //! most general interface for reading and writing input and output. |
7 | //! | |
781aab86 | 8 | //! ## Read and Write |
c1a9b12d | 9 | //! |
c30ab7b3 | 10 | //! Because they are traits, [`Read`] and [`Write`] are implemented by a number |
b039eaaf SL |
11 | //! of other types, and you can implement them for your types too. As such, |
12 | //! you'll see a few different types of I/O throughout the documentation in | |
c30ab7b3 | 13 | //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For |
cc61c64b | 14 | //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on |
3b2f2976 | 15 | //! [`File`]s: |
c1a9b12d | 16 | //! |
0531ce1d | 17 | //! ```no_run |
c1a9b12d SL |
18 | //! use std::io; |
19 | //! use std::io::prelude::*; | |
20 | //! use std::fs::File; | |
21 | //! | |
0531ce1d XL |
22 | //! fn main() -> io::Result<()> { |
23 | //! let mut f = File::open("foo.txt")?; | |
24 | //! let mut buffer = [0; 10]; | |
c1a9b12d | 25 | //! |
0531ce1d | 26 | //! // read up to 10 bytes |
532ac7d7 | 27 | //! let n = f.read(&mut buffer)?; |
c1a9b12d | 28 | //! |
532ac7d7 | 29 | //! println!("The bytes: {:?}", &buffer[..n]); |
0531ce1d XL |
30 | //! Ok(()) |
31 | //! } | |
c1a9b12d SL |
32 | //! ``` |
33 | //! | |
c30ab7b3 | 34 | //! [`Read`] and [`Write`] are so important, implementors of the two traits have a |
c1a9b12d | 35 | //! nickname: readers and writers. So you'll sometimes see 'a reader' instead |
c30ab7b3 | 36 | //! of 'a type that implements the [`Read`] trait'. Much easier! |
c1a9b12d SL |
37 | //! |
38 | //! ## Seek and BufRead | |
39 | //! | |
c30ab7b3 SL |
40 | //! Beyond that, there are two important traits that are provided: [`Seek`] |
41 | //! and [`BufRead`]. Both of these build on top of a reader to control | |
42 | //! how the reading happens. [`Seek`] lets you control where the next byte is | |
c1a9b12d SL |
43 | //! coming from: |
44 | //! | |
0531ce1d | 45 | //! ```no_run |
c1a9b12d SL |
46 | //! use std::io; |
47 | //! use std::io::prelude::*; | |
48 | //! use std::io::SeekFrom; | |
49 | //! use std::fs::File; | |
50 | //! | |
0531ce1d XL |
51 | //! fn main() -> io::Result<()> { |
52 | //! let mut f = File::open("foo.txt")?; | |
53 | //! let mut buffer = [0; 10]; | |
c1a9b12d | 54 | //! |
0531ce1d XL |
55 | //! // skip to the last 10 bytes of the file |
56 | //! f.seek(SeekFrom::End(-10))?; | |
c1a9b12d | 57 | //! |
0531ce1d | 58 | //! // read up to 10 bytes |
532ac7d7 | 59 | //! let n = f.read(&mut buffer)?; |
c1a9b12d | 60 | //! |
532ac7d7 | 61 | //! println!("The bytes: {:?}", &buffer[..n]); |
0531ce1d XL |
62 | //! Ok(()) |
63 | //! } | |
c1a9b12d SL |
64 | //! ``` |
65 | //! | |
c30ab7b3 | 66 | //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but |
c1a9b12d SL |
67 | //! to show it off, we'll need to talk about buffers in general. Keep reading! |
68 | //! | |
69 | //! ## BufReader and BufWriter | |
70 | //! | |
71 | //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be | |
72 | //! making near-constant calls to the operating system. To help with this, | |
c30ab7b3 | 73 | //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap |
c1a9b12d SL |
74 | //! readers and writers. The wrapper uses a buffer, reducing the number of |
75 | //! calls and providing nicer methods for accessing exactly what you want. | |
76 | //! | |
c30ab7b3 | 77 | //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra |
c1a9b12d SL |
78 | //! methods to any reader: |
79 | //! | |
0531ce1d | 80 | //! ```no_run |
c1a9b12d SL |
81 | //! use std::io; |
82 | //! use std::io::prelude::*; | |
83 | //! use std::io::BufReader; | |
84 | //! use std::fs::File; | |
85 | //! | |
0531ce1d XL |
86 | //! fn main() -> io::Result<()> { |
87 | //! let f = File::open("foo.txt")?; | |
88 | //! let mut reader = BufReader::new(f); | |
89 | //! let mut buffer = String::new(); | |
c1a9b12d | 90 | //! |
0531ce1d XL |
91 | //! // read a line into buffer |
92 | //! reader.read_line(&mut buffer)?; | |
c1a9b12d | 93 | //! |
5e7ed085 | 94 | //! println!("{buffer}"); |
0531ce1d XL |
95 | //! Ok(()) |
96 | //! } | |
c1a9b12d SL |
97 | //! ``` |
98 | //! | |
c30ab7b3 | 99 | //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call |
cc61c64b | 100 | //! to [`write`][`Write::write`]: |
c1a9b12d | 101 | //! |
0531ce1d | 102 | //! ```no_run |
c1a9b12d SL |
103 | //! use std::io; |
104 | //! use std::io::prelude::*; | |
105 | //! use std::io::BufWriter; | |
106 | //! use std::fs::File; | |
107 | //! | |
0531ce1d XL |
108 | //! fn main() -> io::Result<()> { |
109 | //! let f = File::create("foo.txt")?; | |
110 | //! { | |
111 | //! let mut writer = BufWriter::new(f); | |
c1a9b12d | 112 | //! |
0531ce1d XL |
113 | //! // write a byte to the buffer |
114 | //! writer.write(&[42])?; | |
c1a9b12d | 115 | //! |
0531ce1d | 116 | //! } // the buffer is flushed once writer goes out of scope |
c1a9b12d | 117 | //! |
0531ce1d XL |
118 | //! Ok(()) |
119 | //! } | |
c1a9b12d SL |
120 | //! ``` |
121 | //! | |
c1a9b12d SL |
122 | //! ## Standard input and output |
123 | //! | |
124 | //! A very common source of input is standard input: | |
125 | //! | |
0531ce1d | 126 | //! ```no_run |
c1a9b12d SL |
127 | //! use std::io; |
128 | //! | |
0531ce1d XL |
129 | //! fn main() -> io::Result<()> { |
130 | //! let mut input = String::new(); | |
c1a9b12d | 131 | //! |
0531ce1d | 132 | //! io::stdin().read_line(&mut input)?; |
c1a9b12d | 133 | //! |
0531ce1d XL |
134 | //! println!("You typed: {}", input.trim()); |
135 | //! Ok(()) | |
136 | //! } | |
c1a9b12d SL |
137 | //! ``` |
138 | //! | |
3b2f2976 | 139 | //! Note that you cannot use the [`?` operator] in functions that do not return |
94b46f34 | 140 | //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`] |
3b2f2976 | 141 | //! or `match` on the return value to catch any possible errors: |
cc61c64b | 142 | //! |
0531ce1d | 143 | //! ```no_run |
cc61c64b XL |
144 | //! use std::io; |
145 | //! | |
146 | //! let mut input = String::new(); | |
147 | //! | |
148 | //! io::stdin().read_line(&mut input).unwrap(); | |
149 | //! ``` | |
150 | //! | |
c1a9b12d SL |
151 | //! And a very common source of output is standard output: |
152 | //! | |
0531ce1d | 153 | //! ```no_run |
c1a9b12d SL |
154 | //! use std::io; |
155 | //! use std::io::prelude::*; | |
156 | //! | |
0531ce1d XL |
157 | //! fn main() -> io::Result<()> { |
158 | //! io::stdout().write(&[42])?; | |
159 | //! Ok(()) | |
160 | //! } | |
c1a9b12d SL |
161 | //! ``` |
162 | //! | |
cc61c64b | 163 | //! Of course, using [`io::stdout`] directly is less common than something like |
c30ab7b3 | 164 | //! [`println!`]. |
c1a9b12d SL |
165 | //! |
166 | //! ## Iterator types | |
167 | //! | |
168 | //! A large number of the structures provided by `std::io` are for various | |
c30ab7b3 | 169 | //! ways of iterating over I/O. For example, [`Lines`] is used to split over |
c1a9b12d SL |
170 | //! lines: |
171 | //! | |
0531ce1d | 172 | //! ```no_run |
c1a9b12d SL |
173 | //! use std::io; |
174 | //! use std::io::prelude::*; | |
175 | //! use std::io::BufReader; | |
176 | //! use std::fs::File; | |
177 | //! | |
0531ce1d XL |
178 | //! fn main() -> io::Result<()> { |
179 | //! let f = File::open("foo.txt")?; | |
180 | //! let reader = BufReader::new(f); | |
c1a9b12d | 181 | //! |
0531ce1d XL |
182 | //! for line in reader.lines() { |
183 | //! println!("{}", line?); | |
184 | //! } | |
185 | //! Ok(()) | |
c1a9b12d | 186 | //! } |
c1a9b12d SL |
187 | //! ``` |
188 | //! | |
189 | //! ## Functions | |
190 | //! | |
a7813a04 | 191 | //! There are a number of [functions][functions-list] that offer access to various |
c1a9b12d SL |
192 | //! features. For example, we can use three of these functions to copy everything |
193 | //! from standard input to standard output: | |
194 | //! | |
0531ce1d | 195 | //! ```no_run |
c1a9b12d SL |
196 | //! use std::io; |
197 | //! | |
0531ce1d XL |
198 | //! fn main() -> io::Result<()> { |
199 | //! io::copy(&mut io::stdin(), &mut io::stdout())?; | |
200 | //! Ok(()) | |
201 | //! } | |
c1a9b12d SL |
202 | //! ``` |
203 | //! | |
a7813a04 | 204 | //! [functions-list]: #functions-1 |
c1a9b12d SL |
205 | //! |
206 | //! ## io::Result | |
207 | //! | |
c30ab7b3 | 208 | //! Last, but certainly not least, is [`io::Result`]. This type is used |
c1a9b12d SL |
209 | //! as the return type of many `std::io` functions that can cause an error, and |
210 | //! can be returned from your own functions as well. Many of the examples in this | |
32a655c1 | 211 | //! module use the [`?` operator]: |
c1a9b12d SL |
212 | //! |
213 | //! ``` | |
214 | //! use std::io; | |
215 | //! | |
216 | //! fn read_input() -> io::Result<()> { | |
217 | //! let mut input = String::new(); | |
218 | //! | |
32a655c1 | 219 | //! io::stdin().read_line(&mut input)?; |
c1a9b12d SL |
220 | //! |
221 | //! println!("You typed: {}", input.trim()); | |
222 | //! | |
223 | //! Ok(()) | |
224 | //! } | |
225 | //! ``` | |
226 | //! | |
c30ab7b3 SL |
227 | //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very |
228 | //! common type for functions which don't have a 'real' return value, but do want to | |
229 | //! return errors if they happen. In this case, the only purpose of this function is | |
b039eaaf | 230 | //! to read the line and print it, so we use `()`. |
c1a9b12d | 231 | //! |
9cc50fc6 SL |
232 | //! ## Platform-specific behavior |
233 | //! | |
234 | //! Many I/O functions throughout the standard library are documented to indicate | |
235 | //! what various library or syscalls they are delegated to. This is done to help | |
236 | //! applications both understand what's happening under the hood as well as investigate | |
237 | //! any possibly unclear semantics. Note, however, that this is informative, not a binding | |
238 | //! contract. The implementation of many of these functions are subject to change over | |
239 | //! time and may call fewer or more syscalls/library functions. | |
c30ab7b3 | 240 | //! |
781aab86 FG |
241 | //! ## I/O Safety |
242 | //! | |
243 | //! Rust follows an I/O safety discipline that is comparable to its memory safety discipline. This | |
244 | //! means that file descriptors can be *exclusively owned*. (Here, "file descriptor" is meant to | |
245 | //! subsume similar concepts that exist across a wide range of operating systems even if they might | |
246 | //! use a different name, such as "handle".) An exclusively owned file descriptor is one that no | |
247 | //! other code is allowed to access in any way, but the owner is allowed to access and even close | |
248 | //! it any time. A type that owns its file descriptor should usually close it in its `drop` | |
249 | //! function. Types like [`File`] own their file descriptor. Similarly, file descriptors | |
250 | //! can be *borrowed*, granting the temporary right to perform operations on this file descriptor. | |
251 | //! This indicates that the file descriptor will not be closed for the lifetime of the borrow, but | |
252 | //! it does *not* imply any right to close this file descriptor, since it will likely be owned by | |
253 | //! someone else. | |
254 | //! | |
255 | //! The platform-specific parts of the Rust standard library expose types that reflect these | |
256 | //! concepts, see [`os::unix`] and [`os::windows`]. | |
257 | //! | |
258 | //! To uphold I/O safety, it is crucial that no code acts on file descriptors it does not own or | |
259 | //! borrow, and no code closes file descriptors it does not own. In other words, a safe function | |
260 | //! that takes a regular integer, treats it as a file descriptor, and acts on it, is *unsound*. | |
261 | //! | |
262 | //! Not upholding I/O safety and acting on a file descriptor without proof of ownership can lead to | |
263 | //! misbehavior and even Undefined Behavior in code that relies on ownership of its file | |
264 | //! descriptors: a closed file descriptor could be re-allocated, so the original owner of that file | |
265 | //! descriptor is now working on the wrong file. Some code might even rely on fully encapsulating | |
266 | //! its file descriptors with no operations being performed by any other part of the program. | |
267 | //! | |
268 | //! Note that exclusive ownership of a file descriptor does *not* imply exclusive ownership of the | |
269 | //! underlying kernel object that the file descriptor references (also called "file description" on | |
270 | //! some operating systems). File descriptors basically work like [`Arc`]: when you receive an owned | |
271 | //! file descriptor, you cannot know whether there are any other file descriptors that reference the | |
272 | //! same kernel object. However, when you create a new kernel object, you know that you are holding | |
273 | //! the only reference to it. Just be careful not to lend it to anyone, since they can obtain a | |
274 | //! clone and then you can no longer know what the reference count is! In that sense, [`OwnedFd`] is | |
275 | //! like `Arc` and [`BorrowedFd<'a>`] is like `&'a Arc` (and similar for the Windows types). In | |
276 | //! particular, given a `BorrowedFd<'a>`, you are not allowed to close the file descriptor -- just | |
277 | //! like how, given a `&'a Arc`, you are not allowed to decrement the reference count and | |
278 | //! potentially free the underlying object. There is no equivalent to `Box` for file descriptors in | |
279 | //! the standard library (that would be a type that guarantees that the reference count is `1`), | |
280 | //! however, it would be possible for a crate to define a type with those semantics. | |
281 | //! | |
3dfed10e XL |
282 | //! [`File`]: crate::fs::File |
283 | //! [`TcpStream`]: crate::net::TcpStream | |
3dfed10e XL |
284 | //! [`io::stdout`]: stdout |
285 | //! [`io::Result`]: self::Result | |
0731742a | 286 | //! [`?` operator]: ../../book/appendix-02-operators.html |
3dfed10e XL |
287 | //! [`Result`]: crate::result::Result |
288 | //! [`.unwrap()`]: crate::result::Result::unwrap | |
781aab86 FG |
289 | //! [`os::unix`]: ../os/unix/io/index.html |
290 | //! [`os::windows`]: ../os/windows/io/index.html | |
291 | //! [`OwnedFd`]: ../os/fd/struct.OwnedFd.html | |
292 | //! [`BorrowedFd<'a>`]: ../os/fd/struct.BorrowedFd.html | |
293 | //! [`Arc`]: crate::sync::Arc | |
1a4d82fc | 294 | |
c34b1796 | 295 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 296 | |
1b1a35ee XL |
297 | #[cfg(test)] |
298 | mod tests; | |
299 | ||
532ac7d7 XL |
300 | use crate::cmp; |
301 | use crate::fmt; | |
49aad941 | 302 | use crate::mem::take; |
532ac7d7 | 303 | use crate::ops::{Deref, DerefMut}; |
60c5eb7d XL |
304 | use crate::slice; |
305 | use crate::str; | |
532ac7d7 | 306 | use crate::sys; |
17df50a5 | 307 | use crate::sys_common::memchr; |
1a4d82fc | 308 | |
94222f64 XL |
309 | #[stable(feature = "bufwriter_into_parts", since = "1.56.0")] |
310 | pub use self::buffered::WriterPanicked; | |
9ffffee4 FG |
311 | #[unstable(feature = "raw_os_error_ty", issue = "107792")] |
312 | pub use self::error::RawOsError; | |
2b03887a | 313 | pub(crate) use self::stdio::attempt_print_to_stderr; |
fc512014 XL |
314 | #[unstable(feature = "internal_output_capture", issue = "none")] |
315 | #[doc(no_inline, hidden)] | |
316 | pub use self::stdio::set_output_capture; | |
353b0b11 | 317 | #[stable(feature = "is_terminal", since = "1.70.0")] |
2b03887a | 318 | pub use self::stdio::IsTerminal; |
dfeec247 | 319 | #[unstable(feature = "print_internals", issue = "none")] |
ed00b5ec | 320 | #[doc(hidden)] |
60c5eb7d | 321 | pub use self::stdio::{_eprint, _print}; |
60c5eb7d | 322 | #[stable(feature = "rust1", since = "1.0.0")] |
5099ac24 FG |
323 | pub use self::{ |
324 | buffered::{BufReader, BufWriter, IntoInnerError, LineWriter}, | |
325 | copy::copy, | |
326 | cursor::Cursor, | |
327 | error::{Error, ErrorKind, Result}, | |
328 | stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}, | |
329 | util::{empty, repeat, sink, Empty, Repeat, Sink}, | |
330 | }; | |
29967ef6 | 331 | |
a2a8927a | 332 | #[unstable(feature = "read_buf", issue = "78485")] |
ed00b5ec | 333 | pub use core::io::{BorrowedBuf, BorrowedCursor}; |
5099ac24 | 334 | pub(crate) use error::const_io_error; |
a2a8927a | 335 | |
1a4d82fc | 336 | mod buffered; |
fc512014 | 337 | pub(crate) mod copy; |
85aaf69f SL |
338 | mod cursor; |
339 | mod error; | |
340 | mod impls; | |
60c5eb7d | 341 | pub mod prelude; |
c34b1796 | 342 | mod stdio; |
60c5eb7d | 343 | mod util; |
1a4d82fc | 344 | |
532ac7d7 | 345 | const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE; |
1a4d82fc | 346 | |
3c0e092e | 347 | pub(crate) use stdio::cleanup; |
cdc7bbd5 | 348 | |
60c5eb7d XL |
349 | struct Guard<'a> { |
350 | buf: &'a mut Vec<u8>, | |
351 | len: usize, | |
352 | } | |
041b39d2 | 353 | |
9fa01778 | 354 | impl Drop for Guard<'_> { |
041b39d2 | 355 | fn drop(&mut self) { |
60c5eb7d XL |
356 | unsafe { |
357 | self.buf.set_len(self.len); | |
358 | } | |
041b39d2 XL |
359 | } |
360 | } | |
361 | ||
c295e0f8 XL |
362 | // Several `read_to_string` and `read_line` methods in the standard library will |
363 | // append data into a `String` buffer, but we need to be pretty careful when | |
364 | // doing this. The implementation will just call `.as_mut_vec()` and then | |
365 | // delegate to a byte-oriented reading method, but we must ensure that when | |
366 | // returning we never leave `buf` in a state such that it contains invalid UTF-8 | |
367 | // in its bounds. | |
85aaf69f SL |
368 | // |
369 | // To this end, we use an RAII guard (to protect against panics) which updates | |
370 | // the length of the string when it is dropped. This guard initially truncates | |
371 | // the string to the prior length and only after we've validated that the | |
372 | // new contents are valid UTF-8 do we allow it to set a longer length. | |
373 | // | |
374 | // The unsafety in this function is twofold: | |
375 | // | |
376 | // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8 | |
377 | // checks. | |
378 | // 2. We're passing a raw buffer to the function `f`, and it is expected that | |
379 | // the function only *appends* bytes to the buffer. We'll get undefined | |
380 | // behavior if existing bytes are overwritten to have non-UTF-8 data. | |
c295e0f8 | 381 | pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize> |
60c5eb7d XL |
382 | where |
383 | F: FnOnce(&mut Vec<u8>) -> Result<usize>, | |
85aaf69f | 384 | { |
c295e0f8 XL |
385 | let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() }; |
386 | let ret = f(g.buf); | |
387 | if str::from_utf8(&g.buf[g.len..]).is_err() { | |
388 | ret.and_then(|_| { | |
5099ac24 FG |
389 | Err(error::const_io_error!( |
390 | ErrorKind::InvalidData, | |
391 | "stream did not contain valid UTF-8" | |
392 | )) | |
c295e0f8 XL |
393 | }) |
394 | } else { | |
395 | g.len = g.buf.len(); | |
396 | ret | |
1a4d82fc JJ |
397 | } |
398 | } | |
399 | ||
4b012472 FG |
400 | // Here we must serve many masters with conflicting goals: |
401 | // | |
402 | // - avoid allocating unless necessary | |
403 | // - avoid overallocating if we know the exact size (#89165) | |
404 | // - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820) | |
405 | // - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads | |
406 | // - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems | |
407 | // at the same time, i.e. small reads suffer from syscall overhead, all reads incur initialization cost | |
408 | // proportional to buffer size (#110650) | |
409 | // | |
49aad941 FG |
410 | pub(crate) fn default_read_to_end<R: Read + ?Sized>( |
411 | r: &mut R, | |
412 | buf: &mut Vec<u8>, | |
413 | size_hint: Option<usize>, | |
414 | ) -> Result<usize> { | |
c34b1796 | 415 | let start_len = buf.len(); |
c295e0f8 | 416 | let start_cap = buf.capacity(); |
49aad941 FG |
417 | // Optionally limit the maximum bytes read on each iteration. |
418 | // This adds an arbitrary fiddle factor to allow for more data than we expect. | |
4b012472 FG |
419 | let mut max_read_size = size_hint |
420 | .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE)) | |
421 | .unwrap_or(DEFAULT_BUF_SIZE); | |
a2a8927a XL |
422 | |
423 | let mut initialized = 0; // Extra initialized bytes from previous loop iteration | |
4b012472 FG |
424 | |
425 | const PROBE_SIZE: usize = 32; | |
426 | ||
427 | fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> { | |
428 | let mut probe = [0u8; PROBE_SIZE]; | |
429 | ||
430 | loop { | |
431 | match r.read(&mut probe) { | |
432 | Ok(n) => { | |
433 | buf.extend_from_slice(&probe[..n]); | |
434 | return Ok(n); | |
435 | } | |
436 | Err(ref e) if e.is_interrupted() => continue, | |
437 | Err(e) => return Err(e), | |
438 | } | |
439 | } | |
440 | } | |
441 | ||
442 | // avoid inflating empty/small vecs before we have determined that there's anything to read | |
443 | if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE { | |
444 | let read = small_probe_read(r, buf)?; | |
445 | ||
446 | if read == 0 { | |
447 | return Ok(0); | |
448 | } | |
449 | } | |
450 | ||
85aaf69f | 451 | loop { |
4b012472 FG |
452 | if buf.len() == buf.capacity() && buf.capacity() == start_cap { |
453 | // The buffer might be an exact fit. Let's read into a probe buffer | |
454 | // and see if it returns `Ok(0)`. If so, we've avoided an | |
455 | // unnecessary doubling of the capacity. But if not, append the | |
456 | // probe buffer to the primary buffer and let its capacity grow. | |
457 | let read = small_probe_read(r, buf)?; | |
458 | ||
459 | if read == 0 { | |
460 | return Ok(buf.len() - start_len); | |
461 | } | |
462 | } | |
463 | ||
a2a8927a | 464 | if buf.len() == buf.capacity() { |
4b012472 | 465 | buf.reserve(PROBE_SIZE); // buf is full, need more space |
c295e0f8 XL |
466 | } |
467 | ||
49aad941 | 468 | let mut spare = buf.spare_capacity_mut(); |
4b012472 FG |
469 | let buf_len = cmp::min(spare.len(), max_read_size); |
470 | spare = &mut spare[..buf_len]; | |
49aad941 | 471 | let mut read_buf: BorrowedBuf<'_> = spare.into(); |
a2a8927a XL |
472 | |
473 | // SAFETY: These bytes were initialized but not filled in the previous loop | |
474 | unsafe { | |
f2b60f7d | 475 | read_buf.set_init(initialized); |
85aaf69f | 476 | } |
c34b1796 | 477 | |
f2b60f7d | 478 | let mut cursor = read_buf.unfilled(); |
4b012472 FG |
479 | loop { |
480 | match r.read_buf(cursor.reborrow()) { | |
481 | Ok(()) => break, | |
482 | Err(e) if e.is_interrupted() => continue, | |
483 | Err(e) => return Err(e), | |
484 | } | |
85aaf69f | 485 | } |
c295e0f8 | 486 | |
4b012472 FG |
487 | let unfilled_but_initialized = cursor.init_ref().len(); |
488 | let bytes_read = cursor.written(); | |
489 | let was_fully_initialized = read_buf.init_len() == buf_len; | |
490 | ||
491 | if bytes_read == 0 { | |
a2a8927a XL |
492 | return Ok(buf.len() - start_len); |
493 | } | |
494 | ||
495 | // store how much was initialized but not filled | |
4b012472 | 496 | initialized = unfilled_but_initialized; |
a2a8927a | 497 | |
f2b60f7d | 498 | // SAFETY: BorrowedBuf's invariants mean this much memory is initialized. |
a2a8927a | 499 | unsafe { |
4b012472 | 500 | let new_len = bytes_read + buf.len(); |
a2a8927a XL |
501 | buf.set_len(new_len); |
502 | } | |
503 | ||
4b012472 FG |
504 | // Use heuristics to determine the max read size if no initial size hint was provided |
505 | if size_hint.is_none() { | |
506 | // The reader is returning short reads but it doesn't call ensure_init(). | |
507 | // In that case we no longer need to restrict read sizes to avoid | |
508 | // initialization costs. | |
509 | if !was_fully_initialized { | |
510 | max_read_size = usize::MAX; | |
511 | } | |
512 | ||
513 | // we have passed a larger buffer than previously and the | |
514 | // reader still hasn't returned a short read | |
515 | if buf_len >= max_read_size && bytes_read == buf_len { | |
516 | max_read_size = max_read_size.saturating_mul(2); | |
c295e0f8 XL |
517 | } |
518 | } | |
1a4d82fc JJ |
519 | } |
520 | } | |
521 | ||
c295e0f8 XL |
522 | pub(crate) fn default_read_to_string<R: Read + ?Sized>( |
523 | r: &mut R, | |
524 | buf: &mut String, | |
49aad941 | 525 | size_hint: Option<usize>, |
c295e0f8 XL |
526 | ) -> Result<usize> { |
527 | // Note that we do *not* call `r.read_to_end()` here. We are passing | |
528 | // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end` | |
529 | // method to fill it up. An arbitrary implementation could overwrite the | |
530 | // entire contents of the vector, not just append to it (which is what | |
531 | // we are expecting). | |
532 | // | |
533 | // To prevent extraneously checking the UTF-8-ness of the entire buffer | |
534 | // we pass it to our hardcoded `default_read_to_end` implementation which | |
535 | // we know is guaranteed to only read data into the end of the buffer. | |
49aad941 | 536 | unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) } |
c295e0f8 XL |
537 | } |
538 | ||
48663c56 | 539 | pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> |
532ac7d7 | 540 | where |
60c5eb7d | 541 | F: FnOnce(&mut [u8]) -> Result<usize>, |
532ac7d7 | 542 | { |
60c5eb7d | 543 | let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b); |
532ac7d7 XL |
544 | read(buf) |
545 | } | |
546 | ||
48663c56 | 547 | pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize> |
532ac7d7 | 548 | where |
60c5eb7d | 549 | F: FnOnce(&[u8]) -> Result<usize>, |
532ac7d7 | 550 | { |
60c5eb7d | 551 | let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b); |
532ac7d7 XL |
552 | write(buf) |
553 | } | |
554 | ||
5869c6ff XL |
555 | pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> { |
556 | while !buf.is_empty() { | |
557 | match this.read(buf) { | |
558 | Ok(0) => break, | |
559 | Ok(n) => { | |
ed00b5ec | 560 | buf = &mut buf[n..]; |
5869c6ff | 561 | } |
781aab86 | 562 | Err(ref e) if e.is_interrupted() => {} |
5869c6ff XL |
563 | Err(e) => return Err(e), |
564 | } | |
565 | } | |
566 | if !buf.is_empty() { | |
5099ac24 | 567 | Err(error::const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) |
5869c6ff XL |
568 | } else { |
569 | Ok(()) | |
570 | } | |
571 | } | |
572 | ||
f2b60f7d | 573 | pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()> |
a2a8927a XL |
574 | where |
575 | F: FnOnce(&mut [u8]) -> Result<usize>, | |
576 | { | |
f2b60f7d FG |
577 | let n = read(cursor.ensure_init().init_mut())?; |
578 | unsafe { | |
579 | // SAFETY: we initialised using `ensure_init` so there is no uninit data to advance to. | |
580 | cursor.advance(n); | |
581 | } | |
a2a8927a XL |
582 | Ok(()) |
583 | } | |
584 | ||
c1a9b12d | 585 | /// The `Read` trait allows for reading bytes from a source. |
85aaf69f | 586 | /// |
041b39d2 | 587 | /// Implementors of the `Read` trait are called 'readers'. |
1a4d82fc | 588 | /// |
3b2f2976 | 589 | /// Readers are defined by one required method, [`read()`]. Each call to [`read()`] |
c1a9b12d | 590 | /// will attempt to pull bytes from this source into a provided buffer. A |
3b2f2976 | 591 | /// number of other methods are implemented in terms of [`read()`], giving |
c1a9b12d SL |
592 | /// implementors a number of ways to read bytes while only needing to implement |
593 | /// a single method. | |
594 | /// | |
595 | /// Readers are intended to be composable with one another. Many implementors | |
3b2f2976 | 596 | /// throughout [`std::io`] take and provide types which implement the `Read` |
c1a9b12d SL |
597 | /// trait. |
598 | /// | |
3b2f2976 XL |
599 | /// Please note that each call to [`read()`] may involve a system call, and |
600 | /// therefore, using something that implements [`BufRead`], such as | |
601 | /// [`BufReader`], will be more efficient. | |
b039eaaf | 602 | /// |
4b012472 FG |
603 | /// Repeated calls to the reader use the same cursor, so for example |
604 | /// calling `read_to_end` twice on a [`File`] will only return the file's | |
605 | /// contents once. It's recommended to first call `rewind()` in that case. | |
606 | /// | |
c1a9b12d SL |
607 | /// # Examples |
608 | /// | |
3b2f2976 | 609 | /// [`File`]s implement `Read`: |
c1a9b12d | 610 | /// |
0531ce1d XL |
611 | /// ```no_run |
612 | /// use std::io; | |
c1a9b12d SL |
613 | /// use std::io::prelude::*; |
614 | /// use std::fs::File; | |
615 | /// | |
0531ce1d XL |
616 | /// fn main() -> io::Result<()> { |
617 | /// let mut f = File::open("foo.txt")?; | |
618 | /// let mut buffer = [0; 10]; | |
c1a9b12d | 619 | /// |
0531ce1d XL |
620 | /// // read up to 10 bytes |
621 | /// f.read(&mut buffer)?; | |
c1a9b12d | 622 | /// |
a1dfa0c6 | 623 | /// let mut buffer = Vec::new(); |
0531ce1d XL |
624 | /// // read the whole file |
625 | /// f.read_to_end(&mut buffer)?; | |
c1a9b12d | 626 | /// |
0531ce1d XL |
627 | /// // read into a String, so that you don't need to do the conversion. |
628 | /// let mut buffer = String::new(); | |
629 | /// f.read_to_string(&mut buffer)?; | |
c1a9b12d | 630 | /// |
0531ce1d XL |
631 | /// // and more! See the other methods for more details. |
632 | /// Ok(()) | |
633 | /// } | |
c1a9b12d | 634 | /// ``` |
ff7c6d11 | 635 | /// |
6a06907d | 636 | /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`: |
ff7c6d11 | 637 | /// |
0531ce1d | 638 | /// ```no_run |
ff7c6d11 XL |
639 | /// # use std::io; |
640 | /// use std::io::prelude::*; | |
641 | /// | |
0531ce1d XL |
642 | /// fn main() -> io::Result<()> { |
643 | /// let mut b = "This string will be read".as_bytes(); | |
644 | /// let mut buffer = [0; 10]; | |
ff7c6d11 | 645 | /// |
0531ce1d XL |
646 | /// // read up to 10 bytes |
647 | /// b.read(&mut buffer)?; | |
ff7c6d11 | 648 | /// |
0531ce1d XL |
649 | /// // etc... it works exactly as a File does! |
650 | /// Ok(()) | |
651 | /// } | |
ff7c6d11 XL |
652 | /// ``` |
653 | /// | |
3dfed10e XL |
654 | /// [`read()`]: Read::read |
655 | /// [`&str`]: prim@str | |
656 | /// [`std::io`]: self | |
657 | /// [`File`]: crate::fs::File | |
c34b1796 | 658 | #[stable(feature = "rust1", since = "1.0.0")] |
17df50a5 | 659 | #[doc(notable_trait)] |
136023e0 | 660 | #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")] |
85aaf69f SL |
661 | pub trait Read { |
662 | /// Pull some bytes from this source into the specified buffer, returning | |
663 | /// how many bytes were read. | |
664 | /// | |
665 | /// This function does not provide any guarantees about whether it blocks | |
ba9703b0 | 666 | /// waiting for data, but if an object needs to block for a read and cannot, |
3b2f2976 | 667 | /// it will typically signal this via an [`Err`] return value. |
85aaf69f | 668 | /// |
6a06907d XL |
669 | /// If the return value of this method is [`Ok(n)`], then implementations must |
670 | /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates | |
9346a6ac | 671 | /// that the buffer `buf` has been filled in with `n` bytes of data from this |
85aaf69f SL |
672 | /// source. If `n` is `0`, then it can indicate one of two scenarios: |
673 | /// | |
674 | /// 1. This reader has reached its "end of file" and will likely no longer | |
675 | /// be able to produce bytes. Note that this does not mean that the | |
17df50a5 XL |
676 | /// reader will *always* no longer be able to produce bytes. As an example, |
677 | /// on Linux, this method will call the `recv` syscall for a [`TcpStream`], | |
678 | /// where returning zero indicates the connection was shut down correctly. While | |
679 | /// for [`File`], it is possible to reach the end of file and get zero as result, | |
680 | /// but if more data is appended to the file, future calls to `read` will return | |
681 | /// more data. | |
85aaf69f SL |
682 | /// 2. The buffer specified was 0 bytes in length. |
683 | /// | |
f9f354fc XL |
684 | /// It is not an error if the returned value `n` is smaller than the buffer size, |
685 | /// even when the reader is not at the end of the stream yet. | |
686 | /// This may happen for example because fewer bytes are actually available right now | |
687 | /// (e. g. being close to end-of-file) or because read() was interrupted by a signal. | |
688 | /// | |
49aad941 FG |
689 | /// As this trait is safe to implement, callers in unsafe code cannot rely on |
690 | /// `n <= buf.len()` for safety. | |
6a06907d XL |
691 | /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes. |
692 | /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if | |
693 | /// `n > buf.len()`. | |
694 | /// | |
85aaf69f | 695 | /// No guarantees are provided about the contents of `buf` when this |
2b03887a | 696 | /// function is called, so implementations cannot rely on any property of the |
dc9dc135 | 697 | /// contents of `buf` being true. It is recommended that *implementations* |
85aaf69f | 698 | /// only write data to `buf` instead of reading its contents. |
1a4d82fc | 699 | /// |
49aad941 FG |
700 | /// Correspondingly, however, *callers* of this method in unsafe code must not assume |
701 | /// any guarantees about how the implementation uses `buf`. The trait is safe to implement, | |
416331ca XL |
702 | /// so it is possible that the code that's supposed to write to the buffer might also read |
703 | /// from it. It is your responsibility to make sure that `buf` is initialized | |
dc9dc135 XL |
704 | /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one |
705 | /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior. | |
706 | /// | |
3dfed10e | 707 | /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit |
dc9dc135 | 708 | /// |
85aaf69f | 709 | /// # Errors |
1a4d82fc | 710 | /// |
85aaf69f SL |
711 | /// If this function encounters any form of I/O or other error, an error |
712 | /// variant will be returned. If an error is returned then it must be | |
713 | /// guaranteed that no bytes were read. | |
c1a9b12d | 714 | /// |
3b2f2976 | 715 | /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read |
7cac9316 XL |
716 | /// operation should be retried if there is nothing else to do. |
717 | /// | |
c1a9b12d SL |
718 | /// # Examples |
719 | /// | |
3b2f2976 | 720 | /// [`File`]s implement `Read`: |
c1a9b12d | 721 | /// |
3dfed10e XL |
722 | /// [`Ok(n)`]: Ok |
723 | /// [`File`]: crate::fs::File | |
17df50a5 | 724 | /// [`TcpStream`]: crate::net::TcpStream |
c1a9b12d | 725 | /// |
0531ce1d | 726 | /// ```no_run |
c1a9b12d SL |
727 | /// use std::io; |
728 | /// use std::io::prelude::*; | |
729 | /// use std::fs::File; | |
730 | /// | |
0531ce1d XL |
731 | /// fn main() -> io::Result<()> { |
732 | /// let mut f = File::open("foo.txt")?; | |
733 | /// let mut buffer = [0; 10]; | |
c1a9b12d | 734 | /// |
0531ce1d | 735 | /// // read up to 10 bytes |
532ac7d7 XL |
736 | /// let n = f.read(&mut buffer[..])?; |
737 | /// | |
738 | /// println!("The bytes: {:?}", &buffer[..n]); | |
0531ce1d XL |
739 | /// Ok(()) |
740 | /// } | |
c1a9b12d | 741 | /// ``` |
c34b1796 | 742 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 743 | fn read(&mut self, buf: &mut [u8]) -> Result<usize>; |
1a4d82fc | 744 | |
9fa01778 XL |
745 | /// Like `read`, except that it reads into a slice of buffers. |
746 | /// | |
747 | /// Data is copied to fill each buffer in order, with the final buffer | |
f9f354fc XL |
748 | /// written to possibly being only partially filled. This method must |
749 | /// behave equivalently to a single call to `read` with concatenated | |
750 | /// buffers. | |
9fa01778 | 751 | /// |
532ac7d7 XL |
752 | /// The default implementation calls `read` with either the first nonempty |
753 | /// buffer provided, or an empty one if none exists. | |
48663c56 XL |
754 | #[stable(feature = "iovec", since = "1.36.0")] |
755 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> { | |
532ac7d7 | 756 | default_read_vectored(|b| self.read(b), bufs) |
9fa01778 XL |
757 | } |
758 | ||
f9f354fc XL |
759 | /// Determines if this `Read`er has an efficient `read_vectored` |
760 | /// implementation. | |
761 | /// | |
762 | /// If a `Read`er does not override the default `read_vectored` | |
763 | /// implementation, code using it may want to avoid the method all together | |
764 | /// and coalesce writes into a single buffer for higher performance. | |
765 | /// | |
766 | /// The default implementation returns `false`. | |
767 | #[unstable(feature = "can_vector", issue = "69941")] | |
768 | fn is_read_vectored(&self) -> bool { | |
769 | false | |
770 | } | |
771 | ||
85aaf69f | 772 | /// Read all bytes until EOF in this source, placing them into `buf`. |
1a4d82fc | 773 | /// |
85aaf69f | 774 | /// All bytes read from this source will be appended to the specified buffer |
3b2f2976 XL |
775 | /// `buf`. This function will continuously call [`read()`] to append more data to |
776 | /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of | |
777 | /// non-[`ErrorKind::Interrupted`] kind. | |
1a4d82fc | 778 | /// |
9346a6ac | 779 | /// If successful, this function will return the total number of bytes read. |
1a4d82fc | 780 | /// |
85aaf69f | 781 | /// # Errors |
1a4d82fc | 782 | /// |
85aaf69f | 783 | /// If this function encounters an error of the kind |
3b2f2976 | 784 | /// [`ErrorKind::Interrupted`] then the error is ignored and the operation |
85aaf69f | 785 | /// will continue. |
1a4d82fc | 786 | /// |
85aaf69f SL |
787 | /// If any other read error is encountered then this function immediately |
788 | /// returns. Any bytes which have already been read will be appended to | |
789 | /// `buf`. | |
c1a9b12d SL |
790 | /// |
791 | /// # Examples | |
792 | /// | |
3b2f2976 | 793 | /// [`File`]s implement `Read`: |
c1a9b12d | 794 | /// |
3dfed10e XL |
795 | /// [`read()`]: Read::read |
796 | /// [`Ok(0)`]: Ok | |
797 | /// [`File`]: crate::fs::File | |
c1a9b12d | 798 | /// |
0531ce1d | 799 | /// ```no_run |
c1a9b12d SL |
800 | /// use std::io; |
801 | /// use std::io::prelude::*; | |
802 | /// use std::fs::File; | |
803 | /// | |
0531ce1d XL |
804 | /// fn main() -> io::Result<()> { |
805 | /// let mut f = File::open("foo.txt")?; | |
806 | /// let mut buffer = Vec::new(); | |
c1a9b12d | 807 | /// |
0531ce1d XL |
808 | /// // read the whole file |
809 | /// f.read_to_end(&mut buffer)?; | |
810 | /// Ok(()) | |
811 | /// } | |
c1a9b12d | 812 | /// ``` |
83c7162d XL |
813 | /// |
814 | /// (See also the [`std::fs::read`] convenience function for reading from a | |
815 | /// file.) | |
816 | /// | |
3dfed10e | 817 | /// [`std::fs::read`]: crate::fs::read |
c34b1796 AL |
818 | #[stable(feature = "rust1", since = "1.0.0")] |
819 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> { | |
49aad941 | 820 | default_read_to_end(self, buf, None) |
1a4d82fc JJ |
821 | } |
822 | ||
2c00a5a8 | 823 | /// Read all bytes until EOF in this source, appending them to `buf`. |
1a4d82fc | 824 | /// |
c34b1796 AL |
825 | /// If successful, this function returns the number of bytes which were read |
826 | /// and appended to `buf`. | |
827 | /// | |
85aaf69f | 828 | /// # Errors |
1a4d82fc | 829 | /// |
85aaf69f SL |
830 | /// If the data in this stream is *not* valid UTF-8 then an error is |
831 | /// returned and `buf` is unchanged. | |
1a4d82fc | 832 | /// |
3dfed10e | 833 | /// See [`read_to_end`] for other error semantics. |
c1a9b12d | 834 | /// |
3dfed10e | 835 | /// [`read_to_end`]: Read::read_to_end |
c1a9b12d SL |
836 | /// |
837 | /// # Examples | |
838 | /// | |
3dfed10e | 839 | /// [`File`]s implement `Read`: |
c1a9b12d | 840 | /// |
3dfed10e | 841 | /// [`File`]: crate::fs::File |
c1a9b12d | 842 | /// |
0531ce1d | 843 | /// ```no_run |
c1a9b12d SL |
844 | /// use std::io; |
845 | /// use std::io::prelude::*; | |
846 | /// use std::fs::File; | |
847 | /// | |
0531ce1d XL |
848 | /// fn main() -> io::Result<()> { |
849 | /// let mut f = File::open("foo.txt")?; | |
850 | /// let mut buffer = String::new(); | |
c1a9b12d | 851 | /// |
0531ce1d XL |
852 | /// f.read_to_string(&mut buffer)?; |
853 | /// Ok(()) | |
854 | /// } | |
c1a9b12d | 855 | /// ``` |
83c7162d XL |
856 | /// |
857 | /// (See also the [`std::fs::read_to_string`] convenience function for | |
858 | /// reading from a file.) | |
859 | /// | |
3dfed10e | 860 | /// [`std::fs::read_to_string`]: crate::fs::read_to_string |
c34b1796 AL |
861 | #[stable(feature = "rust1", since = "1.0.0")] |
862 | fn read_to_string(&mut self, buf: &mut String) -> Result<usize> { | |
49aad941 | 863 | default_read_to_string(self, buf, None) |
1a4d82fc JJ |
864 | } |
865 | ||
e9174d1e SL |
866 | /// Read the exact number of bytes required to fill `buf`. |
867 | /// | |
868 | /// This function reads as many bytes as necessary to completely fill the | |
869 | /// specified buffer `buf`. | |
870 | /// | |
871 | /// No guarantees are provided about the contents of `buf` when this | |
2b03887a | 872 | /// function is called, so implementations cannot rely on any property of the |
e9174d1e | 873 | /// contents of `buf` being true. It is recommended that implementations |
3dfed10e XL |
874 | /// only write data to `buf` instead of reading its contents. The |
875 | /// documentation on [`read`] has a more detailed explanation on this | |
876 | /// subject. | |
e9174d1e SL |
877 | /// |
878 | /// # Errors | |
879 | /// | |
880 | /// If this function encounters an error of the kind | |
3b2f2976 | 881 | /// [`ErrorKind::Interrupted`] then the error is ignored and the operation |
e9174d1e SL |
882 | /// will continue. |
883 | /// | |
884 | /// If this function encounters an "end of file" before completely filling | |
3b2f2976 | 885 | /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`]. |
e9174d1e SL |
886 | /// The contents of `buf` are unspecified in this case. |
887 | /// | |
888 | /// If any other read error is encountered then this function immediately | |
889 | /// returns. The contents of `buf` are unspecified in this case. | |
890 | /// | |
891 | /// If this function returns an error, it is unspecified how many bytes it | |
892 | /// has read, but it will never read more than would be necessary to | |
893 | /// completely fill the buffer. | |
894 | /// | |
895 | /// # Examples | |
896 | /// | |
3b2f2976 | 897 | /// [`File`]s implement `Read`: |
e9174d1e | 898 | /// |
3dfed10e XL |
899 | /// [`read`]: Read::read |
900 | /// [`File`]: crate::fs::File | |
e9174d1e | 901 | /// |
0531ce1d | 902 | /// ```no_run |
e9174d1e SL |
903 | /// use std::io; |
904 | /// use std::io::prelude::*; | |
905 | /// use std::fs::File; | |
906 | /// | |
0531ce1d XL |
907 | /// fn main() -> io::Result<()> { |
908 | /// let mut f = File::open("foo.txt")?; | |
909 | /// let mut buffer = [0; 10]; | |
e9174d1e | 910 | /// |
0531ce1d XL |
911 | /// // read exactly 10 bytes |
912 | /// f.read_exact(&mut buffer)?; | |
913 | /// Ok(()) | |
914 | /// } | |
e9174d1e | 915 | /// ``` |
92a42be0 | 916 | #[stable(feature = "read_exact", since = "1.6.0")] |
5869c6ff XL |
917 | fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { |
918 | default_read_exact(self, buf) | |
e9174d1e SL |
919 | } |
920 | ||
a2a8927a XL |
921 | /// Pull some bytes from this source into the specified buffer. |
922 | /// | |
f2b60f7d | 923 | /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use |
a2a8927a XL |
924 | /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`. |
925 | /// | |
926 | /// The default implementation delegates to `read`. | |
927 | #[unstable(feature = "read_buf", issue = "78485")] | |
f2b60f7d | 928 | fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> { |
a2a8927a XL |
929 | default_read_buf(|b| self.read(b), buf) |
930 | } | |
931 | ||
f2b60f7d | 932 | /// Read the exact number of bytes required to fill `cursor`. |
a2a8927a | 933 | /// |
353b0b11 FG |
934 | /// This is similar to the [`read_exact`](Read::read_exact) method, except |
935 | /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use | |
936 | /// with uninitialized buffers. | |
937 | /// | |
938 | /// # Errors | |
939 | /// | |
940 | /// If this function encounters an error of the kind [`ErrorKind::Interrupted`] | |
941 | /// then the error is ignored and the operation will continue. | |
942 | /// | |
943 | /// If this function encounters an "end of file" before completely filling | |
944 | /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`]. | |
945 | /// | |
946 | /// If any other read error is encountered then this function immediately | |
947 | /// returns. | |
948 | /// | |
949 | /// If this function returns an error, all bytes read will be appended to `cursor`. | |
a2a8927a | 950 | #[unstable(feature = "read_buf", issue = "78485")] |
f2b60f7d FG |
951 | fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> { |
952 | while cursor.capacity() > 0 { | |
953 | let prev_written = cursor.written(); | |
954 | match self.read_buf(cursor.reborrow()) { | |
a2a8927a | 955 | Ok(()) => {} |
781aab86 | 956 | Err(e) if e.is_interrupted() => continue, |
a2a8927a XL |
957 | Err(e) => return Err(e), |
958 | } | |
959 | ||
f2b60f7d | 960 | if cursor.written() == prev_written { |
a2a8927a XL |
961 | return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer")); |
962 | } | |
963 | } | |
964 | ||
965 | Ok(()) | |
966 | } | |
967 | ||
968 | /// Creates a "by reference" adaptor for this instance of `Read`. | |
1a4d82fc | 969 | /// |
94222f64 | 970 | /// The returned adapter also implements `Read` and will simply borrow this |
85aaf69f | 971 | /// current reader. |
c1a9b12d SL |
972 | /// |
973 | /// # Examples | |
974 | /// | |
3dfed10e | 975 | /// [`File`]s implement `Read`: |
c1a9b12d | 976 | /// |
3dfed10e | 977 | /// [`File`]: crate::fs::File |
c1a9b12d | 978 | /// |
0531ce1d | 979 | /// ```no_run |
c1a9b12d SL |
980 | /// use std::io; |
981 | /// use std::io::Read; | |
982 | /// use std::fs::File; | |
983 | /// | |
0531ce1d XL |
984 | /// fn main() -> io::Result<()> { |
985 | /// let mut f = File::open("foo.txt")?; | |
986 | /// let mut buffer = Vec::new(); | |
987 | /// let mut other_buffer = Vec::new(); | |
c1a9b12d | 988 | /// |
0531ce1d XL |
989 | /// { |
990 | /// let reference = f.by_ref(); | |
c1a9b12d | 991 | /// |
0531ce1d XL |
992 | /// // read at most 5 bytes |
993 | /// reference.take(5).read_to_end(&mut buffer)?; | |
c1a9b12d | 994 | /// |
0531ce1d | 995 | /// } // drop our &mut reference so we can use f again |
c1a9b12d | 996 | /// |
0531ce1d XL |
997 | /// // original file still usable, read the rest |
998 | /// f.read_to_end(&mut other_buffer)?; | |
999 | /// Ok(()) | |
1000 | /// } | |
c1a9b12d | 1001 | /// ``` |
c34b1796 | 1002 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
1003 | fn by_ref(&mut self) -> &mut Self |
1004 | where | |
1005 | Self: Sized, | |
1006 | { | |
1007 | self | |
1008 | } | |
1a4d82fc | 1009 | |
3b2f2976 | 1010 | /// Transforms this `Read` instance to an [`Iterator`] over its bytes. |
1a4d82fc | 1011 | /// |
c295e0f8 XL |
1012 | /// The returned type implements [`Iterator`] where the [`Item`] is |
1013 | /// <code>[Result]<[u8], [io::Error]></code>. | |
abe05a73 XL |
1014 | /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`] |
1015 | /// otherwise. EOF is mapped to returning [`None`] from this iterator. | |
c1a9b12d | 1016 | /// |
f2b60f7d FG |
1017 | /// The default implementation calls `read` for each byte, |
1018 | /// which can be very inefficient for data that's not in memory, | |
1019 | /// such as [`File`]. Consider using a [`BufReader`] in such cases. | |
1020 | /// | |
c1a9b12d SL |
1021 | /// # Examples |
1022 | /// | |
3dfed10e | 1023 | /// [`File`]s implement `Read`: |
c1a9b12d | 1024 | /// |
c295e0f8 XL |
1025 | /// [`Item`]: Iterator::Item |
1026 | /// [`File`]: crate::fs::File "fs::File" | |
1027 | /// [Result]: crate::result::Result "Result" | |
1028 | /// [io::Error]: self::Error "io::Error" | |
c1a9b12d | 1029 | /// |
0531ce1d | 1030 | /// ```no_run |
c1a9b12d SL |
1031 | /// use std::io; |
1032 | /// use std::io::prelude::*; | |
f2b60f7d | 1033 | /// use std::io::BufReader; |
c1a9b12d SL |
1034 | /// use std::fs::File; |
1035 | /// | |
0531ce1d | 1036 | /// fn main() -> io::Result<()> { |
f2b60f7d | 1037 | /// let f = BufReader::new(File::open("foo.txt")?); |
c1a9b12d | 1038 | /// |
0531ce1d XL |
1039 | /// for byte in f.bytes() { |
1040 | /// println!("{}", byte.unwrap()); | |
1041 | /// } | |
1042 | /// Ok(()) | |
c1a9b12d | 1043 | /// } |
c1a9b12d | 1044 | /// ``` |
c34b1796 | 1045 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
1046 | fn bytes(self) -> Bytes<Self> |
1047 | where | |
1048 | Self: Sized, | |
1049 | { | |
85aaf69f | 1050 | Bytes { inner: self } |
1a4d82fc JJ |
1051 | } |
1052 | ||
94222f64 | 1053 | /// Creates an adapter which will chain this stream with another. |
1a4d82fc | 1054 | /// |
85aaf69f SL |
1055 | /// The returned `Read` instance will first read all bytes from this object |
1056 | /// until EOF is encountered. Afterwards the output is equivalent to the | |
1057 | /// output of `next`. | |
c1a9b12d SL |
1058 | /// |
1059 | /// # Examples | |
1060 | /// | |
3dfed10e | 1061 | /// [`File`]s implement `Read`: |
c1a9b12d | 1062 | /// |
3dfed10e | 1063 | /// [`File`]: crate::fs::File |
c1a9b12d | 1064 | /// |
0531ce1d | 1065 | /// ```no_run |
c1a9b12d SL |
1066 | /// use std::io; |
1067 | /// use std::io::prelude::*; | |
1068 | /// use std::fs::File; | |
1069 | /// | |
0531ce1d | 1070 | /// fn main() -> io::Result<()> { |
064997fb FG |
1071 | /// let f1 = File::open("foo.txt")?; |
1072 | /// let f2 = File::open("bar.txt")?; | |
c1a9b12d | 1073 | /// |
0531ce1d XL |
1074 | /// let mut handle = f1.chain(f2); |
1075 | /// let mut buffer = String::new(); | |
c1a9b12d | 1076 | /// |
0531ce1d XL |
1077 | /// // read the value into a String. We could use any Read method here, |
1078 | /// // this is just one example. | |
1079 | /// handle.read_to_string(&mut buffer)?; | |
1080 | /// Ok(()) | |
1081 | /// } | |
c1a9b12d | 1082 | /// ``` |
c34b1796 | 1083 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
1084 | fn chain<R: Read>(self, next: R) -> Chain<Self, R> |
1085 | where | |
1086 | Self: Sized, | |
1087 | { | |
85aaf69f | 1088 | Chain { first: self, second: next, done_first: false } |
1a4d82fc JJ |
1089 | } |
1090 | ||
94222f64 | 1091 | /// Creates an adapter which will read at most `limit` bytes from it. |
1a4d82fc | 1092 | /// |
85aaf69f | 1093 | /// This function returns a new instance of `Read` which will read at most |
3b2f2976 | 1094 | /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any |
85aaf69f | 1095 | /// read errors will not count towards the number of bytes read and future |
3b2f2976 | 1096 | /// calls to [`read()`] may succeed. |
c1a9b12d SL |
1097 | /// |
1098 | /// # Examples | |
1099 | /// | |
3b2f2976 | 1100 | /// [`File`]s implement `Read`: |
c1a9b12d | 1101 | /// |
3dfed10e XL |
1102 | /// [`File`]: crate::fs::File |
1103 | /// [`Ok(0)`]: Ok | |
1104 | /// [`read()`]: Read::read | |
c1a9b12d | 1105 | /// |
0531ce1d | 1106 | /// ```no_run |
c1a9b12d SL |
1107 | /// use std::io; |
1108 | /// use std::io::prelude::*; | |
1109 | /// use std::fs::File; | |
1110 | /// | |
0531ce1d | 1111 | /// fn main() -> io::Result<()> { |
064997fb | 1112 | /// let f = File::open("foo.txt")?; |
0531ce1d | 1113 | /// let mut buffer = [0; 5]; |
c1a9b12d | 1114 | /// |
0531ce1d XL |
1115 | /// // read at most five bytes |
1116 | /// let mut handle = f.take(5); | |
c1a9b12d | 1117 | /// |
0531ce1d XL |
1118 | /// handle.read(&mut buffer)?; |
1119 | /// Ok(()) | |
1120 | /// } | |
c1a9b12d | 1121 | /// ``` |
c34b1796 | 1122 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
1123 | fn take(self, limit: u64) -> Take<Self> |
1124 | where | |
1125 | Self: Sized, | |
1126 | { | |
74b04a01 | 1127 | Take { inner: self, limit } |
1a4d82fc | 1128 | } |
85aaf69f | 1129 | } |
1a4d82fc | 1130 | |
5869c6ff XL |
1131 | /// Read all bytes from a [reader][Read] into a new [`String`]. |
1132 | /// | |
1133 | /// This is a convenience function for [`Read::read_to_string`]. Using this | |
1134 | /// function avoids having to create a variable first and provides more type | |
1135 | /// safety since you can only get the buffer out if there were no errors. (If you | |
1136 | /// use [`Read::read_to_string`] you have to remember to check whether the read | |
1137 | /// succeeded because otherwise your buffer will be empty or only partially full.) | |
1138 | /// | |
1139 | /// # Performance | |
1140 | /// | |
1141 | /// The downside of this function's increased ease of use and type safety is | |
1142 | /// that it gives you less control over performance. For example, you can't | |
1143 | /// pre-allocate memory like you can using [`String::with_capacity`] and | |
1144 | /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error | |
1145 | /// occurs while reading. | |
1146 | /// | |
1147 | /// In many cases, this function's performance will be adequate and the ease of use | |
1148 | /// and type safety tradeoffs will be worth it. However, there are cases where you | |
1149 | /// need more control over performance, and in those cases you should definitely use | |
1150 | /// [`Read::read_to_string`] directly. | |
1151 | /// | |
c295e0f8 XL |
1152 | /// Note that in some special cases, such as when reading files, this function will |
1153 | /// pre-allocate memory based on the size of the input it is reading. In those | |
1154 | /// cases, the performance should be as good as if you had used | |
1155 | /// [`Read::read_to_string`] with a manually pre-allocated buffer. | |
1156 | /// | |
5869c6ff XL |
1157 | /// # Errors |
1158 | /// | |
1159 | /// This function forces you to handle errors because the output (the `String`) | |
1160 | /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors | |
1161 | /// that can occur. If any error occurs, you will get an [`Err`], so you | |
1162 | /// don't have to worry about your buffer being empty or partially full. | |
1163 | /// | |
1164 | /// # Examples | |
1165 | /// | |
1166 | /// ```no_run | |
5869c6ff XL |
1167 | /// # use std::io; |
1168 | /// fn main() -> io::Result<()> { | |
5099ac24 | 1169 | /// let stdin = io::read_to_string(io::stdin())?; |
5869c6ff | 1170 | /// println!("Stdin was:"); |
5e7ed085 | 1171 | /// println!("{stdin}"); |
5869c6ff XL |
1172 | /// Ok(()) |
1173 | /// } | |
1174 | /// ``` | |
f2b60f7d | 1175 | #[stable(feature = "io_read_to_string", since = "1.65.0")] |
5099ac24 | 1176 | pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> { |
5869c6ff XL |
1177 | let mut buf = String::new(); |
1178 | reader.read_to_string(&mut buf)?; | |
1179 | Ok(buf) | |
1180 | } | |
1181 | ||
9fa01778 XL |
1182 | /// A buffer type used with `Read::read_vectored`. |
1183 | /// | |
1184 | /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be | |
1185 | /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on | |
1186 | /// Windows. | |
48663c56 | 1187 | #[stable(feature = "iovec", since = "1.36.0")] |
9fa01778 | 1188 | #[repr(transparent)] |
48663c56 | 1189 | pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>); |
9fa01778 | 1190 | |
ed00b5ec | 1191 | #[stable(feature = "iovec_send_sync", since = "1.44.0")] |
ba9703b0 XL |
1192 | unsafe impl<'a> Send for IoSliceMut<'a> {} |
1193 | ||
ed00b5ec | 1194 | #[stable(feature = "iovec_send_sync", since = "1.44.0")] |
ba9703b0 XL |
1195 | unsafe impl<'a> Sync for IoSliceMut<'a> {} |
1196 | ||
48663c56 XL |
1197 | #[stable(feature = "iovec", since = "1.36.0")] |
1198 | impl<'a> fmt::Debug for IoSliceMut<'a> { | |
532ac7d7 | 1199 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
9fa01778 XL |
1200 | fmt::Debug::fmt(self.0.as_slice(), fmt) |
1201 | } | |
1202 | } | |
1203 | ||
48663c56 XL |
1204 | impl<'a> IoSliceMut<'a> { |
1205 | /// Creates a new `IoSliceMut` wrapping a byte slice. | |
9fa01778 XL |
1206 | /// |
1207 | /// # Panics | |
1208 | /// | |
1209 | /// Panics on Windows if the slice is larger than 4GB. | |
48663c56 | 1210 | #[stable(feature = "iovec", since = "1.36.0")] |
9fa01778 | 1211 | #[inline] |
48663c56 XL |
1212 | pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { |
1213 | IoSliceMut(sys::io::IoSliceMut::new(buf)) | |
9fa01778 | 1214 | } |
416331ca XL |
1215 | |
1216 | /// Advance the internal cursor of the slice. | |
1217 | /// | |
136023e0 XL |
1218 | /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of |
1219 | /// multiple buffers. | |
1220 | /// | |
923072b8 FG |
1221 | /// # Panics |
1222 | /// | |
1223 | /// Panics when trying to advance beyond the end of the slice. | |
1224 | /// | |
136023e0 XL |
1225 | /// # Examples |
1226 | /// | |
1227 | /// ``` | |
1228 | /// #![feature(io_slice_advance)] | |
1229 | /// | |
1230 | /// use std::io::IoSliceMut; | |
1231 | /// use std::ops::Deref; | |
1232 | /// | |
1233 | /// let mut data = [1; 8]; | |
1234 | /// let mut buf = IoSliceMut::new(&mut data); | |
1235 | /// | |
1236 | /// // Mark 3 bytes as read. | |
1237 | /// buf.advance(3); | |
1238 | /// assert_eq!(buf.deref(), [1; 5].as_ref()); | |
1239 | /// ``` | |
1240 | #[unstable(feature = "io_slice_advance", issue = "62726")] | |
1241 | #[inline] | |
1242 | pub fn advance(&mut self, n: usize) { | |
1243 | self.0.advance(n) | |
1244 | } | |
1245 | ||
923072b8 | 1246 | /// Advance a slice of slices. |
136023e0 | 1247 | /// |
923072b8 FG |
1248 | /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over. |
1249 | /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified | |
1250 | /// to start at that cursor. | |
416331ca | 1251 | /// |
923072b8 FG |
1252 | /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes, |
1253 | /// the result will only include the second `IoSliceMut`, advanced by 2 bytes. | |
1254 | /// | |
1255 | /// # Panics | |
1256 | /// | |
1257 | /// Panics when trying to advance beyond the end of the slices. | |
416331ca XL |
1258 | /// |
1259 | /// # Examples | |
1260 | /// | |
1261 | /// ``` | |
1262 | /// #![feature(io_slice_advance)] | |
1263 | /// | |
1264 | /// use std::io::IoSliceMut; | |
416331ca XL |
1265 | /// use std::ops::Deref; |
1266 | /// | |
1267 | /// let mut buf1 = [1; 8]; | |
1268 | /// let mut buf2 = [2; 16]; | |
1269 | /// let mut buf3 = [3; 8]; | |
1270 | /// let mut bufs = &mut [ | |
1271 | /// IoSliceMut::new(&mut buf1), | |
1272 | /// IoSliceMut::new(&mut buf2), | |
1273 | /// IoSliceMut::new(&mut buf3), | |
1274 | /// ][..]; | |
1275 | /// | |
1276 | /// // Mark 10 bytes as read. | |
136023e0 | 1277 | /// IoSliceMut::advance_slices(&mut bufs, 10); |
416331ca XL |
1278 | /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); |
1279 | /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); | |
1280 | /// ``` | |
1281 | #[unstable(feature = "io_slice_advance", issue = "62726")] | |
1282 | #[inline] | |
136023e0 | 1283 | pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) { |
416331ca XL |
1284 | // Number of buffers to remove. |
1285 | let mut remove = 0; | |
781aab86 FG |
1286 | // Remaining length before reaching n. |
1287 | let mut left = n; | |
416331ca | 1288 | for buf in bufs.iter() { |
781aab86 FG |
1289 | if let Some(remainder) = left.checked_sub(buf.len()) { |
1290 | left = remainder; | |
416331ca | 1291 | remove += 1; |
781aab86 FG |
1292 | } else { |
1293 | break; | |
416331ca XL |
1294 | } |
1295 | } | |
1296 | ||
49aad941 | 1297 | *bufs = &mut take(bufs)[remove..]; |
923072b8 | 1298 | if bufs.is_empty() { |
781aab86 | 1299 | assert!(left == 0, "advancing io slices beyond their length"); |
923072b8 | 1300 | } else { |
781aab86 | 1301 | bufs[0].advance(left); |
416331ca | 1302 | } |
416331ca | 1303 | } |
9fa01778 XL |
1304 | } |
1305 | ||
48663c56 XL |
1306 | #[stable(feature = "iovec", since = "1.36.0")] |
1307 | impl<'a> Deref for IoSliceMut<'a> { | |
9fa01778 XL |
1308 | type Target = [u8]; |
1309 | ||
1310 | #[inline] | |
1311 | fn deref(&self) -> &[u8] { | |
1312 | self.0.as_slice() | |
1313 | } | |
1314 | } | |
1315 | ||
48663c56 XL |
1316 | #[stable(feature = "iovec", since = "1.36.0")] |
1317 | impl<'a> DerefMut for IoSliceMut<'a> { | |
9fa01778 XL |
1318 | #[inline] |
1319 | fn deref_mut(&mut self) -> &mut [u8] { | |
1320 | self.0.as_mut_slice() | |
1321 | } | |
1322 | } | |
1323 | ||
1324 | /// A buffer type used with `Write::write_vectored`. | |
1325 | /// | |
94222f64 | 1326 | /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be |
9fa01778 XL |
1327 | /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on |
1328 | /// Windows. | |
48663c56 | 1329 | #[stable(feature = "iovec", since = "1.36.0")] |
ba9703b0 | 1330 | #[derive(Copy, Clone)] |
9fa01778 | 1331 | #[repr(transparent)] |
48663c56 | 1332 | pub struct IoSlice<'a>(sys::io::IoSlice<'a>); |
9fa01778 | 1333 | |
ed00b5ec | 1334 | #[stable(feature = "iovec_send_sync", since = "1.44.0")] |
ba9703b0 XL |
1335 | unsafe impl<'a> Send for IoSlice<'a> {} |
1336 | ||
ed00b5ec | 1337 | #[stable(feature = "iovec_send_sync", since = "1.44.0")] |
ba9703b0 XL |
1338 | unsafe impl<'a> Sync for IoSlice<'a> {} |
1339 | ||
48663c56 XL |
1340 | #[stable(feature = "iovec", since = "1.36.0")] |
1341 | impl<'a> fmt::Debug for IoSlice<'a> { | |
532ac7d7 | 1342 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
9fa01778 XL |
1343 | fmt::Debug::fmt(self.0.as_slice(), fmt) |
1344 | } | |
1345 | } | |
1346 | ||
48663c56 XL |
1347 | impl<'a> IoSlice<'a> { |
1348 | /// Creates a new `IoSlice` wrapping a byte slice. | |
9fa01778 XL |
1349 | /// |
1350 | /// # Panics | |
1351 | /// | |
1352 | /// Panics on Windows if the slice is larger than 4GB. | |
48663c56 | 1353 | #[stable(feature = "iovec", since = "1.36.0")] |
c295e0f8 | 1354 | #[must_use] |
9fa01778 | 1355 | #[inline] |
48663c56 XL |
1356 | pub fn new(buf: &'a [u8]) -> IoSlice<'a> { |
1357 | IoSlice(sys::io::IoSlice::new(buf)) | |
9fa01778 | 1358 | } |
416331ca XL |
1359 | |
1360 | /// Advance the internal cursor of the slice. | |
1361 | /// | |
136023e0 XL |
1362 | /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple |
1363 | /// buffers. | |
1364 | /// | |
923072b8 FG |
1365 | /// # Panics |
1366 | /// | |
1367 | /// Panics when trying to advance beyond the end of the slice. | |
1368 | /// | |
136023e0 XL |
1369 | /// # Examples |
1370 | /// | |
1371 | /// ``` | |
1372 | /// #![feature(io_slice_advance)] | |
1373 | /// | |
1374 | /// use std::io::IoSlice; | |
1375 | /// use std::ops::Deref; | |
1376 | /// | |
923072b8 FG |
1377 | /// let data = [1; 8]; |
1378 | /// let mut buf = IoSlice::new(&data); | |
136023e0 XL |
1379 | /// |
1380 | /// // Mark 3 bytes as read. | |
1381 | /// buf.advance(3); | |
1382 | /// assert_eq!(buf.deref(), [1; 5].as_ref()); | |
1383 | /// ``` | |
1384 | #[unstable(feature = "io_slice_advance", issue = "62726")] | |
1385 | #[inline] | |
1386 | pub fn advance(&mut self, n: usize) { | |
1387 | self.0.advance(n) | |
1388 | } | |
1389 | ||
923072b8 | 1390 | /// Advance a slice of slices. |
136023e0 | 1391 | /// |
923072b8 FG |
1392 | /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over. |
1393 | /// If the cursor ends up in the middle of an `IoSlice`, it is modified | |
1394 | /// to start at that cursor. | |
1395 | /// | |
1396 | /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes, | |
1397 | /// the result will only include the second `IoSlice`, advanced by 2 bytes. | |
1398 | /// | |
1399 | /// # Panics | |
416331ca | 1400 | /// |
923072b8 | 1401 | /// Panics when trying to advance beyond the end of the slices. |
416331ca XL |
1402 | /// |
1403 | /// # Examples | |
1404 | /// | |
1405 | /// ``` | |
1406 | /// #![feature(io_slice_advance)] | |
1407 | /// | |
1408 | /// use std::io::IoSlice; | |
416331ca XL |
1409 | /// use std::ops::Deref; |
1410 | /// | |
60c5eb7d XL |
1411 | /// let buf1 = [1; 8]; |
1412 | /// let buf2 = [2; 16]; | |
1413 | /// let buf3 = [3; 8]; | |
416331ca | 1414 | /// let mut bufs = &mut [ |
60c5eb7d XL |
1415 | /// IoSlice::new(&buf1), |
1416 | /// IoSlice::new(&buf2), | |
1417 | /// IoSlice::new(&buf3), | |
416331ca XL |
1418 | /// ][..]; |
1419 | /// | |
1420 | /// // Mark 10 bytes as written. | |
136023e0 | 1421 | /// IoSlice::advance_slices(&mut bufs, 10); |
416331ca XL |
1422 | /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); |
1423 | /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); | |
1424 | #[unstable(feature = "io_slice_advance", issue = "62726")] | |
1425 | #[inline] | |
136023e0 | 1426 | pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) { |
416331ca XL |
1427 | // Number of buffers to remove. |
1428 | let mut remove = 0; | |
781aab86 FG |
1429 | // Remaining length before reaching n. This prevents overflow |
1430 | // that could happen if the length of slices in `bufs` were instead | |
1431 | // accumulated. Those slice may be aliased and, if they are large | |
1432 | // enough, their added length may overflow a `usize`. | |
1433 | let mut left = n; | |
416331ca | 1434 | for buf in bufs.iter() { |
781aab86 FG |
1435 | if let Some(remainder) = left.checked_sub(buf.len()) { |
1436 | left = remainder; | |
416331ca | 1437 | remove += 1; |
781aab86 FG |
1438 | } else { |
1439 | break; | |
416331ca XL |
1440 | } |
1441 | } | |
1442 | ||
49aad941 | 1443 | *bufs = &mut take(bufs)[remove..]; |
923072b8 | 1444 | if bufs.is_empty() { |
781aab86 | 1445 | assert!(left == 0, "advancing io slices beyond their length"); |
923072b8 | 1446 | } else { |
781aab86 | 1447 | bufs[0].advance(left); |
416331ca | 1448 | } |
416331ca | 1449 | } |
9fa01778 XL |
1450 | } |
1451 | ||
48663c56 XL |
1452 | #[stable(feature = "iovec", since = "1.36.0")] |
1453 | impl<'a> Deref for IoSlice<'a> { | |
9fa01778 XL |
1454 | type Target = [u8]; |
1455 | ||
1456 | #[inline] | |
1457 | fn deref(&self) -> &[u8] { | |
1458 | self.0.as_slice() | |
1459 | } | |
1460 | } | |
1461 | ||
85aaf69f SL |
1462 | /// A trait for objects which are byte-oriented sinks. |
1463 | /// | |
c1a9b12d SL |
1464 | /// Implementors of the `Write` trait are sometimes called 'writers'. |
1465 | /// | |
cc61c64b | 1466 | /// Writers are defined by two required methods, [`write`] and [`flush`]: |
c1a9b12d | 1467 | /// |
cc61c64b | 1468 | /// * The [`write`] method will attempt to write some data into the object, |
c1a9b12d SL |
1469 | /// returning how many bytes were successfully written. |
1470 | /// | |
94222f64 | 1471 | /// * The [`flush`] method is useful for adapters and explicit buffers |
c1a9b12d SL |
1472 | /// themselves for ensuring that all buffered data has been pushed out to the |
1473 | /// 'true sink'. | |
1474 | /// | |
1475 | /// Writers are intended to be composable with one another. Many implementors | |
476ff2be | 1476 | /// throughout [`std::io`] take and provide types which implement the `Write` |
c1a9b12d SL |
1477 | /// trait. |
1478 | /// | |
3dfed10e XL |
1479 | /// [`write`]: Write::write |
1480 | /// [`flush`]: Write::flush | |
1481 | /// [`std::io`]: self | |
476ff2be | 1482 | /// |
c1a9b12d SL |
1483 | /// # Examples |
1484 | /// | |
0531ce1d | 1485 | /// ```no_run |
c1a9b12d SL |
1486 | /// use std::io::prelude::*; |
1487 | /// use std::fs::File; | |
85aaf69f | 1488 | /// |
0531ce1d | 1489 | /// fn main() -> std::io::Result<()> { |
532ac7d7 XL |
1490 | /// let data = b"some bytes"; |
1491 | /// | |
1492 | /// let mut pos = 0; | |
0531ce1d | 1493 | /// let mut buffer = File::create("foo.txt")?; |
85aaf69f | 1494 | /// |
532ac7d7 XL |
1495 | /// while pos < data.len() { |
1496 | /// let bytes_written = buffer.write(&data[pos..])?; | |
1497 | /// pos += bytes_written; | |
1498 | /// } | |
0531ce1d XL |
1499 | /// Ok(()) |
1500 | /// } | |
c1a9b12d | 1501 | /// ``` |
532ac7d7 XL |
1502 | /// |
1503 | /// The trait also provides convenience methods like [`write_all`], which calls | |
1504 | /// `write` in a loop until its entire input has been written. | |
1505 | /// | |
3dfed10e | 1506 | /// [`write_all`]: Write::write_all |
c34b1796 | 1507 | #[stable(feature = "rust1", since = "1.0.0")] |
17df50a5 | 1508 | #[doc(notable_trait)] |
136023e0 | 1509 | #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")] |
85aaf69f | 1510 | pub trait Write { |
0731742a | 1511 | /// Write a buffer into this writer, returning how many bytes were written. |
1a4d82fc | 1512 | /// |
85aaf69f | 1513 | /// This function will attempt to write the entire contents of `buf`, but |
94222f64 | 1514 | /// the entire write might not succeed, or the write may also generate an |
fe692bf9 | 1515 | /// error. Typically, a call to `write` represents one attempt to write to |
85aaf69f | 1516 | /// any wrapped object. |
1a4d82fc | 1517 | /// |
85aaf69f | 1518 | /// Calls to `write` are not guaranteed to block waiting for data to be |
62682a34 | 1519 | /// written, and a write which would otherwise block can be indicated through |
2c00a5a8 | 1520 | /// an [`Err`] variant. |
1a4d82fc | 1521 | /// |
fe692bf9 FG |
1522 | /// If this method consumed `n > 0` bytes of `buf` it must return [`Ok(n)`]. |
1523 | /// If the return value is `Ok(n)` then `n` must satisfy `n <= buf.len()`. | |
1524 | /// A return value of `Ok(0)` typically means that the underlying object is | |
1525 | /// no longer able to accept bytes and will likely not be able to in the | |
1526 | /// future as well, or that the buffer provided is empty. | |
1a4d82fc | 1527 | /// |
85aaf69f | 1528 | /// # Errors |
1a4d82fc | 1529 | /// |
85aaf69f SL |
1530 | /// Each call to `write` may generate an I/O error indicating that the |
1531 | /// operation could not be completed. If an error is returned then no bytes | |
1532 | /// in the buffer were written to this writer. | |
1a4d82fc | 1533 | /// |
85aaf69f SL |
1534 | /// It is **not** considered an error if the entire buffer could not be |
1535 | /// written to this writer. | |
c1a9b12d | 1536 | /// |
2c00a5a8 | 1537 | /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the |
7cac9316 XL |
1538 | /// write operation should be retried if there is nothing else to do. |
1539 | /// | |
c1a9b12d SL |
1540 | /// # Examples |
1541 | /// | |
0531ce1d | 1542 | /// ```no_run |
c1a9b12d SL |
1543 | /// use std::io::prelude::*; |
1544 | /// use std::fs::File; | |
1545 | /// | |
0531ce1d XL |
1546 | /// fn main() -> std::io::Result<()> { |
1547 | /// let mut buffer = File::create("foo.txt")?; | |
c1a9b12d | 1548 | /// |
0531ce1d XL |
1549 | /// // Writes some prefix of the byte string, not necessarily all of it. |
1550 | /// buffer.write(b"some bytes")?; | |
1551 | /// Ok(()) | |
1552 | /// } | |
c1a9b12d | 1553 | /// ``` |
3dfed10e XL |
1554 | /// |
1555 | /// [`Ok(n)`]: Ok | |
c34b1796 | 1556 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1557 | fn write(&mut self, buf: &[u8]) -> Result<usize>; |
1a4d82fc | 1558 | |
3dfed10e | 1559 | /// Like [`write`], except that it writes from a slice of buffers. |
9fa01778 | 1560 | /// |
416331ca | 1561 | /// Data is copied from each buffer in order, with the final buffer |
9fa01778 | 1562 | /// read from possibly being only partially consumed. This method must |
3dfed10e | 1563 | /// behave as a call to [`write`] with the buffers concatenated would. |
9fa01778 | 1564 | /// |
3dfed10e | 1565 | /// The default implementation calls [`write`] with either the first nonempty |
532ac7d7 | 1566 | /// buffer provided, or an empty one if none exists. |
3dfed10e | 1567 | /// |
136023e0 XL |
1568 | /// # Examples |
1569 | /// | |
1570 | /// ```no_run | |
1571 | /// use std::io::IoSlice; | |
1572 | /// use std::io::prelude::*; | |
1573 | /// use std::fs::File; | |
1574 | /// | |
1575 | /// fn main() -> std::io::Result<()> { | |
923072b8 FG |
1576 | /// let data1 = [1; 8]; |
1577 | /// let data2 = [15; 8]; | |
1578 | /// let io_slice1 = IoSlice::new(&data1); | |
1579 | /// let io_slice2 = IoSlice::new(&data2); | |
136023e0 XL |
1580 | /// |
1581 | /// let mut buffer = File::create("foo.txt")?; | |
1582 | /// | |
1583 | /// // Writes some prefix of the byte string, not necessarily all of it. | |
1584 | /// buffer.write_vectored(&[io_slice1, io_slice2])?; | |
1585 | /// Ok(()) | |
1586 | /// } | |
1587 | /// ``` | |
1588 | /// | |
3dfed10e | 1589 | /// [`write`]: Write::write |
48663c56 XL |
1590 | #[stable(feature = "iovec", since = "1.36.0")] |
1591 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> { | |
532ac7d7 | 1592 | default_write_vectored(|b| self.write(b), bufs) |
9fa01778 XL |
1593 | } |
1594 | ||
fc512014 | 1595 | /// Determines if this `Write`r has an efficient [`write_vectored`] |
f9f354fc XL |
1596 | /// implementation. |
1597 | /// | |
fc512014 | 1598 | /// If a `Write`r does not override the default [`write_vectored`] |
f9f354fc XL |
1599 | /// implementation, code using it may want to avoid the method all together |
1600 | /// and coalesce writes into a single buffer for higher performance. | |
1601 | /// | |
1602 | /// The default implementation returns `false`. | |
3dfed10e XL |
1603 | /// |
1604 | /// [`write_vectored`]: Write::write_vectored | |
f9f354fc XL |
1605 | #[unstable(feature = "can_vector", issue = "69941")] |
1606 | fn is_write_vectored(&self) -> bool { | |
1607 | false | |
1608 | } | |
1609 | ||
85aaf69f SL |
1610 | /// Flush this output stream, ensuring that all intermediately buffered |
1611 | /// contents reach their destination. | |
1a4d82fc | 1612 | /// |
85aaf69f | 1613 | /// # Errors |
1a4d82fc | 1614 | /// |
85aaf69f SL |
1615 | /// It is considered an error if not all bytes could be written due to |
1616 | /// I/O errors or EOF being reached. | |
c1a9b12d SL |
1617 | /// |
1618 | /// # Examples | |
1619 | /// | |
0531ce1d | 1620 | /// ```no_run |
c1a9b12d SL |
1621 | /// use std::io::prelude::*; |
1622 | /// use std::io::BufWriter; | |
1623 | /// use std::fs::File; | |
1624 | /// | |
0531ce1d XL |
1625 | /// fn main() -> std::io::Result<()> { |
1626 | /// let mut buffer = BufWriter::new(File::create("foo.txt")?); | |
c1a9b12d | 1627 | /// |
532ac7d7 | 1628 | /// buffer.write_all(b"some bytes")?; |
0531ce1d XL |
1629 | /// buffer.flush()?; |
1630 | /// Ok(()) | |
1631 | /// } | |
c1a9b12d | 1632 | /// ``` |
c34b1796 | 1633 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1634 | fn flush(&mut self) -> Result<()>; |
1a4d82fc | 1635 | |
0731742a | 1636 | /// Attempts to write an entire buffer into this writer. |
1a4d82fc | 1637 | /// |
2c00a5a8 XL |
1638 | /// This method will continuously call [`write`] until there is no more data |
1639 | /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is | |
7cac9316 XL |
1640 | /// returned. This method will not return until the entire buffer has been |
1641 | /// successfully written or such an error occurs. The first error that is | |
2c00a5a8 | 1642 | /// not of [`ErrorKind::Interrupted`] kind generated from this method will be |
7cac9316 | 1643 | /// returned. |
1a4d82fc | 1644 | /// |
74b04a01 XL |
1645 | /// If the buffer contains no data, this will never call [`write`]. |
1646 | /// | |
1a4d82fc JJ |
1647 | /// # Errors |
1648 | /// | |
7cac9316 | 1649 | /// This function will return the first error of |
2c00a5a8 XL |
1650 | /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns. |
1651 | /// | |
3dfed10e | 1652 | /// [`write`]: Write::write |
c1a9b12d SL |
1653 | /// |
1654 | /// # Examples | |
1655 | /// | |
0531ce1d | 1656 | /// ```no_run |
c1a9b12d SL |
1657 | /// use std::io::prelude::*; |
1658 | /// use std::fs::File; | |
1659 | /// | |
0531ce1d XL |
1660 | /// fn main() -> std::io::Result<()> { |
1661 | /// let mut buffer = File::create("foo.txt")?; | |
c1a9b12d | 1662 | /// |
0531ce1d XL |
1663 | /// buffer.write_all(b"some bytes")?; |
1664 | /// Ok(()) | |
1665 | /// } | |
c1a9b12d | 1666 | /// ``` |
c34b1796 | 1667 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1668 | fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { |
9346a6ac | 1669 | while !buf.is_empty() { |
85aaf69f | 1670 | match self.write(buf) { |
60c5eb7d | 1671 | Ok(0) => { |
5099ac24 | 1672 | return Err(error::const_io_error!( |
cdc7bbd5 | 1673 | ErrorKind::WriteZero, |
5099ac24 | 1674 | "failed to write whole buffer", |
cdc7bbd5 | 1675 | )); |
60c5eb7d | 1676 | } |
85aaf69f | 1677 | Ok(n) => buf = &buf[n..], |
781aab86 | 1678 | Err(ref e) if e.is_interrupted() => {} |
85aaf69f SL |
1679 | Err(e) => return Err(e), |
1680 | } | |
1681 | } | |
1682 | Ok(()) | |
1683 | } | |
1a4d82fc | 1684 | |
ba9703b0 XL |
1685 | /// Attempts to write multiple buffers into this writer. |
1686 | /// | |
1687 | /// This method will continuously call [`write_vectored`] until there is no | |
1688 | /// more data to be written or an error of non-[`ErrorKind::Interrupted`] | |
1689 | /// kind is returned. This method will not return until all buffers have | |
1690 | /// been successfully written or such an error occurs. The first error that | |
1691 | /// is not of [`ErrorKind::Interrupted`] kind generated from this method | |
1692 | /// will be returned. | |
1693 | /// | |
1694 | /// If the buffer contains no data, this will never call [`write_vectored`]. | |
1695 | /// | |
ba9703b0 XL |
1696 | /// # Notes |
1697 | /// | |
3dfed10e XL |
1698 | /// Unlike [`write_vectored`], this takes a *mutable* reference to |
1699 | /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to | |
ba9703b0 XL |
1700 | /// modify the slice to keep track of the bytes already written. |
1701 | /// | |
1702 | /// Once this function returns, the contents of `bufs` are unspecified, as | |
3dfed10e | 1703 | /// this depends on how many calls to [`write_vectored`] were necessary. It is |
ba9703b0 XL |
1704 | /// best to understand this function as taking ownership of `bufs` and to |
1705 | /// not use `bufs` afterwards. The underlying buffers, to which the | |
3dfed10e | 1706 | /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and |
ba9703b0 XL |
1707 | /// can be reused. |
1708 | /// | |
3dfed10e XL |
1709 | /// [`write_vectored`]: Write::write_vectored |
1710 | /// | |
ba9703b0 XL |
1711 | /// # Examples |
1712 | /// | |
1713 | /// ``` | |
1714 | /// #![feature(write_all_vectored)] | |
1715 | /// # fn main() -> std::io::Result<()> { | |
1716 | /// | |
1717 | /// use std::io::{Write, IoSlice}; | |
1718 | /// | |
1719 | /// let mut writer = Vec::new(); | |
1720 | /// let bufs = &mut [ | |
1721 | /// IoSlice::new(&[1]), | |
1722 | /// IoSlice::new(&[2, 3]), | |
1723 | /// IoSlice::new(&[4, 5, 6]), | |
1724 | /// ]; | |
1725 | /// | |
1726 | /// writer.write_all_vectored(bufs)?; | |
1727 | /// // Note: the contents of `bufs` is now undefined, see the Notes section. | |
1728 | /// | |
1729 | /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]); | |
1730 | /// # Ok(()) } | |
1731 | /// ``` | |
1732 | #[unstable(feature = "write_all_vectored", issue = "70436")] | |
1733 | fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> { | |
3dfed10e XL |
1734 | // Guarantee that bufs is empty if it contains no data, |
1735 | // to avoid calling write_vectored if there is no data to be written. | |
136023e0 | 1736 | IoSlice::advance_slices(&mut bufs, 0); |
ba9703b0 XL |
1737 | while !bufs.is_empty() { |
1738 | match self.write_vectored(bufs) { | |
1739 | Ok(0) => { | |
5099ac24 | 1740 | return Err(error::const_io_error!( |
cdc7bbd5 | 1741 | ErrorKind::WriteZero, |
5099ac24 | 1742 | "failed to write whole buffer", |
cdc7bbd5 | 1743 | )); |
ba9703b0 | 1744 | } |
136023e0 | 1745 | Ok(n) => IoSlice::advance_slices(&mut bufs, n), |
781aab86 | 1746 | Err(ref e) if e.is_interrupted() => {} |
ba9703b0 XL |
1747 | Err(e) => return Err(e), |
1748 | } | |
1749 | } | |
1750 | Ok(()) | |
1751 | } | |
1752 | ||
1a4d82fc JJ |
1753 | /// Writes a formatted string into this writer, returning any error |
1754 | /// encountered. | |
1755 | /// | |
c1a9b12d | 1756 | /// This method is primarily used to interface with the |
c295e0f8 | 1757 | /// [`format_args!()`] macro, and it is rare that this should |
3dfed10e | 1758 | /// explicitly be called. The [`write!()`] macro should be favored to |
c1a9b12d SL |
1759 | /// invoke this method instead. |
1760 | /// | |
3dfed10e | 1761 | /// This function internally uses the [`write_all`] method on |
c1a9b12d SL |
1762 | /// this trait and hence will continuously write data so long as no errors |
1763 | /// are received. This also means that partial writes are not indicated in | |
1764 | /// this signature. | |
1765 | /// | |
3dfed10e | 1766 | /// [`write_all`]: Write::write_all |
85aaf69f | 1767 | /// |
1a4d82fc JJ |
1768 | /// # Errors |
1769 | /// | |
1770 | /// This function will return any I/O error reported while formatting. | |
c1a9b12d SL |
1771 | /// |
1772 | /// # Examples | |
1773 | /// | |
0531ce1d | 1774 | /// ```no_run |
c1a9b12d SL |
1775 | /// use std::io::prelude::*; |
1776 | /// use std::fs::File; | |
1777 | /// | |
0531ce1d XL |
1778 | /// fn main() -> std::io::Result<()> { |
1779 | /// let mut buffer = File::create("foo.txt")?; | |
c1a9b12d | 1780 | /// |
0531ce1d XL |
1781 | /// // this call |
1782 | /// write!(buffer, "{:.*}", 2, 1.234567)?; | |
1783 | /// // turns into this: | |
1784 | /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?; | |
1785 | /// Ok(()) | |
1786 | /// } | |
c1a9b12d | 1787 | /// ``` |
c34b1796 | 1788 | #[stable(feature = "rust1", since = "1.0.0")] |
532ac7d7 | 1789 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> { |
85aaf69f | 1790 | // Create a shim which translates a Write to a fmt::Write and saves |
1a4d82fc | 1791 | // off I/O errors. instead of discarding them |
94222f64 | 1792 | struct Adapter<'a, T: ?Sized + 'a> { |
1a4d82fc | 1793 | inner: &'a mut T, |
85aaf69f | 1794 | error: Result<()>, |
1a4d82fc JJ |
1795 | } |
1796 | ||
94222f64 | 1797 | impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> { |
1a4d82fc | 1798 | fn write_str(&mut self, s: &str) -> fmt::Result { |
85aaf69f | 1799 | match self.inner.write_all(s.as_bytes()) { |
1a4d82fc JJ |
1800 | Ok(()) => Ok(()), |
1801 | Err(e) => { | |
1802 | self.error = Err(e); | |
1803 | Err(fmt::Error) | |
1804 | } | |
1805 | } | |
1806 | } | |
1807 | } | |
1808 | ||
94222f64 | 1809 | let mut output = Adapter { inner: self, error: Ok(()) }; |
1a4d82fc JJ |
1810 | match fmt::write(&mut output, fmt) { |
1811 | Ok(()) => Ok(()), | |
7453a54e SL |
1812 | Err(..) => { |
1813 | // check if the error came from the underlying `Write` or not | |
1814 | if output.error.is_err() { | |
1815 | output.error | |
1816 | } else { | |
5099ac24 | 1817 | Err(error::const_io_error!(ErrorKind::Uncategorized, "formatter error")) |
7453a54e SL |
1818 | } |
1819 | } | |
1a4d82fc JJ |
1820 | } |
1821 | } | |
1a4d82fc | 1822 | |
94222f64 | 1823 | /// Creates a "by reference" adapter for this instance of `Write`. |
1a4d82fc | 1824 | /// |
94222f64 | 1825 | /// The returned adapter also implements `Write` and will simply borrow this |
85aaf69f | 1826 | /// current writer. |
c1a9b12d SL |
1827 | /// |
1828 | /// # Examples | |
1829 | /// | |
0531ce1d | 1830 | /// ```no_run |
c1a9b12d SL |
1831 | /// use std::io::Write; |
1832 | /// use std::fs::File; | |
1833 | /// | |
0531ce1d XL |
1834 | /// fn main() -> std::io::Result<()> { |
1835 | /// let mut buffer = File::create("foo.txt")?; | |
c1a9b12d | 1836 | /// |
0531ce1d | 1837 | /// let reference = buffer.by_ref(); |
c1a9b12d | 1838 | /// |
0531ce1d XL |
1839 | /// // we can use reference just like our original buffer |
1840 | /// reference.write_all(b"some bytes")?; | |
1841 | /// Ok(()) | |
1842 | /// } | |
c1a9b12d | 1843 | /// ``` |
c34b1796 | 1844 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
1845 | fn by_ref(&mut self) -> &mut Self |
1846 | where | |
1847 | Self: Sized, | |
1848 | { | |
1849 | self | |
1850 | } | |
1a4d82fc JJ |
1851 | } |
1852 | ||
c1a9b12d SL |
1853 | /// The `Seek` trait provides a cursor which can be moved within a stream of |
1854 | /// bytes. | |
1a4d82fc | 1855 | /// |
85aaf69f SL |
1856 | /// The stream typically has a fixed size, allowing seeking relative to either |
1857 | /// end or the current offset. | |
c1a9b12d SL |
1858 | /// |
1859 | /// # Examples | |
1860 | /// | |
3dfed10e | 1861 | /// [`File`]s implement `Seek`: |
c1a9b12d | 1862 | /// |
3dfed10e | 1863 | /// [`File`]: crate::fs::File |
c1a9b12d | 1864 | /// |
0531ce1d | 1865 | /// ```no_run |
c1a9b12d SL |
1866 | /// use std::io; |
1867 | /// use std::io::prelude::*; | |
1868 | /// use std::fs::File; | |
1869 | /// use std::io::SeekFrom; | |
1870 | /// | |
0531ce1d XL |
1871 | /// fn main() -> io::Result<()> { |
1872 | /// let mut f = File::open("foo.txt")?; | |
c1a9b12d | 1873 | /// |
0531ce1d XL |
1874 | /// // move the cursor 42 bytes from the start of the file |
1875 | /// f.seek(SeekFrom::Start(42))?; | |
1876 | /// Ok(()) | |
1877 | /// } | |
c1a9b12d | 1878 | /// ``` |
c34b1796 | 1879 | #[stable(feature = "rust1", since = "1.0.0")] |
ed00b5ec | 1880 | #[cfg_attr(not(test), rustc_diagnostic_item = "IoSeek")] |
85aaf69f | 1881 | pub trait Seek { |
c1a9b12d | 1882 | /// Seek to an offset, in bytes, in a stream. |
85aaf69f | 1883 | /// |
0bf4aa26 XL |
1884 | /// A seek beyond the end of a stream is allowed, but behavior is defined |
1885 | /// by the implementation. | |
85aaf69f | 1886 | /// |
c1a9b12d SL |
1887 | /// If the seek operation completed successfully, |
1888 | /// this method returns the new position from the start of the stream. | |
5bcae85e | 1889 | /// That position can be used later with [`SeekFrom::Start`]. |
85aaf69f SL |
1890 | /// |
1891 | /// # Errors | |
1892 | /// | |
17df50a5 XL |
1893 | /// Seeking can fail, for example because it might involve flushing a buffer. |
1894 | /// | |
c1a9b12d | 1895 | /// Seeking to a negative offset is considered an error. |
c34b1796 | 1896 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1897 | fn seek(&mut self, pos: SeekFrom) -> Result<u64>; |
532ac7d7 | 1898 | |
17df50a5 XL |
1899 | /// Rewind to the beginning of a stream. |
1900 | /// | |
1901 | /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`. | |
1902 | /// | |
1903 | /// # Errors | |
1904 | /// | |
1905 | /// Rewinding can fail, for example because it might involve flushing a buffer. | |
1906 | /// | |
1907 | /// # Example | |
1908 | /// | |
1909 | /// ```no_run | |
17df50a5 XL |
1910 | /// use std::io::{Read, Seek, Write}; |
1911 | /// use std::fs::OpenOptions; | |
1912 | /// | |
1913 | /// let mut f = OpenOptions::new() | |
1914 | /// .write(true) | |
1915 | /// .read(true) | |
1916 | /// .create(true) | |
1917 | /// .open("foo.txt").unwrap(); | |
1918 | /// | |
1919 | /// let hello = "Hello!\n"; | |
5e7ed085 | 1920 | /// write!(f, "{hello}").unwrap(); |
17df50a5 XL |
1921 | /// f.rewind().unwrap(); |
1922 | /// | |
1923 | /// let mut buf = String::new(); | |
1924 | /// f.read_to_string(&mut buf).unwrap(); | |
1925 | /// assert_eq!(&buf, hello); | |
1926 | /// ``` | |
136023e0 | 1927 | #[stable(feature = "seek_rewind", since = "1.55.0")] |
17df50a5 XL |
1928 | fn rewind(&mut self) -> Result<()> { |
1929 | self.seek(SeekFrom::Start(0))?; | |
1930 | Ok(()) | |
1931 | } | |
1932 | ||
532ac7d7 XL |
1933 | /// Returns the length of this stream (in bytes). |
1934 | /// | |
1935 | /// This method is implemented using up to three seek operations. If this | |
1936 | /// method returns successfully, the seek position is unchanged (i.e. the | |
1937 | /// position before calling this method is the same as afterwards). | |
1938 | /// However, if this method returns an error, the seek position is | |
1939 | /// unspecified. | |
1940 | /// | |
1941 | /// If you need to obtain the length of *many* streams and you don't care | |
1942 | /// about the seek position afterwards, you can reduce the number of seek | |
1943 | /// operations by simply calling `seek(SeekFrom::End(0))` and using its | |
1944 | /// return value (it is also the stream length). | |
1945 | /// | |
1946 | /// Note that length of a stream can change over time (for example, when | |
1947 | /// data is appended to a file). So calling this method multiple times does | |
1948 | /// not necessarily return the same length each time. | |
1949 | /// | |
532ac7d7 XL |
1950 | /// # Example |
1951 | /// | |
1952 | /// ```no_run | |
5869c6ff | 1953 | /// #![feature(seek_stream_len)] |
532ac7d7 XL |
1954 | /// use std::{ |
1955 | /// io::{self, Seek}, | |
1956 | /// fs::File, | |
1957 | /// }; | |
1958 | /// | |
1959 | /// fn main() -> io::Result<()> { | |
1960 | /// let mut f = File::open("foo.txt")?; | |
1961 | /// | |
1962 | /// let len = f.stream_len()?; | |
5e7ed085 | 1963 | /// println!("The file is currently {len} bytes long"); |
532ac7d7 XL |
1964 | /// Ok(()) |
1965 | /// } | |
1966 | /// ``` | |
5869c6ff | 1967 | #[unstable(feature = "seek_stream_len", issue = "59359")] |
532ac7d7 XL |
1968 | fn stream_len(&mut self) -> Result<u64> { |
1969 | let old_pos = self.stream_position()?; | |
1970 | let len = self.seek(SeekFrom::End(0))?; | |
1971 | ||
1972 | // Avoid seeking a third time when we were already at the end of the | |
1973 | // stream. The branch is usually way cheaper than a seek operation. | |
1974 | if old_pos != len { | |
1975 | self.seek(SeekFrom::Start(old_pos))?; | |
1976 | } | |
1977 | ||
1978 | Ok(len) | |
1979 | } | |
1980 | ||
1981 | /// Returns the current seek position from the start of the stream. | |
1982 | /// | |
1983 | /// This is equivalent to `self.seek(SeekFrom::Current(0))`. | |
1984 | /// | |
532ac7d7 XL |
1985 | /// # Example |
1986 | /// | |
1987 | /// ```no_run | |
532ac7d7 XL |
1988 | /// use std::{ |
1989 | /// io::{self, BufRead, BufReader, Seek}, | |
1990 | /// fs::File, | |
1991 | /// }; | |
1992 | /// | |
1993 | /// fn main() -> io::Result<()> { | |
1994 | /// let mut f = BufReader::new(File::open("foo.txt")?); | |
1995 | /// | |
1996 | /// let before = f.stream_position()?; | |
1997 | /// f.read_line(&mut String::new())?; | |
1998 | /// let after = f.stream_position()?; | |
1999 | /// | |
2000 | /// println!("The first line was {} bytes long", after - before); | |
2001 | /// Ok(()) | |
2002 | /// } | |
2003 | /// ``` | |
5869c6ff | 2004 | #[stable(feature = "seek_convenience", since = "1.51.0")] |
532ac7d7 XL |
2005 | fn stream_position(&mut self) -> Result<u64> { |
2006 | self.seek(SeekFrom::Current(0)) | |
2007 | } | |
4b012472 FG |
2008 | |
2009 | /// Seeks relative to the current position. | |
2010 | /// | |
2011 | /// This is equivalent to `self.seek(SeekFrom::Current(offset))` but | |
2012 | /// doesn't return the new position which can allow some implementations | |
2013 | /// such as [`BufReader`] to perform more efficient seeks. | |
2014 | /// | |
2015 | /// # Example | |
2016 | /// | |
2017 | /// ```no_run | |
2018 | /// #![feature(seek_seek_relative)] | |
2019 | /// use std::{ | |
2020 | /// io::{self, Seek}, | |
2021 | /// fs::File, | |
2022 | /// }; | |
2023 | /// | |
2024 | /// fn main() -> io::Result<()> { | |
2025 | /// let mut f = File::open("foo.txt")?; | |
2026 | /// f.seek_relative(10)?; | |
2027 | /// assert_eq!(f.stream_position()?, 10); | |
2028 | /// Ok(()) | |
2029 | /// } | |
2030 | /// ``` | |
2031 | /// | |
2032 | /// [`BufReader`]: crate::io::BufReader | |
2033 | #[unstable(feature = "seek_seek_relative", issue = "117374")] | |
2034 | fn seek_relative(&mut self, offset: i64) -> Result<()> { | |
2035 | self.seek(SeekFrom::Current(offset))?; | |
2036 | Ok(()) | |
2037 | } | |
1a4d82fc JJ |
2038 | } |
2039 | ||
85aaf69f | 2040 | /// Enumeration of possible methods to seek within an I/O object. |
5bcae85e SL |
2041 | /// |
2042 | /// It is used by the [`Seek`] trait. | |
85aaf69f | 2043 | #[derive(Copy, PartialEq, Eq, Clone, Debug)] |
c34b1796 | 2044 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2045 | pub enum SeekFrom { |
9fa01778 | 2046 | /// Sets the offset to the provided number of bytes. |
c34b1796 | 2047 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 2048 | Start(#[stable(feature = "rust1", since = "1.0.0")] u64), |
1a4d82fc | 2049 | |
9fa01778 | 2050 | /// Sets the offset to the size of this object plus the specified number of |
85aaf69f SL |
2051 | /// bytes. |
2052 | /// | |
9cc50fc6 | 2053 | /// It is possible to seek beyond the end of an object, but it's an error to |
85aaf69f | 2054 | /// seek before byte 0. |
c34b1796 | 2055 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 2056 | End(#[stable(feature = "rust1", since = "1.0.0")] i64), |
1a4d82fc | 2057 | |
9fa01778 | 2058 | /// Sets the offset to the current position plus the specified number of |
85aaf69f SL |
2059 | /// bytes. |
2060 | /// | |
9cc50fc6 | 2061 | /// It is possible to seek beyond the end of an object, but it's an error to |
85aaf69f | 2062 | /// seek before byte 0. |
c34b1796 | 2063 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 2064 | Current(#[stable(feature = "rust1", since = "1.0.0")] i64), |
1a4d82fc JJ |
2065 | } |
2066 | ||
60c5eb7d | 2067 | fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> { |
c34b1796 | 2068 | let mut read = 0; |
85aaf69f SL |
2069 | loop { |
2070 | let (done, used) = { | |
2071 | let available = match r.fill_buf() { | |
2072 | Ok(n) => n, | |
781aab86 | 2073 | Err(ref e) if e.is_interrupted() => continue, |
60c5eb7d | 2074 | Err(e) => return Err(e), |
85aaf69f | 2075 | }; |
9cc50fc6 | 2076 | match memchr::memchr(delim, available) { |
85aaf69f | 2077 | Some(i) => { |
0731742a | 2078 | buf.extend_from_slice(&available[..=i]); |
85aaf69f SL |
2079 | (true, i + 1) |
2080 | } | |
2081 | None => { | |
92a42be0 | 2082 | buf.extend_from_slice(available); |
85aaf69f SL |
2083 | (false, available.len()) |
2084 | } | |
2085 | } | |
2086 | }; | |
2087 | r.consume(used); | |
c34b1796 | 2088 | read += used; |
85aaf69f | 2089 | if done || used == 0 { |
c34b1796 | 2090 | return Ok(read); |
1a4d82fc JJ |
2091 | } |
2092 | } | |
2093 | } | |
2094 | ||
4b012472 FG |
2095 | fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> { |
2096 | let mut read = 0; | |
2097 | loop { | |
2098 | let (done, used) = { | |
2099 | let available = match r.fill_buf() { | |
2100 | Ok(n) => n, | |
2101 | Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, | |
2102 | Err(e) => return Err(e), | |
2103 | }; | |
2104 | match memchr::memchr(delim, available) { | |
2105 | Some(i) => (true, i + 1), | |
2106 | None => (false, available.len()), | |
2107 | } | |
2108 | }; | |
2109 | r.consume(used); | |
2110 | read += used; | |
2111 | if done || used == 0 { | |
2112 | return Ok(read); | |
2113 | } | |
2114 | } | |
2115 | } | |
2116 | ||
c1a9b12d SL |
2117 | /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it |
2118 | /// to perform extra ways of reading. | |
2119 | /// | |
2120 | /// For example, reading line-by-line is inefficient without using a buffer, so | |
2121 | /// if you want to read by line, you'll need `BufRead`, which includes a | |
cc61c64b | 2122 | /// [`read_line`] method as well as a [`lines`] iterator. |
c1a9b12d SL |
2123 | /// |
2124 | /// # Examples | |
2125 | /// | |
2126 | /// A locked standard input implements `BufRead`: | |
2127 | /// | |
0531ce1d | 2128 | /// ```no_run |
c1a9b12d SL |
2129 | /// use std::io; |
2130 | /// use std::io::prelude::*; | |
2131 | /// | |
2132 | /// let stdin = io::stdin(); | |
2133 | /// for line in stdin.lock().lines() { | |
2134 | /// println!("{}", line.unwrap()); | |
2135 | /// } | |
2136 | /// ``` | |
2137 | /// | |
c30ab7b3 SL |
2138 | /// If you have something that implements [`Read`], you can use the [`BufReader` |
2139 | /// type][`BufReader`] to turn it into a `BufRead`. | |
c1a9b12d | 2140 | /// |
c30ab7b3 SL |
2141 | /// For example, [`File`] implements [`Read`], but not `BufRead`. |
2142 | /// [`BufReader`] to the rescue! | |
85aaf69f | 2143 | /// |
3dfed10e XL |
2144 | /// [`File`]: crate::fs::File |
2145 | /// [`read_line`]: BufRead::read_line | |
2146 | /// [`lines`]: BufRead::lines | |
c1a9b12d | 2147 | /// |
0531ce1d | 2148 | /// ```no_run |
c1a9b12d SL |
2149 | /// use std::io::{self, BufReader}; |
2150 | /// use std::io::prelude::*; | |
2151 | /// use std::fs::File; | |
2152 | /// | |
0531ce1d XL |
2153 | /// fn main() -> io::Result<()> { |
2154 | /// let f = File::open("foo.txt")?; | |
2155 | /// let f = BufReader::new(f); | |
c1a9b12d | 2156 | /// |
0531ce1d XL |
2157 | /// for line in f.lines() { |
2158 | /// println!("{}", line.unwrap()); | |
2159 | /// } | |
c1a9b12d | 2160 | /// |
0531ce1d XL |
2161 | /// Ok(()) |
2162 | /// } | |
c1a9b12d | 2163 | /// ``` |
c34b1796 | 2164 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2165 | pub trait BufRead: Read { |
b7449926 XL |
2166 | /// Returns the contents of the internal buffer, filling it with more data |
2167 | /// from the inner reader if it is empty. | |
85aaf69f | 2168 | /// |
c1a9b12d | 2169 | /// This function is a lower-level call. It needs to be paired with the |
cc61c64b | 2170 | /// [`consume`] method to function properly. When calling this |
c1a9b12d | 2171 | /// method, none of the contents will be "read" in the sense that later |
cc61c64b | 2172 | /// calling `read` may return the same contents. As such, [`consume`] must |
c30ab7b3 | 2173 | /// be called with the number of bytes that are consumed from this buffer to |
c1a9b12d | 2174 | /// ensure that the bytes are never returned twice. |
1a4d82fc | 2175 | /// |
3dfed10e | 2176 | /// [`consume`]: BufRead::consume |
1a4d82fc | 2177 | /// |
85aaf69f SL |
2178 | /// An empty buffer returned indicates that the stream has reached EOF. |
2179 | /// | |
2180 | /// # Errors | |
1a4d82fc JJ |
2181 | /// |
2182 | /// This function will return an I/O error if the underlying reader was | |
85aaf69f | 2183 | /// read, but returned an error. |
c1a9b12d SL |
2184 | /// |
2185 | /// # Examples | |
2186 | /// | |
2187 | /// A locked standard input implements `BufRead`: | |
2188 | /// | |
0531ce1d | 2189 | /// ```no_run |
c1a9b12d SL |
2190 | /// use std::io; |
2191 | /// use std::io::prelude::*; | |
2192 | /// | |
2193 | /// let stdin = io::stdin(); | |
2194 | /// let mut stdin = stdin.lock(); | |
2195 | /// | |
48663c56 | 2196 | /// let buffer = stdin.fill_buf().unwrap(); |
c1a9b12d | 2197 | /// |
48663c56 | 2198 | /// // work with buffer |
5e7ed085 | 2199 | /// println!("{buffer:?}"); |
c1a9b12d SL |
2200 | /// |
2201 | /// // ensure the bytes we worked with aren't returned again later | |
48663c56 | 2202 | /// let length = buffer.len(); |
c1a9b12d SL |
2203 | /// stdin.consume(length); |
2204 | /// ``` | |
c34b1796 | 2205 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2206 | fn fill_buf(&mut self) -> Result<&[u8]>; |
1a4d82fc JJ |
2207 | |
2208 | /// Tells this buffer that `amt` bytes have been consumed from the buffer, | |
2209 | /// so they should no longer be returned in calls to `read`. | |
c34b1796 | 2210 | /// |
c1a9b12d | 2211 | /// This function is a lower-level call. It needs to be paired with the |
cc61c64b | 2212 | /// [`fill_buf`] method to function properly. This function does |
c1a9b12d | 2213 | /// not perform any I/O, it simply informs this object that some amount of |
cc61c64b | 2214 | /// its buffer, returned from [`fill_buf`], has been consumed and should |
c30ab7b3 | 2215 | /// no longer be returned. As such, this function may do odd things if |
cc61c64b | 2216 | /// [`fill_buf`] isn't called before calling it. |
c1a9b12d SL |
2217 | /// |
2218 | /// The `amt` must be `<=` the number of bytes in the buffer returned by | |
cc61c64b | 2219 | /// [`fill_buf`]. |
c34b1796 | 2220 | /// |
c1a9b12d | 2221 | /// # Examples |
c34b1796 | 2222 | /// |
cc61c64b | 2223 | /// Since `consume()` is meant to be used with [`fill_buf`], |
c1a9b12d | 2224 | /// that method's example includes an example of `consume()`. |
c30ab7b3 | 2225 | /// |
3dfed10e | 2226 | /// [`fill_buf`]: BufRead::fill_buf |
c34b1796 | 2227 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2228 | fn consume(&mut self, amt: usize); |
1a4d82fc | 2229 | |
136023e0 XL |
2230 | /// Check if the underlying `Read` has any data left to be read. |
2231 | /// | |
2232 | /// This function may fill the buffer to check for data, | |
2233 | /// so this functions returns `Result<bool>`, not `bool`. | |
2234 | /// | |
2235 | /// Default implementation calls `fill_buf` and checks that | |
2236 | /// returned slice is empty (which means that there is no data left, | |
2237 | /// since EOF is reached). | |
2238 | /// | |
2239 | /// Examples | |
2240 | /// | |
2241 | /// ``` | |
2242 | /// #![feature(buf_read_has_data_left)] | |
2243 | /// use std::io; | |
2244 | /// use std::io::prelude::*; | |
2245 | /// | |
2246 | /// let stdin = io::stdin(); | |
2247 | /// let mut stdin = stdin.lock(); | |
2248 | /// | |
2249 | /// while stdin.has_data_left().unwrap() { | |
2250 | /// let mut line = String::new(); | |
2251 | /// stdin.read_line(&mut line).unwrap(); | |
2252 | /// // work with line | |
5e7ed085 | 2253 | /// println!("{line:?}"); |
136023e0 XL |
2254 | /// } |
2255 | /// ``` | |
2256 | #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")] | |
2257 | fn has_data_left(&mut self) -> Result<bool> { | |
2258 | self.fill_buf().map(|b| !b.is_empty()) | |
2259 | } | |
2260 | ||
c30ab7b3 | 2261 | /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached. |
1a4d82fc | 2262 | /// |
c1a9b12d SL |
2263 | /// This function will read bytes from the underlying stream until the |
2264 | /// delimiter or EOF is found. Once found, all bytes up to, and including, | |
2265 | /// the delimiter (if found) will be appended to `buf`. | |
1a4d82fc | 2266 | /// |
c30ab7b3 | 2267 | /// If successful, this function will return the total number of bytes read. |
1a4d82fc | 2268 | /// |
f035d41b XL |
2269 | /// This function is blocking and should be used carefully: it is possible for |
2270 | /// an attacker to continuously send bytes without ever sending the delimiter | |
2271 | /// or EOF. | |
2272 | /// | |
85aaf69f | 2273 | /// # Errors |
1a4d82fc | 2274 | /// |
c30ab7b3 | 2275 | /// This function will ignore all instances of [`ErrorKind::Interrupted`] and |
cc61c64b | 2276 | /// will otherwise return any errors returned by [`fill_buf`]. |
1a4d82fc | 2277 | /// |
85aaf69f SL |
2278 | /// If an I/O error is encountered then all bytes read so far will be |
2279 | /// present in `buf` and its length will have been adjusted appropriately. | |
c1a9b12d | 2280 | /// |
3dfed10e | 2281 | /// [`fill_buf`]: BufRead::fill_buf |
c30ab7b3 | 2282 | /// |
cc61c64b | 2283 | /// # Examples |
c1a9b12d | 2284 | /// |
cc61c64b XL |
2285 | /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In |
2286 | /// this example, we use [`Cursor`] to read all the bytes in a byte slice | |
2287 | /// in hyphen delimited segments: | |
c1a9b12d | 2288 | /// |
cc61c64b XL |
2289 | /// ``` |
2290 | /// use std::io::{self, BufRead}; | |
2291 | /// | |
2292 | /// let mut cursor = io::Cursor::new(b"lorem-ipsum"); | |
2293 | /// let mut buf = vec![]; | |
2294 | /// | |
2295 | /// // cursor is at 'l' | |
2296 | /// let num_bytes = cursor.read_until(b'-', &mut buf) | |
2297 | /// .expect("reading from cursor won't fail"); | |
2298 | /// assert_eq!(num_bytes, 6); | |
2299 | /// assert_eq!(buf, b"lorem-"); | |
2300 | /// buf.clear(); | |
2301 | /// | |
2302 | /// // cursor is at 'i' | |
2303 | /// let num_bytes = cursor.read_until(b'-', &mut buf) | |
2304 | /// .expect("reading from cursor won't fail"); | |
2305 | /// assert_eq!(num_bytes, 5); | |
2306 | /// assert_eq!(buf, b"ipsum"); | |
2307 | /// buf.clear(); | |
2308 | /// | |
2309 | /// // cursor is at EOF | |
2310 | /// let num_bytes = cursor.read_until(b'-', &mut buf) | |
2311 | /// .expect("reading from cursor won't fail"); | |
2312 | /// assert_eq!(num_bytes, 0); | |
2313 | /// assert_eq!(buf, b""); | |
c1a9b12d | 2314 | /// ``` |
c34b1796 AL |
2315 | #[stable(feature = "rust1", since = "1.0.0")] |
2316 | fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> { | |
85aaf69f | 2317 | read_until(self, byte, buf) |
1a4d82fc JJ |
2318 | } |
2319 | ||
4b012472 FG |
2320 | /// Skip all bytes until the delimiter `byte` or EOF is reached. |
2321 | /// | |
2322 | /// This function will read (and discard) bytes from the underlying stream until the | |
2323 | /// delimiter or EOF is found. | |
2324 | /// | |
2325 | /// If successful, this function will return the total number of bytes read, | |
2326 | /// including the delimiter byte. | |
2327 | /// | |
2328 | /// This is useful for efficiently skipping data such as NUL-terminated strings | |
2329 | /// in binary file formats without buffering. | |
2330 | /// | |
2331 | /// This function is blocking and should be used carefully: it is possible for | |
2332 | /// an attacker to continuously send bytes without ever sending the delimiter | |
2333 | /// or EOF. | |
2334 | /// | |
2335 | /// # Errors | |
2336 | /// | |
2337 | /// This function will ignore all instances of [`ErrorKind::Interrupted`] and | |
2338 | /// will otherwise return any errors returned by [`fill_buf`]. | |
2339 | /// | |
2340 | /// If an I/O error is encountered then all bytes read so far will be | |
2341 | /// present in `buf` and its length will have been adjusted appropriately. | |
2342 | /// | |
2343 | /// [`fill_buf`]: BufRead::fill_buf | |
2344 | /// | |
2345 | /// # Examples | |
2346 | /// | |
2347 | /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In | |
2348 | /// this example, we use [`Cursor`] to read some NUL-terminated information | |
2349 | /// about Ferris from a binary string, skipping the fun fact: | |
2350 | /// | |
2351 | /// ``` | |
2352 | /// #![feature(bufread_skip_until)] | |
2353 | /// | |
2354 | /// use std::io::{self, BufRead}; | |
2355 | /// | |
2356 | /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0"); | |
2357 | /// | |
2358 | /// // read name | |
2359 | /// let mut name = Vec::new(); | |
2360 | /// let num_bytes = cursor.read_until(b'\0', &mut name) | |
2361 | /// .expect("reading from cursor won't fail"); | |
2362 | /// assert_eq!(num_bytes, 7); | |
2363 | /// assert_eq!(name, b"Ferris\0"); | |
2364 | /// | |
2365 | /// // skip fun fact | |
2366 | /// let num_bytes = cursor.skip_until(b'\0') | |
2367 | /// .expect("reading from cursor won't fail"); | |
2368 | /// assert_eq!(num_bytes, 30); | |
2369 | /// | |
2370 | /// // read animal type | |
2371 | /// let mut animal = Vec::new(); | |
2372 | /// let num_bytes = cursor.read_until(b'\0', &mut animal) | |
2373 | /// .expect("reading from cursor won't fail"); | |
2374 | /// assert_eq!(num_bytes, 11); | |
2375 | /// assert_eq!(animal, b"Crustacean\0"); | |
2376 | /// ``` | |
2377 | #[unstable(feature = "bufread_skip_until", issue = "111735")] | |
2378 | fn skip_until(&mut self, byte: u8) -> Result<usize> { | |
2379 | skip_until(self, byte) | |
2380 | } | |
2381 | ||
3dfed10e | 2382 | /// Read all bytes until a newline (the `0xA` byte) is reached, and append |
9c376795 FG |
2383 | /// them to the provided `String` buffer. |
2384 | /// | |
2385 | /// Previous content of the buffer will be preserved. To avoid appending to | |
2386 | /// the buffer, you need to [`clear`] it first. | |
1a4d82fc | 2387 | /// |
c1a9b12d | 2388 | /// This function will read bytes from the underlying stream until the |
3dfed10e | 2389 | /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes |
c1a9b12d SL |
2390 | /// up to, and including, the delimiter (if found) will be appended to |
2391 | /// `buf`. | |
1a4d82fc | 2392 | /// |
c30ab7b3 | 2393 | /// If successful, this function will return the total number of bytes read. |
85aaf69f | 2394 | /// |
3dfed10e | 2395 | /// If this function returns [`Ok(0)`], the stream has reached EOF. |
abe05a73 | 2396 | /// |
f035d41b XL |
2397 | /// This function is blocking and should be used carefully: it is possible for |
2398 | /// an attacker to continuously send bytes without ever sending a newline | |
9c376795 | 2399 | /// or EOF. You can use [`take`] to limit the maximum number of bytes read. |
f035d41b | 2400 | /// |
3dfed10e | 2401 | /// [`Ok(0)`]: Ok |
9c376795 FG |
2402 | /// [`clear`]: String::clear |
2403 | /// [`take`]: crate::io::Read::take | |
3dfed10e | 2404 | /// |
85aaf69f SL |
2405 | /// # Errors |
2406 | /// | |
cc61c64b | 2407 | /// This function has the same error semantics as [`read_until`] and will |
c30ab7b3 SL |
2408 | /// also return an error if the read bytes are not valid UTF-8. If an I/O |
2409 | /// error is encountered then `buf` may contain some bytes already read in | |
2410 | /// the event that all data read so far was valid UTF-8. | |
c1a9b12d | 2411 | /// |
3dfed10e | 2412 | /// [`read_until`]: BufRead::read_until |
0531ce1d | 2413 | /// |
c1a9b12d SL |
2414 | /// # Examples |
2415 | /// | |
cc61c64b XL |
2416 | /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In |
2417 | /// this example, we use [`Cursor`] to read all the lines in a byte slice: | |
c1a9b12d | 2418 | /// |
c1a9b12d | 2419 | /// ``` |
cc61c64b XL |
2420 | /// use std::io::{self, BufRead}; |
2421 | /// | |
2422 | /// let mut cursor = io::Cursor::new(b"foo\nbar"); | |
2423 | /// let mut buf = String::new(); | |
2424 | /// | |
2425 | /// // cursor is at 'f' | |
2426 | /// let num_bytes = cursor.read_line(&mut buf) | |
2427 | /// .expect("reading from cursor won't fail"); | |
2428 | /// assert_eq!(num_bytes, 4); | |
2429 | /// assert_eq!(buf, "foo\n"); | |
2430 | /// buf.clear(); | |
2431 | /// | |
2432 | /// // cursor is at 'b' | |
2433 | /// let num_bytes = cursor.read_line(&mut buf) | |
2434 | /// .expect("reading from cursor won't fail"); | |
2435 | /// assert_eq!(num_bytes, 3); | |
2436 | /// assert_eq!(buf, "bar"); | |
2437 | /// buf.clear(); | |
2438 | /// | |
2439 | /// // cursor is at EOF | |
2440 | /// let num_bytes = cursor.read_line(&mut buf) | |
2441 | /// .expect("reading from cursor won't fail"); | |
2442 | /// assert_eq!(num_bytes, 0); | |
2443 | /// assert_eq!(buf, ""); | |
c1a9b12d | 2444 | /// ``` |
c34b1796 AL |
2445 | #[stable(feature = "rust1", since = "1.0.0")] |
2446 | fn read_line(&mut self, buf: &mut String) -> Result<usize> { | |
85aaf69f SL |
2447 | // Note that we are not calling the `.read_until` method here, but |
2448 | // rather our hardcoded implementation. For more details as to why, see | |
2449 | // the comments in `read_to_end`. | |
c295e0f8 | 2450 | unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) } |
1a4d82fc | 2451 | } |
1a4d82fc | 2452 | |
85aaf69f SL |
2453 | /// Returns an iterator over the contents of this reader split on the byte |
2454 | /// `byte`. | |
1a4d82fc | 2455 | /// |
85aaf69f | 2456 | /// The iterator returned from this function will return instances of |
c295e0f8 | 2457 | /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have |
c30ab7b3 | 2458 | /// the delimiter byte at the end. |
1a4d82fc | 2459 | /// |
cc61c64b | 2460 | /// This function will yield errors whenever [`read_until`] would have |
c30ab7b3 | 2461 | /// also yielded an error. |
c1a9b12d | 2462 | /// |
c295e0f8 | 2463 | /// [io::Result]: self::Result "io::Result" |
3dfed10e | 2464 | /// [`read_until`]: BufRead::read_until |
cc61c64b | 2465 | /// |
c1a9b12d SL |
2466 | /// # Examples |
2467 | /// | |
cc61c64b XL |
2468 | /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In |
2469 | /// this example, we use [`Cursor`] to iterate over all hyphen delimited | |
2470 | /// segments in a byte slice | |
c1a9b12d SL |
2471 | /// |
2472 | /// ``` | |
cc61c64b | 2473 | /// use std::io::{self, BufRead}; |
c1a9b12d | 2474 | /// |
cc61c64b | 2475 | /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor"); |
c1a9b12d | 2476 | /// |
cc61c64b XL |
2477 | /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap()); |
2478 | /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec())); | |
2479 | /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec())); | |
2480 | /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec())); | |
2481 | /// assert_eq!(split_iter.next(), None); | |
c1a9b12d | 2482 | /// ``` |
c34b1796 | 2483 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
2484 | fn split(self, byte: u8) -> Split<Self> |
2485 | where | |
2486 | Self: Sized, | |
2487 | { | |
85aaf69f SL |
2488 | Split { buf: self, delim: byte } |
2489 | } | |
1a4d82fc | 2490 | |
85aaf69f | 2491 | /// Returns an iterator over the lines of this reader. |
1a4d82fc | 2492 | /// |
85aaf69f | 2493 | /// The iterator returned from this function will yield instances of |
c295e0f8 | 2494 | /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline |
3dfed10e | 2495 | /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end. |
c1a9b12d | 2496 | /// |
c295e0f8 | 2497 | /// [io::Result]: self::Result "io::Result" |
c30ab7b3 | 2498 | /// |
c1a9b12d SL |
2499 | /// # Examples |
2500 | /// | |
cc61c64b XL |
2501 | /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In |
2502 | /// this example, we use [`Cursor`] to iterate over all the lines in a byte | |
2503 | /// slice. | |
2504 | /// | |
c1a9b12d | 2505 | /// ``` |
cc61c64b | 2506 | /// use std::io::{self, BufRead}; |
c1a9b12d | 2507 | /// |
cc61c64b | 2508 | /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor"); |
c1a9b12d | 2509 | /// |
cc61c64b XL |
2510 | /// let mut lines_iter = cursor.lines().map(|l| l.unwrap()); |
2511 | /// assert_eq!(lines_iter.next(), Some(String::from("lorem"))); | |
2512 | /// assert_eq!(lines_iter.next(), Some(String::from("ipsum"))); | |
2513 | /// assert_eq!(lines_iter.next(), Some(String::from("dolor"))); | |
2514 | /// assert_eq!(lines_iter.next(), None); | |
c1a9b12d | 2515 | /// ``` |
32a655c1 SL |
2516 | /// |
2517 | /// # Errors | |
2518 | /// | |
cc61c64b | 2519 | /// Each line of the iterator has the same error semantics as [`BufRead::read_line`]. |
c34b1796 | 2520 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
2521 | fn lines(self) -> Lines<Self> |
2522 | where | |
2523 | Self: Sized, | |
2524 | { | |
85aaf69f SL |
2525 | Lines { buf: self } |
2526 | } | |
2527 | } | |
2528 | ||
94222f64 | 2529 | /// Adapter to chain together two readers. |
c1a9b12d | 2530 | /// |
cc61c64b XL |
2531 | /// This struct is generally created by calling [`chain`] on a reader. |
2532 | /// Please see the documentation of [`chain`] for more details. | |
85aaf69f | 2533 | /// |
3dfed10e | 2534 | /// [`chain`]: Read::chain |
c34b1796 | 2535 | #[stable(feature = "rust1", since = "1.0.0")] |
cdc7bbd5 | 2536 | #[derive(Debug)] |
85aaf69f SL |
2537 | pub struct Chain<T, U> { |
2538 | first: T, | |
2539 | second: U, | |
2540 | done_first: bool, | |
1a4d82fc JJ |
2541 | } |
2542 | ||
7cac9316 XL |
2543 | impl<T, U> Chain<T, U> { |
2544 | /// Consumes the `Chain`, returning the wrapped readers. | |
2545 | /// | |
2546 | /// # Examples | |
2547 | /// | |
0531ce1d XL |
2548 | /// ```no_run |
2549 | /// use std::io; | |
7cac9316 XL |
2550 | /// use std::io::prelude::*; |
2551 | /// use std::fs::File; | |
2552 | /// | |
0531ce1d XL |
2553 | /// fn main() -> io::Result<()> { |
2554 | /// let mut foo_file = File::open("foo.txt")?; | |
2555 | /// let mut bar_file = File::open("bar.txt")?; | |
7cac9316 | 2556 | /// |
0531ce1d XL |
2557 | /// let chain = foo_file.chain(bar_file); |
2558 | /// let (foo_file, bar_file) = chain.into_inner(); | |
2559 | /// Ok(()) | |
2560 | /// } | |
7cac9316 | 2561 | /// ``` |
041b39d2 | 2562 | #[stable(feature = "more_io_inner_methods", since = "1.20.0")] |
7cac9316 XL |
2563 | pub fn into_inner(self) -> (T, U) { |
2564 | (self.first, self.second) | |
2565 | } | |
2566 | ||
2567 | /// Gets references to the underlying readers in this `Chain`. | |
2568 | /// | |
2569 | /// # Examples | |
2570 | /// | |
0531ce1d XL |
2571 | /// ```no_run |
2572 | /// use std::io; | |
7cac9316 XL |
2573 | /// use std::io::prelude::*; |
2574 | /// use std::fs::File; | |
2575 | /// | |
0531ce1d XL |
2576 | /// fn main() -> io::Result<()> { |
2577 | /// let mut foo_file = File::open("foo.txt")?; | |
2578 | /// let mut bar_file = File::open("bar.txt")?; | |
7cac9316 | 2579 | /// |
0531ce1d XL |
2580 | /// let chain = foo_file.chain(bar_file); |
2581 | /// let (foo_file, bar_file) = chain.get_ref(); | |
2582 | /// Ok(()) | |
2583 | /// } | |
7cac9316 | 2584 | /// ``` |
041b39d2 | 2585 | #[stable(feature = "more_io_inner_methods", since = "1.20.0")] |
7cac9316 XL |
2586 | pub fn get_ref(&self) -> (&T, &U) { |
2587 | (&self.first, &self.second) | |
2588 | } | |
2589 | ||
2590 | /// Gets mutable references to the underlying readers in this `Chain`. | |
2591 | /// | |
2592 | /// Care should be taken to avoid modifying the internal I/O state of the | |
2593 | /// underlying readers as doing so may corrupt the internal state of this | |
2594 | /// `Chain`. | |
2595 | /// | |
2596 | /// # Examples | |
2597 | /// | |
0531ce1d XL |
2598 | /// ```no_run |
2599 | /// use std::io; | |
7cac9316 XL |
2600 | /// use std::io::prelude::*; |
2601 | /// use std::fs::File; | |
2602 | /// | |
0531ce1d XL |
2603 | /// fn main() -> io::Result<()> { |
2604 | /// let mut foo_file = File::open("foo.txt")?; | |
2605 | /// let mut bar_file = File::open("bar.txt")?; | |
7cac9316 | 2606 | /// |
0531ce1d XL |
2607 | /// let mut chain = foo_file.chain(bar_file); |
2608 | /// let (foo_file, bar_file) = chain.get_mut(); | |
2609 | /// Ok(()) | |
2610 | /// } | |
7cac9316 | 2611 | /// ``` |
041b39d2 | 2612 | #[stable(feature = "more_io_inner_methods", since = "1.20.0")] |
7cac9316 XL |
2613 | pub fn get_mut(&mut self) -> (&mut T, &mut U) { |
2614 | (&mut self.first, &mut self.second) | |
2615 | } | |
2616 | } | |
2617 | ||
c34b1796 | 2618 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2619 | impl<T: Read, U: Read> Read for Chain<T, U> { |
2620 | fn read(&mut self, buf: &mut [u8]) -> Result<usize> { | |
2621 | if !self.done_first { | |
54a0048b | 2622 | match self.first.read(buf)? { |
416331ca | 2623 | 0 if !buf.is_empty() => self.done_first = true, |
85aaf69f SL |
2624 | n => return Ok(n), |
2625 | } | |
2626 | } | |
2627 | self.second.read(buf) | |
2628 | } | |
041b39d2 | 2629 | |
48663c56 | 2630 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> { |
9fa01778 XL |
2631 | if !self.done_first { |
2632 | match self.first.read_vectored(bufs)? { | |
2633 | 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true, | |
2634 | n => return Ok(n), | |
2635 | } | |
2636 | } | |
2637 | self.second.read_vectored(bufs) | |
2638 | } | |
1a4d82fc JJ |
2639 | } |
2640 | ||
54a0048b SL |
2641 | #[stable(feature = "chain_bufread", since = "1.9.0")] |
2642 | impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> { | |
2643 | fn fill_buf(&mut self) -> Result<&[u8]> { | |
2644 | if !self.done_first { | |
2645 | match self.first.fill_buf()? { | |
60c5eb7d XL |
2646 | buf if buf.is_empty() => { |
2647 | self.done_first = true; | |
2648 | } | |
54a0048b SL |
2649 | buf => return Ok(buf), |
2650 | } | |
2651 | } | |
2652 | self.second.fill_buf() | |
2653 | } | |
2654 | ||
2655 | fn consume(&mut self, amt: usize) { | |
60c5eb7d | 2656 | if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) } |
54a0048b SL |
2657 | } |
2658 | } | |
2659 | ||
6a06907d | 2660 | impl<T, U> SizeHint for Chain<T, U> { |
136023e0 | 2661 | #[inline] |
6a06907d XL |
2662 | fn lower_bound(&self) -> usize { |
2663 | SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second) | |
2664 | } | |
2665 | ||
136023e0 | 2666 | #[inline] |
6a06907d XL |
2667 | fn upper_bound(&self) -> Option<usize> { |
2668 | match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) { | |
136023e0 | 2669 | (Some(first), Some(second)) => first.checked_add(second), |
6a06907d XL |
2670 | _ => None, |
2671 | } | |
2672 | } | |
2673 | } | |
2674 | ||
94222f64 | 2675 | /// Reader adapter which limits the bytes read from an underlying reader. |
1a4d82fc | 2676 | /// |
cc61c64b XL |
2677 | /// This struct is generally created by calling [`take`] on a reader. |
2678 | /// Please see the documentation of [`take`] for more details. | |
c1a9b12d | 2679 | /// |
3dfed10e | 2680 | /// [`take`]: Read::take |
c34b1796 | 2681 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 2682 | #[derive(Debug)] |
85aaf69f SL |
2683 | pub struct Take<T> { |
2684 | inner: T, | |
2685 | limit: u64, | |
1a4d82fc JJ |
2686 | } |
2687 | ||
85aaf69f SL |
2688 | impl<T> Take<T> { |
2689 | /// Returns the number of bytes that can be read before this instance will | |
2690 | /// return EOF. | |
1a4d82fc | 2691 | /// |
85aaf69f | 2692 | /// # Note |
1a4d82fc | 2693 | /// |
476ff2be SL |
2694 | /// This instance may reach `EOF` after reading fewer bytes than indicated by |
2695 | /// this method if the underlying [`Read`] instance reaches EOF. | |
2696 | /// | |
5bcae85e SL |
2697 | /// # Examples |
2698 | /// | |
0531ce1d | 2699 | /// ```no_run |
5bcae85e SL |
2700 | /// use std::io; |
2701 | /// use std::io::prelude::*; | |
2702 | /// use std::fs::File; | |
2703 | /// | |
0531ce1d XL |
2704 | /// fn main() -> io::Result<()> { |
2705 | /// let f = File::open("foo.txt")?; | |
5bcae85e | 2706 | /// |
0531ce1d XL |
2707 | /// // read at most five bytes |
2708 | /// let handle = f.take(5); | |
5bcae85e | 2709 | /// |
0531ce1d XL |
2710 | /// println!("limit: {}", handle.limit()); |
2711 | /// Ok(()) | |
2712 | /// } | |
5bcae85e | 2713 | /// ``` |
c34b1796 | 2714 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
2715 | pub fn limit(&self) -> u64 { |
2716 | self.limit | |
2717 | } | |
9e0c209e | 2718 | |
041b39d2 XL |
2719 | /// Sets the number of bytes that can be read before this instance will |
2720 | /// return EOF. This is the same as constructing a new `Take` instance, so | |
2721 | /// the amount of bytes read and the previous limit value don't matter when | |
2722 | /// calling this method. | |
2723 | /// | |
2724 | /// # Examples | |
2725 | /// | |
0531ce1d | 2726 | /// ```no_run |
041b39d2 XL |
2727 | /// use std::io; |
2728 | /// use std::io::prelude::*; | |
2729 | /// use std::fs::File; | |
2730 | /// | |
0531ce1d XL |
2731 | /// fn main() -> io::Result<()> { |
2732 | /// let f = File::open("foo.txt")?; | |
041b39d2 | 2733 | /// |
0531ce1d XL |
2734 | /// // read at most five bytes |
2735 | /// let mut handle = f.take(5); | |
2736 | /// handle.set_limit(10); | |
041b39d2 | 2737 | /// |
0531ce1d XL |
2738 | /// assert_eq!(handle.limit(), 10); |
2739 | /// Ok(()) | |
2740 | /// } | |
041b39d2 | 2741 | /// ``` |
83c7162d | 2742 | #[stable(feature = "take_set_limit", since = "1.27.0")] |
041b39d2 XL |
2743 | pub fn set_limit(&mut self, limit: u64) { |
2744 | self.limit = limit; | |
2745 | } | |
2746 | ||
9e0c209e SL |
2747 | /// Consumes the `Take`, returning the wrapped reader. |
2748 | /// | |
2749 | /// # Examples | |
2750 | /// | |
0531ce1d | 2751 | /// ```no_run |
9e0c209e SL |
2752 | /// use std::io; |
2753 | /// use std::io::prelude::*; | |
2754 | /// use std::fs::File; | |
2755 | /// | |
0531ce1d XL |
2756 | /// fn main() -> io::Result<()> { |
2757 | /// let mut file = File::open("foo.txt")?; | |
9e0c209e | 2758 | /// |
0531ce1d XL |
2759 | /// let mut buffer = [0; 5]; |
2760 | /// let mut handle = file.take(5); | |
2761 | /// handle.read(&mut buffer)?; | |
9e0c209e | 2762 | /// |
0531ce1d XL |
2763 | /// let file = handle.into_inner(); |
2764 | /// Ok(()) | |
2765 | /// } | |
9e0c209e | 2766 | /// ``` |
476ff2be | 2767 | #[stable(feature = "io_take_into_inner", since = "1.15.0")] |
9e0c209e SL |
2768 | pub fn into_inner(self) -> T { |
2769 | self.inner | |
2770 | } | |
7cac9316 XL |
2771 | |
2772 | /// Gets a reference to the underlying reader. | |
2773 | /// | |
2774 | /// # Examples | |
2775 | /// | |
0531ce1d | 2776 | /// ```no_run |
7cac9316 XL |
2777 | /// use std::io; |
2778 | /// use std::io::prelude::*; | |
2779 | /// use std::fs::File; | |
2780 | /// | |
0531ce1d XL |
2781 | /// fn main() -> io::Result<()> { |
2782 | /// let mut file = File::open("foo.txt")?; | |
7cac9316 | 2783 | /// |
0531ce1d XL |
2784 | /// let mut buffer = [0; 5]; |
2785 | /// let mut handle = file.take(5); | |
2786 | /// handle.read(&mut buffer)?; | |
7cac9316 | 2787 | /// |
0531ce1d XL |
2788 | /// let file = handle.get_ref(); |
2789 | /// Ok(()) | |
2790 | /// } | |
7cac9316 | 2791 | /// ``` |
041b39d2 | 2792 | #[stable(feature = "more_io_inner_methods", since = "1.20.0")] |
7cac9316 XL |
2793 | pub fn get_ref(&self) -> &T { |
2794 | &self.inner | |
2795 | } | |
2796 | ||
2797 | /// Gets a mutable reference to the underlying reader. | |
2798 | /// | |
2799 | /// Care should be taken to avoid modifying the internal I/O state of the | |
2800 | /// underlying reader as doing so may corrupt the internal limit of this | |
2801 | /// `Take`. | |
2802 | /// | |
2803 | /// # Examples | |
2804 | /// | |
0531ce1d | 2805 | /// ```no_run |
7cac9316 XL |
2806 | /// use std::io; |
2807 | /// use std::io::prelude::*; | |
2808 | /// use std::fs::File; | |
2809 | /// | |
0531ce1d XL |
2810 | /// fn main() -> io::Result<()> { |
2811 | /// let mut file = File::open("foo.txt")?; | |
7cac9316 | 2812 | /// |
0531ce1d XL |
2813 | /// let mut buffer = [0; 5]; |
2814 | /// let mut handle = file.take(5); | |
2815 | /// handle.read(&mut buffer)?; | |
7cac9316 | 2816 | /// |
0531ce1d XL |
2817 | /// let file = handle.get_mut(); |
2818 | /// Ok(()) | |
2819 | /// } | |
7cac9316 | 2820 | /// ``` |
041b39d2 | 2821 | #[stable(feature = "more_io_inner_methods", since = "1.20.0")] |
7cac9316 XL |
2822 | pub fn get_mut(&mut self) -> &mut T { |
2823 | &mut self.inner | |
2824 | } | |
85aaf69f | 2825 | } |
1a4d82fc | 2826 | |
c34b1796 | 2827 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2828 | impl<T: Read> Read for Take<T> { |
2829 | fn read(&mut self, buf: &mut [u8]) -> Result<usize> { | |
c34b1796 AL |
2830 | // Don't call into inner reader at all at EOF because it may still block |
2831 | if self.limit == 0 { | |
2832 | return Ok(0); | |
2833 | } | |
2834 | ||
85aaf69f | 2835 | let max = cmp::min(buf.len() as u64, self.limit) as usize; |
54a0048b | 2836 | let n = self.inner.read(&mut buf[..max])?; |
064997fb | 2837 | assert!(n as u64 <= self.limit, "number of read bytes exceeds limit"); |
85aaf69f SL |
2838 | self.limit -= n as u64; |
2839 | Ok(n) | |
1a4d82fc | 2840 | } |
041b39d2 | 2841 | |
f2b60f7d | 2842 | fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> { |
a2a8927a XL |
2843 | // Don't call into inner reader at all at EOF because it may still block |
2844 | if self.limit == 0 { | |
2845 | return Ok(()); | |
2846 | } | |
2847 | ||
f2b60f7d | 2848 | if self.limit <= buf.capacity() as u64 { |
a2a8927a XL |
2849 | // if we just use an as cast to convert, limit may wrap around on a 32 bit target |
2850 | let limit = cmp::min(self.limit, usize::MAX as u64) as usize; | |
2851 | ||
f2b60f7d | 2852 | let extra_init = cmp::min(limit as usize, buf.init_ref().len()); |
a2a8927a XL |
2853 | |
2854 | // SAFETY: no uninit data is written to ibuf | |
f2b60f7d | 2855 | let ibuf = unsafe { &mut buf.as_mut()[..limit] }; |
a2a8927a | 2856 | |
f2b60f7d | 2857 | let mut sliced_buf: BorrowedBuf<'_> = ibuf.into(); |
a2a8927a XL |
2858 | |
2859 | // SAFETY: extra_init bytes of ibuf are known to be initialized | |
2860 | unsafe { | |
f2b60f7d | 2861 | sliced_buf.set_init(extra_init); |
a2a8927a XL |
2862 | } |
2863 | ||
f2b60f7d FG |
2864 | let mut cursor = sliced_buf.unfilled(); |
2865 | self.inner.read_buf(cursor.reborrow())?; | |
a2a8927a | 2866 | |
f2b60f7d FG |
2867 | let new_init = cursor.init_ref().len(); |
2868 | let filled = sliced_buf.len(); | |
a2a8927a | 2869 | |
f2b60f7d | 2870 | // cursor / sliced_buf / ibuf must drop here |
a2a8927a | 2871 | |
a2a8927a | 2872 | unsafe { |
f2b60f7d FG |
2873 | // SAFETY: filled bytes have been filled and therefore initialized |
2874 | buf.advance(filled); | |
2875 | // SAFETY: new_init bytes of buf's unfilled buffer have been initialized | |
2876 | buf.set_init(new_init); | |
a2a8927a XL |
2877 | } |
2878 | ||
a2a8927a XL |
2879 | self.limit -= filled as u64; |
2880 | } else { | |
f2b60f7d FG |
2881 | let written = buf.written(); |
2882 | self.inner.read_buf(buf.reborrow())?; | |
2883 | self.limit -= (buf.written() - written) as u64; | |
a2a8927a XL |
2884 | } |
2885 | ||
2886 | Ok(()) | |
041b39d2 | 2887 | } |
1a4d82fc JJ |
2888 | } |
2889 | ||
c34b1796 AL |
2890 | #[stable(feature = "rust1", since = "1.0.0")] |
2891 | impl<T: BufRead> BufRead for Take<T> { | |
2892 | fn fill_buf(&mut self) -> Result<&[u8]> { | |
a7813a04 XL |
2893 | // Don't call into inner reader at all at EOF because it may still block |
2894 | if self.limit == 0 { | |
2895 | return Ok(&[]); | |
2896 | } | |
2897 | ||
54a0048b | 2898 | let buf = self.inner.fill_buf()?; |
c34b1796 AL |
2899 | let cap = cmp::min(buf.len() as u64, self.limit) as usize; |
2900 | Ok(&buf[..cap]) | |
2901 | } | |
2902 | ||
2903 | fn consume(&mut self, amt: usize) { | |
2904 | // Don't let callers reset the limit by passing an overlarge value | |
2905 | let amt = cmp::min(amt as u64, self.limit) as usize; | |
2906 | self.limit -= amt as u64; | |
2907 | self.inner.consume(amt); | |
2908 | } | |
2909 | } | |
2910 | ||
136023e0 XL |
2911 | impl<T> SizeHint for Take<T> { |
2912 | #[inline] | |
2913 | fn lower_bound(&self) -> usize { | |
2914 | cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize | |
2915 | } | |
2916 | ||
2917 | #[inline] | |
2918 | fn upper_bound(&self) -> Option<usize> { | |
2919 | match SizeHint::upper_bound(&self.inner) { | |
2920 | Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize), | |
2921 | None => self.limit.try_into().ok(), | |
2922 | } | |
2923 | } | |
2924 | } | |
2925 | ||
c1a9b12d SL |
2926 | /// An iterator over `u8` values of a reader. |
2927 | /// | |
cc61c64b XL |
2928 | /// This struct is generally created by calling [`bytes`] on a reader. |
2929 | /// Please see the documentation of [`bytes`] for more details. | |
1a4d82fc | 2930 | /// |
3dfed10e | 2931 | /// [`bytes`]: Read::bytes |
c34b1796 | 2932 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 2933 | #[derive(Debug)] |
85aaf69f SL |
2934 | pub struct Bytes<R> { |
2935 | inner: R, | |
1a4d82fc JJ |
2936 | } |
2937 | ||
c34b1796 | 2938 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2939 | impl<R: Read> Iterator for Bytes<R> { |
2940 | type Item = Result<u8>; | |
1a4d82fc | 2941 | |
ed00b5ec FG |
2942 | // Not `#[inline]`. This function gets inlined even without it, but having |
2943 | // the inline annotation can result in worse code generation. See #116785. | |
85aaf69f | 2944 | fn next(&mut self) -> Option<Result<u8>> { |
ed00b5ec | 2945 | SpecReadByte::spec_read_byte(&mut self.inner) |
85aaf69f | 2946 | } |
6a06907d | 2947 | |
ed00b5ec | 2948 | #[inline] |
6a06907d XL |
2949 | fn size_hint(&self) -> (usize, Option<usize>) { |
2950 | SizeHint::size_hint(&self.inner) | |
2951 | } | |
2952 | } | |
2953 | ||
ed00b5ec FG |
2954 | /// For the specialization of `Bytes::next`. |
2955 | trait SpecReadByte { | |
2956 | fn spec_read_byte(&mut self) -> Option<Result<u8>>; | |
2957 | } | |
2958 | ||
2959 | impl<R> SpecReadByte for R | |
2960 | where | |
2961 | Self: Read, | |
2962 | { | |
2963 | #[inline] | |
2964 | default fn spec_read_byte(&mut self) -> Option<Result<u8>> { | |
2965 | inlined_slow_read_byte(self) | |
2966 | } | |
2967 | } | |
2968 | ||
2969 | /// Read a single byte in a slow, generic way. This is used by the default | |
2970 | /// `spec_read_byte`. | |
2971 | #[inline] | |
2972 | fn inlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> { | |
2973 | let mut byte = 0; | |
2974 | loop { | |
2975 | return match reader.read(slice::from_mut(&mut byte)) { | |
2976 | Ok(0) => None, | |
2977 | Ok(..) => Some(Ok(byte)), | |
2978 | Err(ref e) if e.is_interrupted() => continue, | |
2979 | Err(e) => Some(Err(e)), | |
2980 | }; | |
2981 | } | |
2982 | } | |
2983 | ||
2984 | // Used by `BufReader::spec_read_byte`, for which the `inline(ever)` is | |
2985 | // important. | |
2986 | #[inline(never)] | |
2987 | fn uninlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> { | |
2988 | inlined_slow_read_byte(reader) | |
2989 | } | |
2990 | ||
6a06907d XL |
2991 | trait SizeHint { |
2992 | fn lower_bound(&self) -> usize; | |
2993 | ||
2994 | fn upper_bound(&self) -> Option<usize>; | |
2995 | ||
2996 | fn size_hint(&self) -> (usize, Option<usize>) { | |
2997 | (self.lower_bound(), self.upper_bound()) | |
2998 | } | |
2999 | } | |
3000 | ||
fe692bf9 | 3001 | impl<T: ?Sized> SizeHint for T { |
136023e0 | 3002 | #[inline] |
6a06907d XL |
3003 | default fn lower_bound(&self) -> usize { |
3004 | 0 | |
3005 | } | |
3006 | ||
136023e0 | 3007 | #[inline] |
6a06907d XL |
3008 | default fn upper_bound(&self) -> Option<usize> { |
3009 | None | |
3010 | } | |
1a4d82fc JJ |
3011 | } |
3012 | ||
136023e0 XL |
3013 | impl<T> SizeHint for &mut T { |
3014 | #[inline] | |
3015 | fn lower_bound(&self) -> usize { | |
3016 | SizeHint::lower_bound(*self) | |
3017 | } | |
3018 | ||
3019 | #[inline] | |
3020 | fn upper_bound(&self) -> Option<usize> { | |
3021 | SizeHint::upper_bound(*self) | |
3022 | } | |
3023 | } | |
3024 | ||
3025 | impl<T> SizeHint for Box<T> { | |
3026 | #[inline] | |
3027 | fn lower_bound(&self) -> usize { | |
3028 | SizeHint::lower_bound(&**self) | |
3029 | } | |
3030 | ||
3031 | #[inline] | |
3032 | fn upper_bound(&self) -> Option<usize> { | |
3033 | SizeHint::upper_bound(&**self) | |
3034 | } | |
3035 | } | |
3036 | ||
3037 | impl SizeHint for &[u8] { | |
3038 | #[inline] | |
3039 | fn lower_bound(&self) -> usize { | |
3040 | self.len() | |
3041 | } | |
3042 | ||
3043 | #[inline] | |
3044 | fn upper_bound(&self) -> Option<usize> { | |
3045 | Some(self.len()) | |
3046 | } | |
3047 | } | |
3048 | ||
85aaf69f SL |
3049 | /// An iterator over the contents of an instance of `BufRead` split on a |
3050 | /// particular byte. | |
3051 | /// | |
e1599b0c XL |
3052 | /// This struct is generally created by calling [`split`] on a `BufRead`. |
3053 | /// Please see the documentation of [`split`] for more details. | |
c1a9b12d | 3054 | /// |
3dfed10e | 3055 | /// [`split`]: BufRead::split |
c34b1796 | 3056 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 3057 | #[derive(Debug)] |
85aaf69f SL |
3058 | pub struct Split<B> { |
3059 | buf: B, | |
3060 | delim: u8, | |
3061 | } | |
1a4d82fc | 3062 | |
c34b1796 | 3063 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
3064 | impl<B: BufRead> Iterator for Split<B> { |
3065 | type Item = Result<Vec<u8>>; | |
1a4d82fc | 3066 | |
85aaf69f SL |
3067 | fn next(&mut self) -> Option<Result<Vec<u8>>> { |
3068 | let mut buf = Vec::new(); | |
3069 | match self.buf.read_until(self.delim, &mut buf) { | |
c34b1796 AL |
3070 | Ok(0) => None, |
3071 | Ok(_n) => { | |
85aaf69f SL |
3072 | if buf[buf.len() - 1] == self.delim { |
3073 | buf.pop(); | |
3074 | } | |
3075 | Some(Ok(buf)) | |
3076 | } | |
60c5eb7d | 3077 | Err(e) => Some(Err(e)), |
1a4d82fc JJ |
3078 | } |
3079 | } | |
85aaf69f SL |
3080 | } |
3081 | ||
c1a9b12d | 3082 | /// An iterator over the lines of an instance of `BufRead`. |
85aaf69f | 3083 | /// |
e1599b0c XL |
3084 | /// This struct is generally created by calling [`lines`] on a `BufRead`. |
3085 | /// Please see the documentation of [`lines`] for more details. | |
c1a9b12d | 3086 | /// |
3dfed10e | 3087 | /// [`lines`]: BufRead::lines |
c34b1796 | 3088 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 3089 | #[derive(Debug)] |
ed00b5ec | 3090 | #[cfg_attr(not(test), rustc_diagnostic_item = "IoLines")] |
85aaf69f SL |
3091 | pub struct Lines<B> { |
3092 | buf: B, | |
3093 | } | |
3094 | ||
c34b1796 | 3095 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
3096 | impl<B: BufRead> Iterator for Lines<B> { |
3097 | type Item = Result<String>; | |
1a4d82fc | 3098 | |
85aaf69f SL |
3099 | fn next(&mut self) -> Option<Result<String>> { |
3100 | let mut buf = String::new(); | |
3101 | match self.buf.read_line(&mut buf) { | |
c34b1796 AL |
3102 | Ok(0) => None, |
3103 | Ok(_n) => { | |
74b04a01 | 3104 | if buf.ends_with('\n') { |
85aaf69f | 3105 | buf.pop(); |
74b04a01 | 3106 | if buf.ends_with('\r') { |
e9174d1e SL |
3107 | buf.pop(); |
3108 | } | |
1a4d82fc | 3109 | } |
85aaf69f | 3110 | Some(Ok(buf)) |
1a4d82fc | 3111 | } |
60c5eb7d | 3112 | Err(e) => Some(Err(e)), |
1a4d82fc JJ |
3113 | } |
3114 | } | |
85aaf69f | 3115 | } |