Commit graph

176 commits

Author SHA1 Message Date
Manish Goregaokar
5f331c0585
Rollup merge of #74774 - oliver-giersch:set_data_ptr, r=dtolnay
adds [*mut|*const] ptr::set_ptr_value

I propose the addition of these two functions to `*mut T` and `*const T`, respectively. The motivation for this is primarily byte-wise pointer arithmetic on (potentially) fat pointers, i.e. for types with a `T: ?Sized` bound. A concrete use-case has been discussed in [this](https://internals.rust-lang.org/t/byte-wise-fat-pointer-arithmetic/12739) thread.
TL;DR: Currently, byte-wise pointer arithmetic with potentially fat pointers in not possible in either stable or nightly Rust without making assumptions about the layout of fat pointers, which is currently still an implementation detail and not formally stabilized. This PR adds one function to `*mut T` and `*const T` each, allowing to circumvent this restriction without exposing any internal implementation details.
One possible alternative would be to add specific byte-wise pointer arithmetic functions to the two pointer types in addition to the already existing count-wise functions. However, I feel this fairly niche use case does not warrant adding a whole set of new functions like `add_bytes`, `offset_bytes`, `wrapping_offset_bytes`, etc. (times two, one for each pointer type) to `libcore`.
2020-08-06 23:04:02 -07:00
Amanieu d'Antras
d51b7b229a Update hashbrown to 0.8.1 2020-08-07 07:03:12 +01:00
bors
98922795f6 Auto merge of #75121 - tmiasko:str-slicing, r=Mark-Simulacrum
Avoid `unwrap_or_else` in str indexing

This provides a small reduction of generated LLVM IR, and leads to a
simpler assembly code.

Closes #68874.
2020-08-07 04:51:04 +00:00
Yuki Okushi
26705d5bcb
Rollup merge of #75211 - lzutao:native-endian-notes, r=lcnr
Note about endianness of returned value of {integer}::from_be_bytes and friends

[`u32::from_be`](https://doc.rust-lang.org/nightly/src/core/num/mod.rs.html#2883-2892) documents about endianness of returned value.

I was confused by endianness of `from_be_bytes` in #75086 .
2020-08-07 09:35:26 +09:00
Yuki Okushi
1b61fd3ccf
Rollup merge of #75179 - lzutao:unsed-ipv4-frominner, r=alexcrichton
Remove unused FromInner impl for Ipv4Addr

The removed is a unused unstable implementation.
2020-08-07 09:35:16 +09:00
Yuki Okushi
c9c7048038
Rollup merge of #75175 - lzutao:doctest-ipv4-fromu32, r=cuviper
Make doctests of Ipv4Addr::from(u32) easier to read

There are many zeroes in `0x0d0c0b0au32` which makes it hard to read.
2020-08-07 09:35:14 +09:00
Tim Diekmann
a784729cde Add as_mut_ptr to NonNull<[T]> 2020-08-06 11:45:54 +02:00
Lzu Tao
eff7d568d8 Note about endianness of returned value
in {integer}::from_be_bytes and friends.
2020-08-06 07:33:07 +00:00
Tomasz Miąsko
888bc07c6b Keep stdout open in limit_vector_count test 2020-08-06 00:00:00 +00:00
bors
c15bae53b5 Auto merge of #75086 - lzutao:u32const, r=oli-obk
Use u32::from_ne_bytes to fix a FIXME and add comment about that

`u32::from_ne_bytes` has been const stable since 1.44.
2020-08-06 14:21:48 +00:00
Nazım Can Altınova
62e06a4d09
Make IntoIterator lifetime bounds of &BTreeMap match with &HashMap 2020-08-05 23:32:13 +02:00
Adam Reichold
9073acdc98 Add fallback for cfg(unix) targets that do not define libc::_SC_IOV_MAX. 2020-08-05 17:15:08 +02:00
Adam Reichold
04a0114e7e Rely only on POSIX semantics for I/O vector count
All #[cfg(unix)] platforms follow the POSIX standard and define _SC_IOV_MAX so
that we rely purely on POSIX semantics to determine the limits on I/O vector
count.
2020-08-05 16:57:02 +02:00
Adam Reichold
87edccf0f0 Reduce synchronization overhead of I/O vector count memoization 2020-08-05 16:57:02 +02:00
Adam Reichold
6672f7be03 Memoize the I/O vector count limit
Keep the I/O vector count limit in a `SyncOnceCell` to avoid the overhead of
repeatedly calling `sysconf` as these limits are guaranteed to not change during
the lifetime of a process by POSIX.
2020-08-05 16:57:02 +02:00
Adam Reichold
9468752581 Query maximum vector count on Linux and macOS
Both Linux and MacOS enforce limits on the vector count when performing vectored
I/O via the readv and writev system calls and return EINVAL when these limits
are exceeded. This changes the standard library to handle those limits as short
reads and writes to avoid forcing its users to query these limits using
platform specific mechanisms.
2020-08-05 16:57:02 +02:00
Lzu Tao
d9f260e95e Remove unused FromInner impl for Ipv4Addr 2020-08-05 05:53:07 +00:00
Lzu Tao
725d37cae0 Make doctests of Ipv4Addr::from(u32) easier to read 2020-08-05 05:31:17 +00:00
bors
dab2ae0404 Auto merge of #75037 - richkadel:llvm-coverage-map-gen-5.2, r=wesleywiser
Completes support for coverage in external crates

Follow-up to #74959 :

The prior PR corrected for errors encountered when trying to generate
the coverage map on source code inlined from external crates (including
macros and generics) by avoiding adding external DefIds to the coverage
map.

This made it possible to generate a coverage report including external
crates, but the external crate coverage was incomplete (did not include
coverage for the DefIds that were eliminated.

The root issue was that the coverage map was converting Span locations
to source file and locations, using the SourceMap for the current crate,
and this would not work for spans from external crates (compliled with a
different SourceMap).

The solution was to convert the Spans to filename and location during
MIR generation instead, so precompiled external crates would already
have the correct source code locations embedded in their MIR, when
imported into another crate.

@wesleywiser FYI
r? @tmandry
2020-08-05 05:08:19 +00:00
Lzu Tao
30a1455c8d Use u32::from_ne_bytes to fix a FIXME
Co-authored-by: Weiyi Wang <wwylele@gmail.com>
Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
Co-authored-by: Josh Stone <cuviper@gmail.com>
Co-authored-by: Scott McMurray <scottmcm@users.noreply.github.com>
Co-authored-by: tmiasko <tomasz.miasko@gmail.com>
2020-08-05 02:49:26 +00:00
Alexis Bourget
d243fa109f Fix the documentation for move about Fn traits implementations 2020-08-04 22:49:25 +02:00
Rich Kadel
e0dc8dec27 Completes support for coverage in external crates
The prior PR corrected for errors encountered when trying to generate
the coverage map on source code inlined from external crates (including
macros and generics) by avoiding adding external DefIds to the coverage
map.

This made it possible to generate a coverage report including external
crates, but the external crate coverage was incomplete (did not include
coverage for the DefIds that were eliminated.

The root issue was that the coverage map was converting Span locations
to source file and locations, using the SourceMap for the current crate,
and this would not work for spans from external crates (compliled with a
different SourceMap).

The solution was to convert the Spans to filename and location during
MIR generation instead, so precompiled external crates would already
have the correct source code locations embedded in their MIR, when
imported into another crate.
2020-08-04 11:06:54 -07:00
Tim Diekmann
93d98328d1
Revert missing "memory block" 2020-08-04 19:24:08 +02:00
Tim Diekmann
929e37d4bf Revert renaming of "memory block" 2020-08-04 19:15:48 +02:00
Tim Diekmann
ab9362ad9a Replace Memoryblock with NonNull<[u8]> 2020-08-04 18:03:34 +02:00
Ivan Tham
e1ef3fa686
Consistent variable name alloc for raw_vec 2020-08-04 23:46:14 +08:00
bors
5f6bd6ec0a Auto merge of #74850 - TimDiekmann:remove-in-place-alloc, r=Amanieu
Remove in-place allocation and revert to separate methods for zeroed allocations

closes rust-lang/wg-allocators#58
2020-08-04 11:22:45 +00:00
bors
80f84eb9c6 Auto merge of #75058 - ssomers:btree_cleanup_insert_2, r=Mark-Simulacrum
Clarify reuse of a BTreeMap insert support function and treat split support likewise

r? @Mark-Simulacrum
2020-08-04 03:48:48 +00:00
Yuki Okushi
622759d129
Rollup merge of #75084 - Aaron1011:stabilize/ident-new-raw, r=petrochenkov
Stabilize Ident::new_raw

Tracking issue: #54723

This is a continuation of PR #59002
2020-08-04 09:27:06 +09:00
Yuki Okushi
cc0ac7eece
Rollup merge of #74759 - carbotaniuman:uabs, r=shepmaster
add `unsigned_abs` to signed integers

Mentioned on rust-lang/rfcs#2914

This PR simply adds an `unsigned_abs` to signed integers function which returns the correct absolute value as a unsigned integer.
2020-08-04 09:26:58 +09:00
Tim Diekmann
6395659168
Apply suggestions from code review
Co-authored-by: Amanieu d'Antras <amanieu@gmail.com>
2020-08-04 00:21:05 +02:00
Tomasz Miąsko
427634b503 Avoid unwrap_or_else in str indexing
This provides a small reduction of generated LLVM IR, and leads to a
simpler assembly code.
2020-08-04 00:01:48 +02:00
bors
d8cbd9caca Auto merge of #74526 - erikdesjardins:reftrack, r=Mark-Simulacrum
Add track_caller to RefCell::{borrow, borrow_mut}

So panic messages point at the offending borrow.

Fixes #74472
2020-08-03 21:43:27 +00:00
Aaron Hill
6deda6a6a0
Stabilize Ident::new_raw
Tracking issue: #54723

This is a continuation of PR #59002
2020-08-03 17:23:31 -04:00
bors
829d69b9c6 Auto merge of #74827 - ssomers:btree_cleanup_insert, r=Mark-Simulacrum
Move bulk of BTreeMap::insert method down to new method on handle

Adjust the boundary between the map and node layers for insertion: do more in the node layer, keep root manipulation and pointer dereferencing separate. No change in undefined behaviour or performance.

r? @Mark-Simulacrum
2020-08-03 15:46:02 +00:00
oliver-giersch
6c81556a36
adds [*mut|*const] ptr::set_ptr_value 2020-08-03 04:17:45 -07:00
kennytm
fd7596c9a5
fix broken git commit in stdarch 2020-08-03 15:52:30 +08:00
Tim Diekmann
24ddf76ed7
Merge branch 'master' into remove-in-place-alloc 2020-08-03 02:18:20 +02:00
bors
19ecce332e Auto merge of #74948 - lzutao:stalize-result-as-deref, r=dtolnay
Stabilize `Result::as_deref` and `as_deref_mut`

FCP completed in https://github.com/rust-lang/rust/issues/50264#issuecomment-645681400.

This PR stabilizes two new APIs for `std::result::Result`:
```rust
fn as_deref(&self) -> Result<&T::Target, &E> where T: Deref;
fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> where T: DerefMut;
```

This PR also removes two rarely used unstable APIs from `Result`:
```rust
fn as_deref_err(&self) -> Result<&T, &E::Target> where E: Deref;
fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> where E: DerefMut;
```

Closes #50264
2020-08-02 23:55:12 +00:00
Manish Goregaokar
9471ab068c
Rollup merge of #75059 - shengsheng:typos, r=Dylan-DPC
fix typos

Fix common misspellings with https://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/For_machines
2020-08-02 13:08:47 -07:00
Manish Goregaokar
1b350ecb60
Rollup merge of #75009 - georgio:master, r=kennytm
Document the discrepancy in the mask type for _mm_shuffle_ps

This Pull Request updates the `stdarch` submodule in order to resolve #62490
2020-08-02 13:08:43 -07:00
Stein Somers
532e7f49fc Separate off a leafy insert function instead of lying, and split split similarly 2020-08-02 21:42:17 +02:00
Stein Somers
f5c47fa44d Move bulk of BTreeMap::insert method down to new method on handle 2020-08-02 20:20:42 +02:00
Yuki Okushi
7d18040b0c
Rollup merge of #74974 - RalfJung:miri-tests, r=Mark-Simulacrum
Make tests faster in Miri

Reduce some test iteration counts in Miri.
2020-08-03 01:05:20 +09:00
Yuki Okushi
1033c74665
Rollup merge of #74874 - ssomers:btree_cleanup_8, r=Mark-Simulacrum
BTreeMap: define forget_type only when relevant

Similar to `forget_node_type` for handles.
No effect on generated code, apart maybe from the superfluous calls that might not have been optimized away.

r? @Mark-Simulacrum
2020-08-03 01:05:18 +09:00
Yuki Okushi
814b31eb2e
Rollup merge of #74762 - ssomers:btree_no_root_in_remove_kv_tracking, r=Mark-Simulacrum
BTreeMap::drain_filter should not touch the root during iteration

Although Miri doesn't point it out, I believe there is undefined behaviour using `drain_filter` when draining the 11th-last element from a tree that was larger. When this happens, the last remaining child nodes are merged, the root becomes empty and is popped from the tree. That last step establishes a mutable reference to the node elected root and writes a pointer in `node::Root`, while iteration continues to visit the same node.

This is mostly code from #74437, slightly adapted.
2020-08-03 01:05:13 +09:00
Yuki Okushi
8c331ee470
Rollup merge of #74686 - ssomers:btree_cleanup_3, r=Mark-Simulacrum
BTreeMap: remove into_slices and its unsafe block

A small tweak to make BTreeMap code shorter and less unsafe.

r? @Mark-Simulacrum
2020-08-03 01:05:12 +09:00
Georgio Nicolas
1e2ce28ec0 Document the discrepancy in the mask type for _mm_shuffle_ps 2020-08-02 18:22:26 +03:00
liuzhenyu
3b4151c9f3 fix typos 2020-08-02 23:20:00 +08:00
bors
1e99138078 Auto merge of #74972 - second-state:wasi-right-fix, r=KodrAus
Fix std::fs::File::metadata permission on WASI target

Previously `std::fs::File::metadata` on wasm32-wasi would call `fd_filestat_get`
to get metadata associated with fd, but that fd is opened without
RIGHTS_FD_FILESTAT_GET right, so it will failed on correctly implemented WASI
environment.

This change instead to add the missing rights when opening an fd.
2020-08-02 09:41:17 +00:00
bors
e18b56345f Auto merge of #75033 - Manishearth:rollup-d8afil1, r=Manishearth
Rollup of 5 pull requests

Successful merges:

 - #74602 (Clarify the doc for MaybeUninit::zeroed on incorrect use)
 - #74720 (Clean up E0728 explanation)
 - #74992 (fix rustdoc generic param order)
 - #75015 (Add Vec::spare_capacity_mut)
 - #75022 (Use a slice pattern instead of rchunks_exact(_).next())

Failed merges:

r? @ghost
2020-08-02 01:04:54 +00:00
Manish Goregaokar
d544e21dc3
Rollup merge of #75015 - Amanieu:vec_spare, r=sfackler
Add Vec::spare_capacity_mut

Returns the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.

As suggested by @sfackler in https://github.com/rust-lang/rust/pull/70967#issuecomment-612659006.

r? @sfackler
2020-08-01 17:42:16 -07:00
Manish Goregaokar
39436ebe72
Rollup merge of #74602 - poliorcetics:maybe-uninit-zeroed-doc-clarification, r=jyn514
Clarify the doc for MaybeUninit::zeroed on incorrect use

Fixes #74343.

@rustbot modify labels: C-enhancement, T-doc
2020-08-01 17:42:11 -07:00
bors
5ef872f961 Auto merge of #74605 - rust-lang:vec-leak, r=Amanieu
Stabilize Vec::leak as a method

Closes https://github.com/rust-lang/rust/issues/62195

The signature is changed to a method rather than an associated function:

```diff
-pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
+pub fn leak<'a>(self) -> &'a mut [T]
```

The reason for `Box::leak` not to be a method (`Deref` to an arbitrary `T` which might have its own, different `leak` method) does not apply.
2020-08-01 22:29:30 +00:00
Stein Somers
99398dd2fd BTreeMap::drain_filter no longer touches the root during iteration 2020-08-01 23:35:30 +02:00
Tim Diekmann
db7d07b83b
Remove a trailing whitespace 2020-08-01 21:53:00 +02:00
Tim Diekmann
9cd9286e20
Update doc-comment for grow_zeroed 2020-08-01 21:51:50 +02:00
Stein Somers
602f9aab89 More benchmarks of BTreeMap mutation 2020-08-01 20:23:13 +02:00
Alexis Bourget
54eb3768e0 Reword incorrect use of zeroed() 2020-08-01 19:28:19 +02:00
Amanieu d'Antras
df3a30aee4 Add Vec::spare_capacity_mut 2020-08-01 18:24:35 +01:00
Stein Somers
240ef70c7b Define forget_type only when relevant 2020-08-01 14:09:19 +02:00
bors
b5eae9c44d Auto merge of #74373 - lcnr:array_chunks, r=withoutboats
add `slice::array_chunks` to std

Now that #74113 has landed, these methods are suddenly usable. A rebirth of #72334

Tests are directly copied from `chunks_exact` and some additional tests for type inference.

r? @withoutboats as you are both part of t-libs and working on const generics. closes #60735
2020-08-01 06:54:14 +00:00
Bastian Kauschke
d51b71a35a add tracking issue 2020-08-01 07:49:24 +02:00
Yuki Okushi
ab4570eaf0
Rollup merge of #74644 - crlf0710:drop_old_stuff, r=Amanieu
Remove `linked_list_extras` methods.

Removing these in favor of the `Cursor` API in https://github.com/rust-lang/rust/issues/58533 .
Closes #27794.

r? @Amanieu
2020-08-01 08:02:04 +09:00
Charles Lew
dc21178830 Remove linked_list_extras methods. 2020-08-01 00:54:22 +08:00
Ralf Jung
ff0c3a9209 expand comments 2020-07-31 14:03:42 +02:00
Ralf Jung
7468f632ff also reduce some libcore test iteration counts 2020-07-31 11:56:08 +02:00
Ralf Jung
7e168a696f reduce slice::panic_safe test size further in Miri 2020-07-31 11:56:08 +02:00
Ralf Jung
0a62b7dc92 make some vec_deque tests less exhaustive in Miri 2020-07-31 11:56:08 +02:00
Shen-Ta Hsieh
4c851792ac
Fix std::fs::File::metadata permission on WASI target
Previously `std::fs::File::metadata` on wasm32-wasi would call `fd_filestat_get`
to get metadata associated with fd, but that fd is opened without
RIGHTS_FD_FILESTAT_GET right, so it will failed on correctly implemented WASI
environment.

This change instead to add the missing rights when opening an fd.
2020-07-31 09:01:16 +00:00
bors
3a92b9987a Auto merge of #74956 - ecstatic-morse:const-option-unwrap, r=oli-obk
Make `Option::unwrap` unstably const

This is lumped into the `const_option` feature gate (#67441), which enables a potpourri of `Option` methods.

cc @rust-lang/wg-const-eval

r? @oli-obk
2020-07-31 08:26:33 +00:00
Bastian Kauschke
e75ffb0f1c use Iter<'_, [T; N]> in array_chunks 2020-07-31 08:25:23 +02:00
Bastian Kauschke
a410ebc5ea add note to array_chunks 2020-07-31 08:24:57 +02:00
Lzu Tao
6d293ede9f Update tests 2020-07-31 02:44:29 +00:00
Lzu Tao
c25f25f7f1 Stabilize as_deref and as_deref on Result 2020-07-31 02:42:24 +00:00
Lzu Tao
07575286b8 Remove as_deref_err and as_deref_mut_err from Result 2020-07-31 02:42:24 +00:00
bors
ffa80f01d8 Auto merge of #74926 - Manishearth:rename-lint, r=jyn514
Rename intra_doc_link_resolution_failure

It should be plural to follow the conventions in https://github.com/rust-lang/rfcs/blob/master/text/0344-conventions-galore.md#lints
2020-07-31 02:20:47 +00:00
bors
c058a8b8dc Auto merge of #74682 - alexcrichton:backtrace-gimli-round-2, r=Mark-Simulacrum
std: Switch from libbacktrace to gimli (take 2)

This is the second attempt to land https://github.com/rust-lang/rust/pull/73441 after being reverted in https://github.com/rust-lang/rust/pull/74613. Will be gathering precise perf numbers here in this take.

Closes #71060
2020-07-30 23:22:09 +00:00
Manish Goregaokar
46379687ac
Rollup merge of #74782 - vorner:weak-into-raw-cnt-doc, r=dtolnay
Don't use "weak count" around Weak::from_raw_ptr

As `Rc/Arc::weak_count` returns 0 when having no strong counts, this
could be confusing and it's better to avoid using that completely.

Closes #73840.
2020-07-30 13:04:29 -07:00
Dylan MacKenzie
fc2c1f8ddc Make Option::unwrap unstably const
`Result::unwrap` is not eligible becuase it formats the contents of the
`Err` variant. `unwrap_or`, `unwrap_or_else` and friends are not
eligible because they drop things or invoke closures.
2020-07-30 12:30:58 -07:00
Manish Goregaokar
522ef2e981 Remove deny for intra doc link failures from library code, it's no longer necessary 2020-07-30 08:14:27 -07:00
Manish Goregaokar
7b7b5a7a12 Rename in library 2020-07-30 08:14:27 -07:00
bors
21867225a7 Auto merge of #74930 - ecstatic-morse:const-size-align-of-val, r=oli-obk
Make `mem::size_of_val` and `mem::align_of_val` unstably const

Implements #46571 but does not stabilize it. I wanted this while working on something today.

The only reason not to immediately stabilize are concerns around [custom DSTs](https://github.com/rust-lang/rust/issues/46571#issuecomment-387669352). That proposal has made zero progress in the last two years and const eval is rich enough to support pretty much any user-defined `len` function as long as nightly features are allowed (`raw_ptr_deref`).

Currently, this raises a `const_err` lint when passed an `extern type`.

r? @oli-obk

cc @rust-lang/wg-const-eval
2020-07-30 12:52:41 +00:00
Bastian Kauschke
95fa63e63f liballoc export ArrayChunks 2020-07-30 10:50:35 +02:00
Bastian Kauschke
d27007fd6d add tests for array_chunks 2020-07-30 10:50:34 +02:00
Bastian Kauschke
d405347f09 adds slice::array_chunks 2020-07-30 10:50:34 +02:00
Bastian Kauschke
870b7cbb11 improve chunks + windows err on size 0 2020-07-30 10:50:34 +02:00
Dylan MacKenzie
9caf0b5222 Make {align,size}_of_val const 2020-07-29 16:50:15 -07:00
Manish Goregaokar
2050128302
Rollup merge of #74910 - RalfJung:fence, r=Mark-Simulacrum
fence docs: fix example Mutex

Fixes https://github.com/rust-lang/rust/issues/74808

Cc @pca006132
2020-07-29 16:38:31 -07:00
Manish Goregaokar
0f9b7bd80f
Rollup merge of #74902 - rust-lang:into_raw_non_null, r=dtolnay
Remove deprecated unstable `{Box,Rc,Arc}::into_raw_non_null` functions

FCP: https://github.com/rust-lang/rust/issues/47336#issuecomment-619369613
2020-07-29 16:38:28 -07:00
Manish Goregaokar
c07998e0e7
Rollup merge of #74852 - lzutao:inline-rm-tostring, r=nnethercote
Explain why inlining default ToString impl

Trying to remove inline attribute from default ToString impl causes regression.
Perf result at <https://github.com/rust-lang/rust/pull/74852#issuecomment-664812994>.
2020-07-29 16:38:22 -07:00
Manish Goregaokar
35226766c9
Rollup merge of #74819 - tmiasko:format-spec, r=joshtriplett
Point towards `format_spec`; it is in other direction
2020-07-29 16:38:20 -07:00
Manish Goregaokar
acad0a0517
Rollup merge of #74742 - poliorcetics:ip-addr-remove-rejected-errata, r=nikomatsakis
Remove links to rejected errata 4406 for RFC 4291

Fixes #74198.

For now I simply removed the links, the docs seems clear enough to me but I'm no expert in the domain so don't hesitate to correct me if more is needed.

cc @ghanan94.

@rustbot modify labels: T-doc, T-libs
2020-07-29 16:38:19 -07:00
bors
6fd4c3f20f Auto merge of #72488 - KodrAus:stabilize/const_type_id, r=nikomatsakis
Stabilize const_type_id feature

The tracking issue for `const_type_id` points to the ill-fated #41875. So I'm re-energizing `TypeId` shenanigans by opening this one up to see if there's anything blocking us from stabilizing the constification of type ids.

Will wait for CI before pinging teams/groups.

-----

This PR stabilizes the `const_type_id` feature, which allows `TypeId::of` (and the underlying unstable intrinsic) to be called in constant contexts.

There are some [sanity tests](https://github.com/rust-lang/rust/blob/master/src/test/ui/consts/const-typeid-of-rpass.rs) that demonstrate its usage, but I’ve included some more below.

As a simple example, you could create a constant item that contains some type ids:

```rust
use std::any::TypeId;

const TYPE_IDS: [TypeId; 2] = [
    TypeId::of::<u32>(),
    TypeId::of::<i32>(),
];

assert_eq!(TypeId::of::<u32>(), TYPE_IDS[0]);
```

Type ids can also now appear in associated constants. You could create a trait that associates each type with its constant type id:

```rust
trait Any where Self: 'static {
    const TYPE_ID: TypeId = TypeId::of::<Self>();
}

impl<T: 'static> Any for T { }

assert_eq!(TypeId::of::<usize>(), usize::TYPE_ID);
```

`TypeId::of` is generic, which we saw above in the way the generic `Self` argument was used. This has some implications for const evaluation. It means we can make trait impls evaluate differently depending on information that wasn't directly passed through the trait system. This violates the _parametricity_ property, which requires all instances of a generic function to behave the same way with respect to its generic parameters. That's not unique to `TypeId::of`, other generic const functions based on compiler intrinsics like `mem::align_of` can also violate parametricity. In practice Rust doesn't really have type parametricity anyway since it monomorphizes generics into concrete functions, so violating it using type ids isn’t new.

As an example of how impls can behave differently, you could combine constant type ids with the `const_if_match` feature to dispatch calls based on the type id of the generic `Self`, rather than based on information about `Self` that was threaded through trait bounds. It's like a rough-and-ready form of specialization:

```rust
#![feature(const_if_match)]

trait Specialized where Self: 'static {
    // An associated constant that determines the function to call
    // at compile-time based on `TypeId::of::<Self>`.
    const CALL: fn(&Self) = {
        const USIZE: TypeId = TypeId::of::<usize>();

        match TypeId::of::<Self>() {
            // Use a closure for `usize` that transmutes the generic `Self` to
            // a concrete `usize` and dispatches to `Self::usize`.
            USIZE => |x| Self::usize(unsafe { &*(x as *const Self as *const usize) }),
            // For other types, dispatch to the generic `Self::default`.
            _ => Self::default,
        }
    };

    fn call(&self) {
        // Call the function we determined at compile-time
        (Self::CALL)(self)
    }

    fn default(x: &Self);
    fn usize(x: &usize);
}

// Implement our `Specialized` trait for any `Debug` type.
impl<T: fmt::Debug + 'static> Specialized for T {
    fn default(x: &Self) {
        println!("default: {:?}", x);
    }

    fn usize(x: &usize) {
        println!("usize: {:?}", x);
    }
}

// Will print "usize: 42"
Specialized::call(&42usize);

// Will print "default: ()"
Specialized::call(&());
```

Type ids have some edges that this stabilization exposes to more contexts. It's possible for type ids to collide (but this is a bug). Since they can change between compiler versions, it's never valid to cast a type id to its underlying value.
2020-07-29 15:58:32 +00:00
carbotaniuman
784dd22aac add unsigned_abs to signed integers 2020-07-29 10:38:58 -05:00
Ralf Jung
897149a883 fence docs: fix example Mutex 2020-07-29 15:45:42 +02:00
Tim Diekmann
b01fbc437e Simplify implementations of AllocRef for Global and System 2020-07-29 11:41:36 +02:00
Simon Sapin
1fb67363bf Remove deprecated unstable {Box,Rc,Arc}::into_raw_non_null functions
FCP: https://github.com/rust-lang/rust/issues/47336#issuecomment-619369613
2020-07-29 11:00:31 +02:00
Simon Sapin
7d759f539f Stabilize Vec::leak 2020-07-29 10:53:55 +02:00
Simon Sapin
d8bcf75206 Make Vec::leak a method instead of an associated function.
The reason for `Box::leak` not to be a method (`Deref` to an arbitrary `T`
which might have its own, different `leak` method) does not apply.
2020-07-29 10:53:55 +02:00