1
1
# Safety comments
2
2
3
- Using [ ` unsafe ` ] blocks in often required in the Rust compiler or standard
3
+ Using [ ` unsafe ` ] blocks is often required in the Rust compiler or standard
4
4
library, but this is not done without rules: each ` unsafe ` block should have
5
5
a ` SAFETY: ` comment explaining why the block is safe, which invariants are
6
6
used and must be respected. Below are some examples taken from the standard
@@ -15,6 +15,8 @@ caller with the use of documentation in a `# Safety` section while still having
15
15
more invariants needed that are not required from callers. ` clippy ` has a
16
16
lint for ` # Safety ` sections by the way.
17
17
18
+ [ See the example on github] [ as_bytes_mut ]
19
+
18
20
``` rust
19
21
/// Converts a mutable string slice to a mutable byte slice.
20
22
///
@@ -35,8 +37,6 @@ pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
35
37
}
36
38
```
37
39
38
- [ See the function on github] [ as_bytes_mut ]
39
-
40
40
This example is for a function but the same principle applies to ` unsafe trait ` s
41
41
like [ ` Send ` ] or [ ` Sync ` ] for example, though they have no ` # Safety ` section
42
42
since their entire documentation is about why they are ` unsafe ` .
@@ -54,14 +54,16 @@ their `unsafe` parts.
54
54
## Inside * safe* elements
55
55
56
56
Inside safe elements, a ` SAFETY: ` comment must not depend on anything from the
57
- caller beside properly contruscted types and values (i.e, if your function
58
- receive a reference that is unaligned or null, it's the caller fault if it fails
59
- and not yours).
57
+ caller beside properly constructed types and values (i.e, if your function
58
+ receives a reference that is unaligned or null, it is the caller fault if it
59
+ fails and not yours).
60
60
61
61
` SAFETY ` comments in * safe* elements often rely on checks that are done before
62
62
the ` unsafe ` block or on type invariants, like a division by ` NonZeroU8 ` would
63
63
not check for ` 0 ` before dividing.
64
64
65
+ [ See the example on github] [ split_at ]
66
+
65
67
``` rust
66
68
pub fn split_at (& self , mid : usize ) -> (& str , & str ) {
67
69
// is_char_boundary checks that the index is in [0, .len()]
@@ -74,6 +76,4 @@ pub fn split_at(&self, mid: usize) -> (&str, &str) {
74
76
}
75
77
```
76
78
77
- [ See the function on github] [ split_at ]
78
-
79
79
[ split_at ] : https://github.com/rust-lang/rust/blob/a08f25a7ef2800af5525762e981c24d96c14febe/library/core/src/str/mod.rs#L570
0 commit comments