about summary refs log tree commit diff
path: root/library/std/src
AgeCommit message (Collapse)AuthorLines
2022-05-28Stabilize `toowned_clone_into`Yuki Okushi-1/+0
2022-05-27Call the OS function to set the main thread's name on program initWesley Wiser-1/+15
Normally, `Thread::spawn` takes care of setting the thread's name, if one was provided, but since the main thread wasn't created by calling `Thread::spawn`, we need to call that function in `std::rt::init`. This is mainly useful for system tools like debuggers and profilers which might show the thread name to a user. Prior to these changes, gdb and WinDbg would show all thread names except the main thread's name to a user. I've validated that this patch resolves the issue for both debuggers.
2022-05-27Finish bumping stage0Mark Rousskov-4/+0
It looks like the last time had left some remaining cfg's -- which made me think that the stage0 bump was actually successful. This brings us to a released 1.62 beta though.
2022-05-27docs: Don't imply that OsStr on Unix is always UTF-8Xiretza-1/+1
The methods in `OsStrExt` consume and return `&[u8]` and don't perform any UTF-8 checks.
2022-05-26Rollup merge of #96033 - yaahc:expect-elaboration, r=scottmcmMatthias Krüger-1/+137
Add section on common message styles for Result::expect Based on a question from https://github.com/rust-lang/project-error-handling/issues/50#issuecomment-1092339937 ~~One thing I haven't decided on yet, should I duplicate this section on `Option::expect`, link to this section, or move it somewhere else and link to that location from both docs?~~: I ended up moving the section to `std::error` and referencing it from both `Result::expect` and `Option::expect`'s docs. I think this section, when combined with the similar update I made on [`std::panic!`](https://doc.rust-lang.org/nightly/std/macro.panic.html#when-to-use-panic-vs-result) implies that we should possibly more aggressively encourage and support the "expect as precondition" style described in this section. The consensus among the libs team seems to be that panic should be used for bugs, not expected potential failure modes. The "expect as error message" style seems to align better with the panic for unrecoverable errors style where they're seen as normal errors where the only difference is a desire to kill the current execution unit (aka erlang style error handling). I'm wondering if we should be providing a panic hook similar to `human-panic` or more strongly recommending the "expect as precondition" style of expect message.
2022-05-26Auto merge of #96742 - m-ou-se:bsd-no-ancillary, r=joshtriplettbors-173/+33
Disable unix::net::ancillary on BSD. See https://github.com/rust-lang/rust/issues/76915#issuecomment-1118954474
2022-05-25Disable unix::net::ancillary on BSD.Mara Bos-173/+33
2022-05-25fix linksJane Lusby-11/+13
2022-05-24add aliases for current_dirjulio-0/+3
2022-05-24explained unwrap vs expectJane Losare-Lusby-12/+15
2022-05-25Rollup merge of #97364 - notriddle:continue-keyword, r=JohnTitorYuki Okushi-6/+6
Fix weird indentation in continue_keyword docs This format was causing every line in the code examples to have a space at the start.
2022-05-24Fix weird indentation in continue_keyword docsMichael Howell-6/+6
This format was causing every line in the code examples to have a space at the start.
2022-05-24Rollup merge of #97321 - RalfJung:int-to-fnptr, r=Dylan-DPCDylan DPC-0/+26
explain how to turn integers into fn ptrs (with an intermediate raw ptr, not a direct transmute) Direct int2ptr transmute, under the semantics I am imagining, will produce a ptr with "invalid" provenance that is invalid to deref or call. We cannot give it the same semantics as int2ptr casts since those do [something complicated](https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html). To my great surprise, that is already what the example in the `transmute` docs does. :) I still added a comment to say that that part is important, and I added a section explicitly talking about this to the `fn()` type docs. With https://github.com/rust-lang/miri/pull/2151, Miri will start complaining about direct int-to-fnptr transmutes (in the sense that it is UB to call the resulting pointer).
2022-05-24Fix stabilization version of `Ipv6Addr::to_ipv4_mapped`Tobias Bucher-1/+1
2022-05-23sync primitive_docsRalf Jung-0/+26
2022-05-23Auto merge of #97315 - Dylan-DPC:rollup-2wee2oz, r=Dylan-DPCbors-0/+13
Rollup of 4 pull requests Successful merges: - #96129 (Document rounding for floating-point primitive operations and string parsing) - #97286 (Add new eslint rule to prevent whitespace before function call paren) - #97292 (Lifetime variance fixes for rustc) - #97309 (Add some regression tests for #90400) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2022-05-23Put a bound on collection misbehaviorChristopher Durham-8/+10
As currently written, when a logic error occurs in a collection's trait parameters, this allows *completely arbitrary* misbehavior, so long as it does not cause undefined behavior in std. However, because the extent of misbehavior is not specified, it is allowed for *any* code in std to start misbehaving in arbitrary ways which are not formally UB; consider the theoretical example of a global which gets set on an observed logic error. Because the misbehavior is only bound by not resulting in UB from safe APIs and the crate-level encapsulation boundary of all of std, this makes writing user unsafe code that utilizes std theoretically impossible, as it now relies on undocumented QOI that unrelated parts of std cannot be caused to misbehave by a misuse of std::collections APIs. In practice, this is a nonconcern, because std has reasonable QOI and an implementation that takes advantage of this freedom is essentially a malicious implementation and only compliant by the most langauage-lawyer reading of the documentation. To close this hole, we just add a small clause to the existing logic error paragraph that ensures that any misbehavior is limited to the collection which observed the logic error, making it more plausible to prove the soundness of user unsafe code. This is not meant to be formal; a formal refinement would likely need to mention that values derived from the collection can also misbehave after a logic error is observed, as well as define what it means to "observe" a logic error in the first place. This fix errs on the side of informality in order to close the hole without complicating a normal reading which can assume a reasonable nonmalicious QOI. See also [discussion on IRLO][1]. [1]: https://internals.rust-lang.org/t/using-std-collections-and-unsafe-anything-can-happen/16640
2022-05-23Rollup merge of #96129 - mattheww:2022-04_float_rounding, r=Dylan-DPCDylan DPC-0/+13
Document rounding for floating-point primitive operations and string parsing The docs for floating point don't have much to say at present about either the precision of their results or rounding behaviour. As I understand it[^1][^2], Rust doesn't support operating with non-default rounding directions, so we need only describe roundTiesToEven. [^1]: https://github.com/rust-lang/rust/issues/41753#issuecomment-299322887 [^2]: https://github.com/llvm/llvm-project/issues/8472#issuecomment-980888781 This PR makes a start by documenting that for primitive operations and `from_str()`.
2022-05-23Auto merge of #92461 - rust-lang:const_tls_local_panic_count, r=Mark-Simulacrumbors-1/+1
Use const initializer for LOCAL_PANIC_COUNT This reduces the size of the __getit function for LOCAL_PANIC_COUNT and should speed up accesses of LOCAL_PANIC_COUNT a bit.
2022-05-23Rollup merge of #97294 - jersou:patch-1, r=Dylan-DPCDylan DPC-2/+2
std::time : fix variable name in the doc
2022-05-23Auto merge of #96455 - dtolnay:writetmp, r=m-ou-sebors-6/+6
Make write/print macros eagerly drop temporaries This PR fixes the 2 regressions in #96434 (`println` and `eprintln`) and changes all the other similar macros (`write`, `writeln`, `print`, `eprint`) to match the old pre-#94868 behavior of `println` and `eprintln`. argument position | before #94868 | after #94868 | after this PR --- |:---:|:---:|:---: `write!($tmp, "…", …)` | :rage: | :rage: | :smiley_cat: `write!(…, "…", $tmp)` | :rage: | :rage: | :smiley_cat: `writeln!($tmp, "…", …)` | :rage: | :rage: | :smiley_cat: `writeln!(…, "…", $tmp)` | :rage: | :rage: | :smiley_cat: `print!("…", $tmp)` | :rage: | :rage: | :smiley_cat: `println!("…", $tmp)` | :smiley_cat: | :rage: | :smiley_cat: `eprint!("…", $tmp)` | :rage: | :rage: | :smiley_cat: `eprintln!("…", $tmp)` | :smiley_cat: | :rage: | :smiley_cat: `panic!("…", $tmp)` | :smiley_cat: | :smiley_cat: | :smiley_cat: Example of code that is affected by this change: ```rust use std::sync::Mutex; fn main() { let mutex = Mutex::new(0); print!("{}", mutex.lock().unwrap()) /* no semicolon */ } ``` You can see several real-world examples like this in the Crater links at the top of #96434. This code failed to compile prior to this PR as follows, but works after this PR. ```console error[E0597]: `mutex` does not live long enough --> src/main.rs:5:18 | 5 | print!("{}", mutex.lock().unwrap()) /* no semicolon */ | ^^^^^^^^^^^^--------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... 6 | } | - | | | `mutex` dropped here while still borrowed | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `MutexGuard` ```
2022-05-23Implement `FusedIterator` for `std::net::[Into]Incoming`Chayim Refael Friedman-0/+7
They never return `None`, so they trivially fulfill the contract.
2022-05-23Auto merge of #96906 - tbu-:pr_stabilize_to_ipv4_mapped, r=dtolnaybors-5/+5
Stabilize `Ipv6Addr::to_ipv4_mapped` CC https://github.com/rust-lang/rust/issues/27709 (tracking issue for the `ip` feature which contains more functions) The function `Ipv6Addr::to_ipv4` is bad because it also returns an IPv4 address for the IPv6 loopback address `::1`. Stabilize `Ipv6Addr::to_ipv4_mapped` so we can recommend that function instead.
2022-05-22Make write/print macros eagerly drop temporariesDavid Tolnay-6/+6
2022-05-23std::time : fix doc variable namejersou-2/+2
2022-05-22small changeProloy Mishra-1/+1
2022-05-22Rollup merge of #97245 - m-ou-se:rwlock-state-typo, r=JohnTitorYuki Okushi-3/+2
Fix typo in futex RwLock::write_contended. I wrote `state` where I should've used `s`. This was spotted by `@Warrenren.` This change removes the unnecessary `s` variable to prevent that mistake. Fortunately, this typo didn't affect the correctness of the lock, as the second half of the condition (!has_writers_waiting) is enough for correctness, which explains why this mistake didn't show up during testing. Fixes https://github.com/rust-lang/rust/issues/97162
2022-05-22Rollup merge of #97144 - samziz:patch-1, r=Dylan-DPCYuki Okushi-4/+4
Fix rusty grammar in `std::error::Reporter` docs ### Commit I initially saw "print's" instead of "prints" at the start of the doc comment for `std::error::Reporter`, while reading the docs for that type. Then I figured 'probably more where that came from', so, as well as correcting the foregoing to "prints", I've patched up these three minor solecisms (well, two [types](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction), three [tokens](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction)): - One use of the indicative which should be subjunctive - indeed the sentence immediately following it, which mirrors its structure, _does_ use the subjunctive ([L871](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L871)). Replaced with the subjunctive. - Two separate clauses joined with commas ([L975](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L975), [L1023](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L1023)). Replaced the first with a semicolon and the second with a period. Admittedly those judgements are pretty much 100% subjective, based on my sense of how the sentences flowed into each other (though ofc the _replacement of the comma itself_ is not subjective or opinion-based). I know this is silly and finicky, but I hope it helps tidy up the docs a bit for future readers! ### PR notes **This is very much non-urgent (and, honestly, non-important).** I just figured it might be a nice quality-of-life improvement and bit of tidying up for the core contributors themselves not to have to do. 🙂 I'm tagging Steve, per the [contributing guidelines](https://rustc-dev-guide.rust-lang.org/contributing.html#r) ("Steve usually reviews documentation changes. So if you were to make a documentation change, add `r? `@steveklabnik`"):` r? `@steveklabnik`
2022-05-21Expand the explanation of OsString capacityJosh Triplett-3/+14
2022-05-21Fix typo in futex RwLock::write_contended.Mara Bos-3/+2
I wrote `state` where I should've used `s`. This removes the unnecessary `s` variable to prevent that mistake. Fortunately, this typo didn't affect the correctness of the lock, as the second half of the condition (!has_writers_waiting) is enough for correctness, which explains why this mistake didn't show up during testing.
2022-05-21Use GRND_INSECURE instead of /dev/urandom when possibleJason A. Donenfeld-0/+15
From reading the source code, it appears like the desired semantic of std::unix::rand is to always provide some bytes and never block. For that reason GRND_NONBLOCK is checked before calling getrandom(0), so that getrandom(0) won't block. If it would block, then the function falls back to using /dev/urandom, which for the time being doesn't block. There are some drawbacks to using /dev/urandom, however, and so getrandom(GRND_INSECURE) was created as a replacement for this exact circumstance. getrandom(GRND_INSECURE) is the same as /dev/urandom, except: - It won't leave a warning in dmesg if used at early boot time, which is a common occurance (and the reason why I found this issue); - It won't introduce a tiny delay at early boot on newer kernels when /dev/urandom tries to opportunistically create jitter entropy; - It only requires 1 syscall, rather than 3. Other than that, it returns the same "quality" of randomness as /dev/urandom, and never blocks. It's only available on kernels ≥5.6, so we try to use it, cache the result of that attempt, and fall back to to the previous code if it didn't work.
2022-05-20Add complexity estimation of iterating over HashSet and HashMapAngelicosPhosphoros-0/+50
It is not obvious (at least for me) that complexity of iteration over hash tables depends on capacity and not length. Especially comparing with other containers like Vec or String. I think, this behaviour is worth mentioning. I run benchmark which tests iteration time for maps with length 50 and different capacities and get this results: ``` capacity - time 64 - 203.87 ns 256 - 351.78 ns 1024 - 607.87 ns 4096 - 965.82 ns 16384 - 3.1188 us ``` If you want to dig why it behaves such way, you can look current implementation in [hashbrown code](https://github.com/rust-lang/hashbrown/blob/f3a9f211d06f78c5beb81ac22ea08fdc269e068f/src/raw/mod.rs#L1933). Benchmarks code would be presented in PR related to this commit.
2022-05-20Auto merge of #96422 - tmccombs:mutex-unpoison, r=m-ou-sebors-0/+83
Add functions to un-poison Mutex and RwLock See discussion at https://internals.rust-lang.org/t/unpoisoning-a-mutex/16521/3
2022-05-20Remove references to guards in documentation for clear_poisonThayne McCombs-10/+10
2022-05-19OsString: Consolidate all documentation about capacity in top-level docsJosh Triplett-28/+12
2022-05-19impl Read and Write for VecDeque<u8>Evan Richter-0/+48
* For read and read_buf, only the front slice of a discontiguous VecDeque is copied. The VecDeque is advanced after reading, making any back slice available for reading with a second call to Read::read(_buf). * For write, the VecDeque always appends the entire slice to the end, growing its allocation when necessary.
2022-05-19std: fix deadlock in `Parker`joboet-8/+13
2022-05-19Remove unnecessay .report() on ExitCodebenediktwerner-2/+2
2022-05-19Change clear_poison to take the lock instead of a guardThayne McCombs-8/+18
2022-05-19Auto merge of #97033 - nbdd0121:unwind3, r=Amanieubors-1/+1
Remove libstd's calls to `C-unwind` foreign functions Remove all libstd and its dependencies' usage of `extern "C-unwind"`. This is a prerequiste of a WIP PR which will forbid libraries calling `extern "C-unwind"` functions to be compiled in `-Cpanic=unwind` and linked against `panic_abort` (this restriction is necessary to address soundness bug #96926). Cargo will ensure all crates are compiled with the same `-Cpanic` but the std is only compiled `-Cpanic=unwind` but needs the ability to be linked into `-Cpanic=abort`. Currently there are two places where `C-unwind` is used in libstd: * `__rust_start_panic` is used for interfacing to the panic runtime. This could be `extern "Rust"` * `_{rdl,rg}_oom`: a shim `__rust_alloc_error_handler` will be generated by codegen to call into one of these; they can also be `extern "Rust"` (in fact, the generated shim is used as `extern "Rust"`, so I am not even sure why these are not, probably because they used to `extern "C"` and was changed to `extern "C-unwind"` when we allow alloc error hooks to unwind, but they really should just be using Rust ABI). For dependencies, there is only one `extern "C-unwind"` function call, in `unwind` crate. This can be expressed as a re-export. More dicussions can be seen in the Zulip thread: https://rust-lang.zulipchat.com/#narrow/stream/210922-project-ffi-unwind/topic/soundness.20in.20mixed.20panic.20mode `@rustbot` label: T-libs F-c_unwind
2022-05-19Rollup merge of #97131 - gimbles:patch-2, r=Dylan-DPCYuki Okushi-1/+1
Improve println! documentation
2022-05-19Rollup merge of #97127 - Mark-Simulacrum:revert-96441, r=m-ou-seYuki Okushi-132/+31
Revert "Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se" This reverts commit ddb7fbe8434be481607ae199fe2aee976ee2fc2e. Partially addresses https://github.com/rust-lang/rust/issues/97124, but not marking as fixed as we're still pending on a beta backport (for 1.62, which is happening in https://github.com/rust-lang/rust/pull/97088). r? ``@m-ou-se`` ``@ChrisDenton``
2022-05-18std: Add capacity guarantees notes for OsStringXuanwo-0/+35
Signed-off-by: Xuanwo <github@xuanwo.io>
2022-05-18Fix rusty grammar in `std::error::Reporter` docsSam Robinson-Adams-4/+4
I initially saw "print's" instead of "prints" at the start of the doc comment for `std::error::Reporter`, while reading the docs for that type. Then I figured 'probably more where that came from', so, as well as correcting the foregoing to "prints", I've patched up these three minor solecisms (well, two [types](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction), three [tokens](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction)): - One use of the indicative which should be subjunctive - indeed the sentence immediately following it, which mirrors its structure, _does_ use the subjunctive ([L871](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L871)). Replaced with the subjunctive. - Two separate clauses joined with commas ([L975](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L975), [L1023](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L1023)). Replaced the first with a semicolon and the second with a period. Admittedly those judgements are pretty much 100% subjective, based on my sense of how the sentences flowed into each other (though ofc the _replacement of the comma itself_ is not subjective or opinion-based). I know this is silly and finicky, but I hope it helps tidy up the docs a bit for future readers!
2022-05-18std: use an event flag based thread parker on SOLIDjoboet-6/+214
2022-05-18Rollup merge of #97101 - coolreader18:exitcode-method-issue, r=yaahcDylan DPC-1/+1
Add tracking issue for ExitCode::exit_process r? `@yaahc`
2022-05-18Rollup merge of #96917 - marti4d:master, r=ChrisDentonDylan DPC-4/+74
Make HashMap fall back to RtlGenRandom if BCryptGenRandom fails With PR #84096, Rust `std::collections::hash_map::RandomState` changed from using `RtlGenRandom()` ([msdn](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom)) to `BCryptGenRandom()` ([msdn](https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom)) as its source of secure randomness after much discussion ([here](https://github.com/rust-random/getrandom/issues/65#issuecomment-753634074), among other places). Unfortunately, after that PR landed, Mozilla Firefox started experiencing fairly-rare crashes during startup while attempting to initialize the `env_logger` crate. ([docs for env_logger](https://docs.rs/env_logger/latest/env_logger/)) The root issue is that on some machines, `BCryptGenRandom()` will fail with an `Access is denied. (os error 5)` error message. ([Bugzilla issue 1754490](https://bugzilla.mozilla.org/show_bug.cgi?id=1754490)) (Discussion in issue #94098) Note that this is happening upon startup of Firefox's unsandboxed Main Process, so this behavior is different and separate from previous issues ([like this](https://bugzilla.mozilla.org/show_bug.cgi?id=1746254)) where BCrypt DLLs were blocked by process sandboxing. In the case of sandboxing, we knew we were doing something abnormal and expected that we'd have to resort to abnormal measures to make it work. However, in this case we are in a regular unsandboxed process just trying to initialize `env_logger` and getting a panic. We suspect that this may be caused by a virus scanner or some other security software blocking the loading of the BCrypt DLLs, but we're not completely sure as we haven't been able to replicate locally. It is also possible that Firefox is not the only software affected by this; we just may be one of the pieces of Rust software that has the telemetry and crash reporting necessary to catch it. I have read some of the historical discussion around using `BCryptGenRandom()` in Rust code, and I respect the decision that was made and agree that it was a good course of action, so I'm not trying to open a discussion about a return to `RtlGenRandom()`. Instead, I'd like to suggest that perhaps we use `RtlGenRandom()` as a "fallback RNG" in the case that BCrypt doesn't work. This pull request implements this fallback behavior. I believe this would improve the robustness of this essential data structure within the standard library, and I see only 2 potential drawbacks: 1. Slight added overhead: It should be quite minimal though. The first call to `sys::rand::hashmap_random_keys()` will incur a bit of initialization overhead, and every call after will incur roughly 2 non-atomic global reads and 2 easily predictable branches. Both should be negligible compared to the actual cost of generating secure random numbers 2. `RtlGenRandom()` is deprecated by Microsoft: Technically true, but as mentioned in [this comment on GoLang](https://github.com/golang/go/issues/33542#issuecomment-626124873), this API is ubiquitous in Windows software and actually removing it would break lots of things. Also, Firefox uses it already in [our C++ code](https://searchfox.org/mozilla-central/rev/5f88c1d6977e03e22d3420d0cdf8ad0113c2eb31/mfbt/RandomNum.cpp#25), and [Chromium uses it in their code as well](https://source.chromium.org/chromium/chromium/src/+/main:base/rand_util_win.cc) (which transitively means that Microsoft uses it in their own web browser, Edge). If there did come a time when Microsoft truly removes this API, it should be easy enough for Rust to simply remove the fallback in the code I've added here
2022-05-18Update macros.rsGim-1/+1
2022-05-17Revert "Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se"Mark Rousskov-132/+31
This reverts commit ddb7fbe8434be481607ae199fe2aee976ee2fc2e, reversing changes made to baaa3b682986879c7784b5733ecea942e9ae7de3.
2022-05-16Add tracking issue for ExitCode::exit_processNoa-1/+1