[0]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#651
[1]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#567 [0]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=847dc401e16fdff14ecf3724a3b15a93
[1]: https://doc.rust-lang.org/cargo/reference/profiles.html for x in some_array { // copy semantics
for &x in some_array { // reference semantics
// no move semantics? (could be wrong on this)
Rust: for x in vec.iter_ref().copied() { // bytewise copy semantics (only for POD types)
for x in vec.iter_ref().cloned() { // RAII copy semantics
for x in &vec { // reference semantics
for x in vec { // move semantics
C++: for (auto x : vec) { // copy semantics
for (auto &x : vec) { // reference semantics
for (auto &&x : vec) { // move semantics // Assume std::vec has this definition
struct Vec<T> {
capacity: usize,
length: usize,
arena: * T
}
enum Example {
First {
capacity: usize,
length: usize,
arena: usize,
discriminator: NonZero<u8>
},
Second {
vec: Vec<u8>
}
}
Now assume the compiler has used niche optimization so that if the byte corresponding to `discriminator` is 0, then the enum is `Example::Second`, while if the byte corresponding to `discriminator` is not 0, then the enum is `Example::First` with discriminator being equal to its given non-zero value. Furthermore, assume that `Example::First`'s `capacity`, `length`, and `arena` fields are in the in the same position as the fields of the same name for `Example::Second.vec`. If we allow `fn NonZero::new_unchecked(u8) -> NonZero<u8>` to be a safe function, we can create an invalid Vec: fn main() {
let evil = NonZero::new_unchecked(0);
// We write as an Example::First,
// but this is read as an Example::Second
// because discriminator == 0 and niche optimization
let first = Example::First {
capacity: 9001, length: 9001,
arena: 0x20202020,
discriminator: evil
}
if let Example::Second{ vec: bad_vec } = first {
// If the layout of Example is as I described,
// and no optimizations occur, we should end up in here.
// This writes 255 to address 0x20202020
bad_vec[0] = 255;
}
}
So if we allowed new_unchecked to be safe, then it would be impossible to write a sound definition of Vec.
I don't want to have to do a literature review again, and sharing papers is hard because they are often paywalled unless you are associated with a university or are willing to pirate them.
Luckily, The American Psychological Association [0] has shared this nice health advisory [1] which goes into detail. The APA has stewarded psychology research and communicated it to the public in the US for a long time. They have a good track record.
[0]: https://en.wikipedia.org/wiki/American_Psychological_Associa...
[1]: https://www.apa.org/topics/social-media-internet/health-advi...