about summary refs log tree commit diff
path: root/library/std/src/lib.rs
AgeCommit message (Collapse)AuthorLines
2021-06-25Add Integer::{log,log2,log10} variantsYoshua Wuyts-0/+1
2021-06-22Auto merge of #84910 - eopb:stabilize_int_error_matching, r=yaahcbors-1/+0
stabilize `int_error_matching` closes #22639 > It has been over half a year since https://github.com/rust-lang/rust/pull/77640#pullrequestreview-511263516, and the indexing question is rejected in https://github.com/rust-lang/rust/pull/79728#pullrequestreview-633030341, so I guess we can submit another stabilization attempt? 😉 _Originally posted by `@kennytm` in https://github.com/rust-lang/rust/issues/22639#issuecomment-831738266_
2021-06-19Auto merge of #86034 - nagisa:nagisa/rt-soundness, r=m-ou-sebors-4/+5
Change entry point to 🛡️ against 💥 💥-payloads Guard against panic payloads panicking within entrypoints, where it is UB to do so. Note that there are a number of tradeoffs to consider. For instance, I considered guarding against accidental panics inside the `rt::init` and `rt::cleanup` code as well, as it is not all that obvious these may not panic, but doing so would mean that we initialize certain thread-local slots unconditionally, which has its own problems. Fixes #86030 r? `@m-ou-se`
2021-06-19Change entry point to 🛡️ against 💥 💥-payloadsSimonas Kazlauskas-4/+5
Guard against panic payloads panicking within entrypoints, where it is UB to do so. Note that there are a number of implementation approaches to consider. Some simpler, some more complicated. This particular solution is nice in that it also guards against accidental implementation issues in various pieces of runtime code, something we cannot prevent statically right now. Fixes #86030
2021-06-17Rollup merge of #85925 - clarfonthey:lerp, r=m-ou-seMara Bos-0/+1
Linear interpolation #71016 is a previous attempt at implementation that was closed by the author. I decided to reuse the feature request issue (#71015) as a tracking issue. A member of the rust-lang org will have to edit the original post to be formatted correctly as I am not the issue's original author. The common name `lerp` is used because it is the term used by most code in a wide variety of contexts; it also happens to be the recently chosen name of the function that was added to C++20. To ensure symmetry as a method, this breaks the usual ordering of the method from `lerp(a, b, t)` to `t.lerp(a, b)`. This makes the most sense to me personally, and there will definitely be discussion before stabilisation anyway. Implementing lerp "correctly" is very dififcult even though it's a very common building-block used in all sorts of applications. A good prior reading is [this proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0811r2.html#linear-interpolation) for the C++20 lerp which talks about the various guarantees, which I've simplified down to: 1. Exactness: `(0.0).lerp(start, end) == start` and `(1.0).lerp(start, end) == end` 2. Consistency: `anything.lerp(x, x) == x` 3. Monotonicity: once you go up don't go down Fun story: the version provided in that proposal, from what I understand, isn't actually monotonic. I messed around with a *lot* of different lerp implementations because I kind of got a bit obsessed and I ultimately landed on one that uses the fused `mul_add` instruction. Floating-point lerp lore is hard to come by, so, just trust me when I say that this ticks all the boxes. I'm only 90% certain that it's monotonic, but I'm sure that people who care deeply about this will be there to discuss before stabilisation. The main reason for using `mul_add` is that, in general, it ticks more boxes with fewer branches to be "correct." Although it will be slower on architectures without the fused `mul_add`, that's becoming more and more rare and I have a feeling that most people who will find themselves needing `lerp` will also have an efficient `mul_add` instruction available.
2021-06-15Rollup merge of #86294 - m-ou-se:edition-prelude-modules, r=joshtriplettYuki Okushi-1/+0
Stabilize {std, core}::prelude::rust_*. This stabilizes the `{core, std}::prelude::{rust_2015, rust_2018, rust_2021}` modules. The usage of these modules as the prelude in those editions was already stabilized. This just stabilizes the modules themselves, making it possible for a user to explicitly refer to them. Tracking issue: https://github.com/rust-lang/rust/issues/85684 FCP on the RFC that included this finished here: https://github.com/rust-lang/rfcs/pull/3114#issuecomment-840577395
2021-06-15Rollup merge of #82179 - mbartlett21:patch-5, r=joshtriplettYuki Okushi-0/+1
Add functions `Duration::try_from_secs_{f32, f64}` These functions allow constructing a Duration from a floating point value that could be out of range without panicking. Tracking issue: #83400
2021-06-14Stabilize {std, core}::prelude::rust_*.Mara Bos-1/+0
2021-06-14Add functions `Duration::try_from_secs_{f32, f64}`mbartlett21-0/+1
This also adds the error type used, `FromSecsError` and its `impl`s.
2021-06-14stabilize `int_error_matching`Ethan Brierley-1/+0
2021-06-14Stabilize `maybe_uninit_ref`Yuki Okushi-1/+0
2021-06-06A few lerp testsltdk-0/+1
2021-06-04rustdoc: link to stable/beta docs consistently in documentationJoshua Nelson-1/+0
## User-facing changes - Intra-doc links to primitives that currently go to rust-lang.org/nightly/std/primitive.x.html will start going to channel that rustdoc was built with. Nightly will continue going to /nightly; Beta will link to /beta; stable compilers will link to /1.52.1 (or whatever version they were built as). - Cross-crate links from std to core currently go to /nightly unconditionally. They will start going to /1.52.0 on stable channels (but remain the same on nightly channels). - Intra-crate links from std to std (or core to core) currently go to the same URL they are hosted at; they will continue to do so. Notably, this is different from everything else because it can preserve the distinction between /stable and /1.52.0 by using relative links. Note that "links" includes both intra-doc links and rustdoc's own automatically generated hyperlinks. ## Implementation changes - Update the testsuite to allow linking to /beta and /1.52.1 in docs - Use an html_root_url for the standard library that's dependent on the channel This avoids linking to nightly docs on stable. - Update rustdoc to use channel-dependent links for primitives from an unknown crate - Set DOC_RUST_LANG_ORG_CHANNEL from bootstrap to ensure it's in sync - Include doc.rust-lang.org in the channel
2021-05-24remove cfg(bootstrap)Pietro Albini-3/+1
2021-05-20Rollup merge of #85275 - CDirkx:memchr, r=m-ou-seGuillaume Gomez-1/+0
Move `std::memchr` to `sys_common` `std::memchr` is a thin abstraction over the different `memchr` implementations in `sys`, along with documentation and tests. The module is only used internally by `std`, nothing is exported externally. Code like this is exactly what the `sys_common` module is for, so this PR moves it there.
2021-05-18Stabilize extended_key_value_attributesJoshua Nelson-1/+1
# Stabilization report ## Summary This stabilizes using macro expansion in key-value attributes, like so: ```rust #[doc = include_str!("my_doc.md")] struct S; #[path = concat!(env!("OUT_DIR"), "/generated.rs")] mod m; ``` See the changes to the reference for details on what macros are allowed; see Petrochenkov's excellent blog post [on internals](https://internals.rust-lang.org/t/macro-expansion-points-in-attributes/11455) for alternatives that were considered and rejected ("why accept no more and no less?") This has been available on nightly since 1.50 with no major issues. ## Notes ### Accepted syntax The parser accepts arbitrary Rust expressions in this position, but any expression other than a macro invocation will ultimately lead to an error because it is not expected by the built-in expression forms (e.g., `#[doc]`). Note that decorators and the like may be able to observe other expression forms. ### Expansion ordering Expansion of macro expressions in "inert" attributes occurs after decorators have executed, analogously to macro expressions appearing in the function body or other parts of decorator input. There is currently no way for decorators to accept macros in key-value position if macro expansion must be performed before the decorator executes (if the macro can simply be copied into the output for later expansion, that can work). ## Test cases - https://github.com/rust-lang/rust/blob/master/src/test/ui/attributes/key-value-expansion-on-mac.rs - https://github.com/rust-lang/rust/blob/master/src/test/rustdoc/external-doc.rs The feature has also been dogfooded extensively in the compiler and standard library: - https://github.com/rust-lang/rust/pull/83329 - https://github.com/rust-lang/rust/pull/83230 - https://github.com/rust-lang/rust/pull/82641 - https://github.com/rust-lang/rust/pull/80534 ## Implementation history - Initial proposal: https://github.com/rust-lang/rust/issues/55414#issuecomment-554005412 - Experiment to see how much code it would break: https://github.com/rust-lang/rust/pull/67121 - Preliminary work to restrict expansion that would conflict with this feature: https://github.com/rust-lang/rust/pull/77271 - Initial implementation: https://github.com/rust-lang/rust/pull/78837 - Fix for an ICE: https://github.com/rust-lang/rust/pull/80563 ## Unresolved Questions ~~https://github.com/rust-lang/rust/pull/83366#issuecomment-805180738 listed some concerns, but they have been resolved as of this final report.~~ ## Additional Information There are two workarounds that have a similar effect for `#[doc]` attributes on nightly. One is to emulate this behavior by using a limited version of this feature that was stabilized for historical reasons: ```rust macro_rules! forward_inner_docs { ($e:expr => $i:item) => { #[doc = $e] $i }; } forward_inner_docs!(include_str!("lib.rs") => struct S {}); ``` This also works for other attributes (like `#[path = concat!(...)]`). The other is to use `doc(include)`: ```rust #![feature(external_doc)] #[doc(include = "lib.rs")] struct S {} ``` The first works, but is non-trivial for people to discover, and difficult to read and maintain. The second is a strange special-case for a particular use of the macro. This generalizes it to work for any use case, not just including files. I plan to remove `doc(include)` when this is stabilized. The `forward_inner_docs` workaround will still compile without warnings, but I expect it to be used less once it's no longer necessary.
2021-05-14Move `std::memchr` to `sys_common`Christiaan Dirkx-1/+0
2021-05-09remove const_fn feature gateRalf Jung-1/+0
2021-04-25move core::hint::black_box under its own feature gateRalf Jung-0/+1
2021-04-18Auto merge of #84207 - SimonSapin:deprecate-core-raw, r=dtolnaybors-0/+1
Deprecate the core::raw / std::raw module It only contains the `TraitObject` struct which exposes components of wide pointer. Pointer metadata APIs are designed to replace this: https://github.com/rust-lang/rust/issues/81513
2021-04-16std: Add a variant of thread locals with const initAlex Crichton-1/+4
This commit adds a variant of the `thread_local!` macro as a new `thread_local_const_init!` macro which requires that the initialization expression is constant (e.g. could be stuck into a `const` if so desired). This form of thread local allows for a more efficient implementation of `LocalKey::with` both if the value has a destructor and if it doesn't. If the value doesn't have a destructor then `with` should desugar to exactly as-if you use `#[thread_local]` given sufficient inlining. The purpose of this new form of thread locals is to precisely be equivalent to `#[thread_local]` on platforms where possible for values which fit the bill (those without destructors). This should help close the gap in performance between `thread_local!`, which is safe, relative to `#[thread_local]`, which is not easy to use in a portable fashion.
2021-04-14Requires deprecated *and* deprecated_in_future, depending on what stage is ↵David Tolnay-1/+1
building
2021-04-14s/deprecated_in_future/deprecated/David Tolnay-1/+1
2021-04-15Deprecate the core::raw / std::raw moduleSimon Sapin-0/+1
It only contains the `TraitObject` struct which exposes components of wide pointer. Pointer metadata APIs are designed to replace this: https://github.com/rust-lang/rust/issues/81513
2021-04-13Rollup merge of #84084 - m-ou-se:stabilize-zero, r=scottmcmDylan DPC-1/+0
Stabilize duration_zero. FCP here: https://github.com/rust-lang/rust/issues/73544#issuecomment-817201305
2021-04-12Auto merge of #83776 - jyn514:update-stdarch-docs, r=Amanieubors-14/+8
Update stdarch submodule (to before it switched to const generics) https://github.com/rust-lang/rust/pull/83278#issuecomment-812389823: This unblocks #82539. Major changes: - More AVX-512 intrinsics. - More ARM & AArch64 NEON intrinsics. - Updated unstable WASM intrinsics to latest draft standards. - std_detect is now a separate crate instead of a submodule of std. I double-checked and the first use of const generics looks like https://github.com/rust-lang/stdarch/commit/8d5017861ed594a2baf169e632379862d516e013, which isn't included in this PR. r? `@Amanieu`
2021-04-12Stabilize duration_zero.Mara Bos-1/+0
2021-04-12Update stdarch submodule (to before it switched to const generics)Joshua Nelson-14/+8
This also includes a cherry-pick of https://github.com/rust-lang/stdarch/commit/ec1461905b421cf0c56adeebb49bbf55bb33fd17 and https://github.com/rust-lang/stdarch/pull/1108 to fix a build failure. It also adds a re-export of various macros to the crate root of libstd - previously they would show up automatically because std_detect was defined in the same crate.
2021-04-11Remove FixedSizeArrayTomasz Miąsko-1/+0
2021-04-05Auto merge of #83864 - Dylan-DPC:rollup-78an86n, r=Dylan-DPCbors-1/+0
Rollup of 7 pull requests Successful merges: - #80525 (wasm64 support) - #83019 (core: disable `ptr::swap_nonoverlapping_one`'s block optimization on SPIR-V.) - #83717 (rustdoc: Separate filter-empty-string out into its own function) - #83807 (Tests: Remove redundant `ignore-tidy-linelength` annotations) - #83815 (ptr::addr_of documentation improvements) - #83820 (Remove attribute `#[link_args]`) - #83841 (Allow clobbering unsupported registers in asm!) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2021-04-05Rollup merge of #83820 - petrochenkov:nolinkargs, r=nagisaDylan DPC-1/+0
Remove attribute `#[link_args]` Closes https://github.com/rust-lang/rust/issues/29596 The attribute could always be replaced with `-C link-arg`, but cargo didn't provide a reasonable way to pass such flags to rustc. Now cargo supports `cargo:rustc-link-arg*` directives in build scripts (https://doc.rust-lang.org/cargo/reference/unstable.html#extra-link-arg), so this attribute can be removed.
2021-04-04Bump cfgsMark Rousskov-2/+1
2021-04-03Remove attribute `#[link_args]`Vadim Petrochenkov-1/+0
2021-04-04Rollup merge of #82487 - CDirkx:const-socketaddr, r=m-ou-seYuki Okushi-0/+1
Constify methods of `std::net::SocketAddr`, `SocketAddrV4` and `SocketAddrV6` The following methods are made unstable const under the `const_socketaddr` feature (https://github.com/rust-lang/rust/issues/82485): ```rust // std::net impl SocketAddr { pub const fn ip(&self) -> IpAddr; pub const fn port(&self) -> u16; pub const fn is_ipv4(&self) -> bool; pub const fn is_ipv6(&self) -> bool; } impl SocketAddrV4 { pub const fn ip(&self) -> IpAddr; pub const fn port(&self) -> u16; } impl SocketAddrV6 { pub const fn ip(&self) -> IpAddr; pub const fn port(&self) -> u16; pub const fn flowinfo(&self) -> u32; pub const fn scope_id(&self) -> u32; } ``` Note: `SocketAddrV4::ip` and `SocketAddrV6::ip` use pointer casting and depend on the unstable feature `const_raw_ptr_deref`
2021-04-02Auto merge of #80965 - camelid:rename-doc-spotlight, r=jyn514bors-1/+2
Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]` Fixes #80936. "spotlight" is not a very specific or self-explaining name. Additionally, the dialog that it triggers is called "Notable traits". So, "notable trait" is a better name. * Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]` * Rename `#![feature(doc_spotlight)]` to `#![feature(doc_notable_trait)]` * Update documentation * Improve documentation r? `@Manishearth`
2021-03-26Use iter::zip in library/Josh Stone-0/+1
2021-03-19core/std/alloc: stabilize or_patternsmark-1/+1
2021-03-15Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]`Camelid-1/+2
"spotlight" is not a very specific or self-explaining name. Additionally, the dialog that it triggers is called "Notable traits". So, "notable trait" is a better name. * Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]` * Rename `#![feature(doc_spotlight)]` to `#![feature(doc_notable_trait)]` * Update documentation * Improve documentation
2021-03-10Rollup merge of #82217 - m-ou-se:edition-prelude, r=nikomatsakisDylan DPC-0/+1
Edition-specific preludes This changes `{std,core}::prelude` to export edition-specific preludes under `rust_2015`, `rust_2018` and `rust_2021`. (As suggested in https://github.com/rust-lang/rust/issues/51418#issuecomment-395630382.) For now they all just re-export `v1::*`, but this allows us to add things to the 2021edition prelude soon. This also changes the compiler to make the automatically injected prelude import dependent on the selected edition. cc `@rust-lang/libs` `@djc`
2021-03-10Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, ↵Yuki Okushi-1/+1
r=nikomatsakis Stabilize `unsafe_op_in_unsafe_fn` lint This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896. Tracking issue: #71668 r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung``` # Stabilization report This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`. ## Summary Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside. The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block. For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level. For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md) ### Example ```rust // An `unsafe fn` for demonstration purposes. // Calling this is an unsafe operation. unsafe fn unsf() {} // #[allow(unsafe_op_in_unsafe_fn)] by default, // the behavior of `unsafe fn` is unchanged unsafe fn allowed() { // Here, no `unsafe` block is needed to // perform unsafe operations... unsf(); // ...and any `unsafe` block is considered // unused and is warned on by the compiler. unsafe { unsf(); } } #[warn(unsafe_op_in_unsafe_fn)] unsafe fn warned() { // Removing this `unsafe` block will // cause the compiler to emit a warning. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } #[deny(unsafe_op_in_unsafe_fn)] unsafe fn denied() { // Removing this `unsafe` block will // cause a compilation error. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } ```
2021-03-08Rollup merge of #82870 - jfrimmel:improve-docs, r=jyn514Mara Bos-1/+5
Add note about the `#[doc(no-inline)]` usage This is required to correctly build the documentation (including all submodules, that are only available in certain targets). See the linked issue and #82861 for reference.
2021-03-07Add note about the `#[doc(no-inline)]` usageJulian Frimmel-1/+5
This is required to correctly build the documentation (including all submodules, that are only available in certain targets).
2021-03-06Implement built-in attribute macro `#[cfg_eval]`Vadim Petrochenkov-0/+1
2021-03-05Rollup merge of #82770 - m-ou-se:assert-match, r=joshtriplettMara-2/+3
Add assert_matches macro. This adds `assert_matches!(expression, pattern)`. Unlike the other asserts, this one ~~consumes the expression~~ may consume the expression, to be able to match the pattern. (It could add a `&` implicitly, but that's noticable in the pattern, and will make a consuming guard impossible.) See https://github.com/rust-lang/rust/issues/62633#issuecomment-790737853 This re-uses the same `left: .. right: ..` output as the `assert_eq` and `assert_ne` macros, but with the pattern as the right part: assert_eq: ``` assertion failed: `(left == right)` left: `Some("asdf")`, right: `None` ``` assert_matches: ``` assertion failed: `(left matches right)` left: `Ok("asdf")`, right: `Err(_)` ``` cc ```@cuviper```
2021-03-05Rollup merge of #82764 - m-ou-se:map-try-insert, r=AmanieuMara-0/+1
Add {BTreeMap,HashMap}::try_insert `{BTreeMap,HashMap}::insert(key, new_val)` returns `Some(old_val)` if the key was already in the map. It's often useful to assert no duplicate values are inserted. We experimented with `map.insert(key, val).unwrap_none()` (https://github.com/rust-lang/rust/issues/62633), but decided that that's not the kind of method we'd like to have on `Option`s. `insert` always succeeds because it replaces the old value if it exists. One could argue that `insert()` is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened. This PR adds a `try_insert` method that instead returns a `Result::Err` when the key already exists. This error contains both the `OccupiedEntry` and the value that was supposed to be inserted. This means that unwrapping that result gives more context: ```rust map.insert(10, "world").unwrap_none(); // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29 ``` ```rust map.try_insert(10, "world").unwrap(); // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33 ``` It also allows handling the failure in any other way, as you have full access to the `OccupiedEntry` and the value. `try_insert` returns a reference to the value in case of success, making it an alternative to `.entry(key).or_insert(value)`. r? ```@Amanieu``` Fixes https://github.com/rust-lang/rfcs/issues/3092
2021-03-04Add debug_assert_matches macro.Mara Bos-2/+2
2021-03-04Add assert_matches!(expr, pat).Mara Bos-2/+3
2021-03-04Implement Error for OccupiedError.Mara Bos-0/+1
2021-03-03Avoid unnecessary Vec construction in BufReaderCaleb Sander-0/+1
2021-03-02Rollup merge of #80189 - jyn514:convert-primitives, r=poliorceticsYuki Okushi-6/+6
Convert primitives in the standard library to intra-doc links Blocked on https://github.com/rust-lang/rust/pull/80181. I forgot that this needs to wait for the beta bump so the standard library can be documented with `doc --stage 0`. Notably I didn't convert `core::slice` because it's like 50 links and I got scared :fearful: