@@ -11,7 +11,7 @@ Unsafe Rust gives us a powerful tool to handle this problem:
11
11
[ ` MaybeUninit ` ] . This type can be used to handle memory that has not been fully
12
12
initialized yet.
13
13
14
- With ` MaybeUninit ` , we can initialize an array element-for- element as follows:
14
+ With ` MaybeUninit ` , we can initialize an array element by element as follows:
15
15
16
16
``` rust
17
17
use std :: mem :: {self , MaybeUninit };
@@ -79,16 +79,15 @@ This code proceeds in three steps:
79
79
acknowledge that by providing appropriate methods).
80
80
81
81
It's worth spending a bit more time on the loop in the middle, and in particular
82
- the assignment operator and its interaction with ` drop ` . If we would have
83
- written something like:
82
+ the assignment operator and its interaction with ` drop ` . If we wrote something like:
84
83
85
84
<!-- ignore: simplified code -->
86
85
``` rust,ignore
87
86
*x[i].as_mut_ptr() = Box::new(i as u32); // WRONG!
88
87
```
89
88
90
89
we would actually overwrite a ` Box<u32> ` , leading to ` drop ` of uninitialized
91
- data, which will cause much sadness and pain.
90
+ data, which would cause much sadness and pain.
92
91
93
92
The correct alternative, if for some reason we cannot use ` MaybeUninit::new ` , is
94
93
to use the [ ` ptr ` ] module. In particular, it provides three functions that allow
@@ -97,16 +96,16 @@ us to assign bytes to a location in memory without dropping the old value:
97
96
98
97
* ` ptr::write(ptr, val) ` takes a ` val ` and moves it into the address pointed
99
98
to by ` ptr ` .
100
- * ` ptr::copy(src, dest, count) ` copies the bits that ` count ` T's would occupy
99
+ * ` ptr::copy(src, dest, count) ` copies the bits that ` count ` T items would occupy
101
100
from src to dest. (this is equivalent to C's memmove -- note that the argument
102
101
order is reversed!)
103
102
* ` ptr::copy_nonoverlapping(src, dest, count) ` does what ` copy ` does, but a
104
103
little faster on the assumption that the two ranges of memory don't overlap.
105
104
(this is equivalent to C's memcpy -- note that the argument order is reversed!)
106
105
107
106
It should go without saying that these functions, if misused, will cause serious
108
- havoc or just straight up Undefined Behavior. The only things that these
109
- functions * themselves* require is that the locations you want to read and write
107
+ havoc or just straight up Undefined Behavior. The only requirement of these
108
+ functions * themselves* is that the locations you want to read and write
110
109
are allocated and properly aligned. However, the ways writing arbitrary bits to
111
110
arbitrary locations of memory can break things are basically uncountable!
112
111
0 commit comments