mirror of
https://github.com/allankoechke/rust.git
synced 2026-12-02 17:44:28 +00:00
Windows: cache the stdio write mode for the duration of a lock session On Windows, every write to stdout/stderr calls `GetStdHandle` and `GetConsoleMode` (and `GetConsoleOutputCP` for consoles) to decide how to write. For bulk writes through a locked handle that is most of the work; rust-lang/rust#154071 measured 14% of CPU time in `is_console` alone. This caches the handle and the console verdict in the sys-level `Stdout`/`Stderr` and re-queries when a new lock session begins, as [suggested in the issue](https://github.com/rust-lang/rust/issues/154071#issuecomment-4092410339). Holding a `StdoutLock` pins the stream; unlocked writes acquire the lock per call, so they re-query per write exactly as before, and `SetStdHandle` calls made between lock sessions keep working (the rust-lang/rust#40490 behavior is preserved). Numbers from the issue's workload shape (16 KiB chunks to `NUL`, 4 GiB total, Windows 11): | mode | before | after | |---|---|---| | `stdout().lock()` | 0.478 s (8,561 MiB/s) | 0.120 s (34,350 MiB/s) | | unlocked | 0.467 s | 0.293 s | The unlocked case also improves because one implicit lock session can contain several sys-level writes when `LineWriter` splits a chunk at newlines. The console path cannot run in CI, so it was verified under a pseudoconsole: several writes through one lock session on a CP437 console came through `WriteConsoleW` intact (non-ASCII included), and after `SetConsoleOutputCP` plus a new lock session the refresh picked up the change. The `refresh` hook is a small `#[cfg(windows)]` shim on `StdoutRaw`/`StderrRaw`; happy to change it to a method on every platform's sys type instead if that is preferred. Fixes rust-lang/rust#154071