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