about summary refs log tree commit diff
path: root/library/std/src/io
AgeCommit message (Collapse)AuthorLines
2022-10-24Fix grammar in docs for std::io::ReadJesse Ruderman-2/+2
2022-10-15Auto merge of #98033 - joshtriplett:is-terminal-fd-handle, r=thomccbors-0/+31
Add `IsTerminal` trait to determine if a descriptor or handle is a terminal The UNIX implementation uses `isatty`. The Windows implementation uses the same logic the `atty` crate uses, including the hack needed to detect msys terminals. Implement this trait for `Stdin`/`Stdout`/`Stderr`/`File` on all platforms. On Unix, implement it for `BorrowedFd`/`OwnedFd`. On Windows, implement it for `BorrowedHandle`/`OwnedHandle`. Based on https://github.com/rust-lang/rust/pull/91121 Co-authored-by: Matt Wilkinson <mattwilki17@gmail.com>
2022-10-15Add `IsTerminal` trait to determine if a descriptor or handle is a terminalJosh Triplett-0/+31
The UNIX and WASI implementations use `isatty`. The Windows implementation uses the same logic the `atty` crate uses, including the hack needed to detect msys terminals. Implement this trait for `File` and for `Stdin`/`Stdout`/`Stderr` and their locked counterparts on all platforms. On UNIX and WASI, implement it for `BorrowedFd`/`OwnedFd`. On Windows, implement it for `BorrowedHandle`/`OwnedHandle`. Based on https://github.com/rust-lang/rust/pull/91121 Co-authored-by: Matt Wilkinson <mattwilki17@gmail.com>
2022-10-14Rollup merge of #103067 - Nilstrieb:tidy-likes-the-alphabet, r=jackh726Matthias Krüger-1/+2
More alphabetical sorting Sort and enforce a few more things. The biggest change here is sorting all target features.
2022-10-14Rollup merge of #102781 - StackOverflowExcept1on:master, r=joshtriplettMatthias Krüger-1/+2
Improved documentation for `std::io::Error`
2022-10-14Add some tidy-alphabeticalnils-1/+2
2022-10-14Tweak grammarJosh Triplett-1/+1
2022-10-13fix small word dupe typosRageking8-1/+1
2022-10-12Rollup merge of #102811 - the8472:bufread-memset, r=m-ou-seDylan DPC-3/+6
Use memset to initialize readbuf The write loop was found to be slow in #102727 The proper fix is in #102760 but this might still help debug builds and code running under miri by using the write_bytes intrinsic instead of writing one byte at a time.
2022-10-10Rollup merge of #102794 - dtolnay:termination, r=thomccDylan DPC-6/+23
Make tests capture the error printed by a Result return An error returned by tests previously would get written directly to stderr, instead of to the capture buffer set up by the test harness. This PR makes it write to the capture buffer so that it can be integrated as part of the test output by build tools such as `buck test`, since being able to read the error message returned by a test is pretty critical to debugging why the test failed. <br> **Before:** ```rust // tests/test.rs #[test] fn test() -> Result<(), &'static str> { println!("STDOUT"); eprintln!("STDERR"); Err("RESULT") } ``` ```console $ cargo build --test test $ target/debug/deps/test-???????????????? -Z unstable-options --format=json { "type": "suite", "event": "started", "test_count": 1 } { "type": "test", "event": "started", "name": "test" } Error: "RESULT" { "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\n" } { "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.00040313 } ``` **After:** ```console $ target/debug/deps/test-???????????????? -Z unstable-options --format=json { "type": "suite", "event": "started", "test_count": 1 } { "type": "test", "event": "started", "name": "test" } { "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\nError: \"RESULT\"" } { "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.000261894 } ```
2022-10-08use memset to initialize a readbufThe 8472-3/+6
2022-10-07Make tests capture the error printed by a Result returnDavid Tolnay-6/+23
2022-10-07Improved documentation for `std::io::Error`StackOverflowExcept1on-1/+2
2022-10-06Avoid defensive re-initialization of the BufReader bufferBen Kimock-3/+48
2022-09-26remove cfg(bootstrap)Pietro Albini-1/+0
2022-09-26replace stabilization placeholdersPietro Albini-1/+1
2022-09-07stdio: Document no support for writing to non-blocking stdio/stderrUsama Arif-0/+3
Printing to stdio/stderr that have been opened with non-blocking (O_NONBLOCK in linux) can result in an error, which is not handled by std::io module causing a panic. Signed-off-by: Usama Arif <usama.arif@bytedance.com>
2022-09-05std: fix cleanup for uninitialized stdout (#101375)joboet-8/+17
2022-09-04Auto merge of #100576 - joboet:movable_const_remutex, r=Mark-Simulacrumbors-25/+16
Make `ReentrantMutex` movable and `const` As `MovableMutex` is now `const`, it can be used to simplify the implementation and interface of the internal reentrant mutex type. Consequently, the standard error stream does not need to be wrapped in `OnceLock` and `OnceLock::get_or_init_pin()` can be removed.
2022-09-03std: make `ReentrantMutex` movable and `const`; simplify `Stdout` initializationjoboet-25/+16
2022-09-01Update outdated comment about output capturing in print_to.Mara Bos-4/+4
2022-08-29Rollup merge of #100819 - WaffleLapkin:use_ptr_byte_methods, r=scottmcmDylan DPC-2/+2
Make use of `[wrapping_]byte_{add,sub}` These new methods trivially replace old `.cast().wrapping_offset().cast()` & similar code. Note that [`arith_offset`](https://doc.rust-lang.org/std/intrinsics/fn.arith_offset.html) and `wrapping_offset` are the same thing. r? ``@scottmcm`` _split off from #100746_
2022-08-28Stabilize `std::io::read_to_string`Noah Lev-3/+1
2022-08-28Rollup merge of #100520 - jakubdabek:patch-1, r=thomccMatthias Krüger-1/+6
Add mention of `BufReader` in `Read::bytes` docs There is a general paragraph about `BufRead` in the `Read` trait's docs, however using `bytes` without `BufRead` *always* has a large impact, due to reads of size 1. `@rustbot` label +A-docs
2022-08-28Rollup merge of #100296 - BlackHoleFox:os-error-aliases, r=thomccMatthias Krüger-0/+2
Add standard C error function aliases to last_os_error This aids the discoverability of `io::Error::last_os_error()` by linking to commonly used error number functions from C/C++. I've seen a few people not realize this exists, so hopefully this helps draw attention to the API to encourage using it over integer error codes.
2022-08-28Rollup merge of #97015 - nrc:read-buf-cursor, r=Mark-SimulacrumMatthias Krüger-379/+438
std::io: migrate ReadBuf to BorrowBuf/BorrowCursor This PR replaces `ReadBuf` (used by the `Read::read_buf` family of methods) with `BorrowBuf` and `BorrowCursor`. The general idea is to split `ReadBuf` because its API is large and confusing. `BorrowBuf` represents a borrowed buffer which is mostly read-only and (other than for construction) deals only with filled vs unfilled segments. a `BorrowCursor` is a mostly write-only view of the unfilled part of a `BorrowBuf` which distinguishes between initialized and uninitialized segments. For `Read::read_buf`, the caller would create a `BorrowBuf`, then pass a `BorrowCursor` to `read_buf`. In addition to the major API split, I've made the following smaller changes: * Removed some methods entirely from the API (mostly the functionality can be replicated with two calls rather than a single one) * Unified naming, e.g., by replacing initialized with init and assume_init with set_init * Added an easy way to get the number of bytes written to a cursor (`written` method) As well as simplifying the API (IMO), this approach has the following advantages: * Since we pass the cursor by value, we remove the 'unsoundness footgun' where a malicious `read_buf` could swap out the `ReadBuf`. * Since `read_buf` cannot write into the filled part of the buffer, we prevent the filled part shrinking or changing which could cause underflow for the caller or unexpected behaviour. ## Outline ```rust pub struct BorrowBuf<'a> impl Debug for BorrowBuf<'_> impl<'a> From<&'a mut [u8]> for BorrowBuf<'a> impl<'a> From<&'a mut [MaybeUninit<u8>]> for BorrowBuf<'a> impl<'a> BorrowBuf<'a> { pub fn capacity(&self) -> usize pub fn len(&self) -> usize pub fn init_len(&self) -> usize pub fn filled(&self) -> &[u8] pub fn unfilled<'this>(&'this mut self) -> BorrowCursor<'this, 'a> pub fn clear(&mut self) -> &mut Self pub unsafe fn set_init(&mut self, n: usize) -> &mut Self } pub struct BorrowCursor<'buf, 'data> impl<'buf, 'data> BorrowCursor<'buf, 'data> { pub fn clone<'this>(&'this mut self) -> BorrowCursor<'this, 'data> pub fn capacity(&self) -> usize pub fn written(&self) -> usize pub fn init_ref(&self) -> &[u8] pub fn init_mut(&mut self) -> &mut [u8] pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] pub unsafe fn advance(&mut self, n: usize) -> &mut Self pub fn ensure_init(&mut self) -> &mut Self pub unsafe fn set_init(&mut self, n: usize) -> &mut Self pub fn append(&mut self, buf: &[u8]) } ``` ## TODO * ~~Migrate non-unix libs and tests~~ * ~~Naming~~ * ~~`BorrowBuf` or `BorrowedBuf` or `SliceBuf`? (We might want an owned equivalent for the async IO traits)~~ * ~~Should we rename the `readbuf` module? We might keep the name indicate it includes both the buf and cursor variations and someday the owned version too. Or we could change it. It is not publicly exposed, so it is not that important~~. * ~~`read_buf` method: we read into the cursor now, so the `_buf` suffix is a bit weird.~~ * ~~Documentation~~ * Tests are incomplete (I adjusted existing tests, but did not add new ones). cc https://github.com/rust-lang/rust/issues/78485, https://github.com/rust-lang/rust/issues/94741 supersedes: https://github.com/rust-lang/rust/pull/95770, https://github.com/rust-lang/rust/pull/93359 fixes #93305
2022-08-23Make use of `[wrapping_]byte_{add,sub}`Maybe Waffle-2/+2
...replacing `.cast().wrapping_offset().cast()` & similar code.
2022-08-22Move error trait into coreJane Losare-Lusby-0/+9
2022-08-18make many std tests work in MiriRalf Jung-1/+2
2022-08-18Address reviewer commentsNick Cameron-45/+64
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-08-14Add mention of `BufReader` in `Read::bytes` docsJakub Dąbek-1/+6
2022-08-08Add standard C error function aliasesBlackHoleFox-0/+2
Aids the discoverability of `io::Error::last_os_error()` by linking to commonly used error number functions from C/C++.
2022-08-05non-linux platformsNick Cameron-108/+177
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-08-04Add some docs for BorrowBufNick Cameron-24/+60
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-08-04std::io: migrate ReadBuf to BorrowBuf/BorrowCursorNick Cameron-376/+311
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-07-27Auto merge of #98748 - saethlin:optimize-bufreader, r=Mark-Simulacrumbors-53/+134
Remove some redundant checks from BufReader The implementation of BufReader contains a lot of redundant checks. While any one of these checks is not particularly expensive to execute, especially when taken together they dramatically inhibit LLVM's ability to make subsequent optimizations by confusing data flow increasing the code size of anything that uses BufReader. In particular, these changes have a ~2x increase on the benchmark that this adds a `black_box` to. I'm adding that `black_box` here just in case LLVM gets clever enough to remove the reads entirely. Right now it can't, but these optimizations are really setting it up to do so. We get this optimization by factoring all the actual buffer management and bounds-checking logic into a new module inside `bufreader` with a new `Buffer` type. This makes it much easier to ensure that we have correctly encapsulated the management of the region of the buffer that we have read bytes into, and it lets us provide a new faster way to do small reads. `Buffer::consume_with` lets a caller do a read from the buffer with a single bounds check, instead of the double-check that's required to use `buffer` + `consume`. Unfortunately I'm not aware of a lot of open-source usage of `BufReader` in perf-critical environments. Some time ago I tweaked this code because I saw `BufReader` in a profile at work, and I contributed some benchmarks to the `bincode` crate which exercise `BufReader::buffer`. These changes appear to help those benchmarks at little, but all these sorts of benchmarks are kind of fragile so I'm wary of quoting anything specific.
2022-07-26Add Buffer::consume_with to enable direct buffer access with one checkBen Kimock-3/+18
2022-07-26Rollup merge of #99716 - sourcelliu:iomut, r=Mark-SimulacrumMatthias Krüger-4/+4
remove useless mut from examples remove useless mut from examples
2022-07-25Rollup merge of #95040 - frank-king:fix/94981, r=Mark-SimulacrumYuki Okushi-0/+20
protect `std::io::Take::limit` from overflow in `read` Resolves #94981
2022-07-25remove useless mut from examplessourcelliu-4/+4
2022-07-24Rename and document the new BufReader internalsBen Kimock-29/+33
2022-07-24Allow Buffer methods to inlineBen Kimock-0/+9
2022-07-24Remove some redundant checks from BufReaderBen Kimock-53/+106
The implementation of BufReader contains a lot of redundant checks. While any one of these checks is not particularly expensive to execute, especially when taken together they dramatically inhibit LLVM's ability to make subsequent optimizations.
2022-07-23Remove `mut`Phosra-1/+1
2022-07-16Rollup merge of #98387 - NobodyXu:feature/std_io_Error_try_downgrade_inner, ↵Yuki Okushi-1/+127
r=yaahc Add new unstable API `downcast` to `std::io::Error` https://github.com/rust-lang/libs-team/issues/57 Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-07-15Apply suggestions from code reviewJane Losare-Lusby-1/+1
2022-07-15Improve example of `downcast`Jiahao XU-3/+4
Co-authored-by: Jane Losare-Lusby <jlusby42@gmail.com>
2022-07-14Rename `std::io::Error::try_downcast_inner` to `downcast`Jiahao XU-11/+11
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-28Auto merge of #98324 - conradludgate:write-vectored-vec, r=Mark-Simulacrumbors-25/+149
attempt to optimise vectored write benchmarked: old: ``` test io::cursor::tests::bench_write_vec ... bench: 68 ns/iter (+/- 2) test io::cursor::tests::bench_write_vec_vectored ... bench: 913 ns/iter (+/- 31) ``` new: ``` test io::cursor::tests::bench_write_vec ... bench: 64 ns/iter (+/- 0) test io::cursor::tests::bench_write_vec_vectored ... bench: 747 ns/iter (+/- 27) ``` More unsafe than I wanted (and less gains) in the end, but it still does the job
2022-06-26attempt to optimise vectored writeConrad Ludgate-25/+149