You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/lessons/15_unsafe/index.md
+31
Original file line number
Diff line number
Diff line change
@@ -37,6 +37,37 @@ In the following code sample, we show all superpowers of `unsafe` code:
37
37
38
38
Safe code may **_never_** cause Undefined Behaviour.
39
39
40
+
This is a valid _sound_ code, with a safe encapsulation over `unsafe` interior.
41
+
42
+
```rust
43
+
fnindex(idx:usize, arr:&[u8]) ->Option<u8> {
44
+
ifidx<arr.len() {
45
+
unsafe {
46
+
Some(*arr.get_unchecked(idx))
47
+
}
48
+
} else {
49
+
None
50
+
}
51
+
}
52
+
```
53
+
54
+
_(Un)soundness_ means that there exists a _possibility_ to trigger UB.
55
+
The following code is _unsound_ (why? what has changed?):
56
+
57
+
```rust
58
+
fnindex(idx:usize, arr:&[u8]) ->Option<u8> {
59
+
ifidx<=arr.len() {
60
+
unsafe {
61
+
Some(*arr.get_unchecked(idx))
62
+
}
63
+
} else {
64
+
None
65
+
}
66
+
}
67
+
```
68
+
69
+
But we only changed safe code! This shows that `unsafe` is unfortunately not perfectly scoped and isolated. We need to be extra careful when writing `unsafe` code.
0 commit comments