Skip to content

Commit ebc0fb2

Browse files
committed
Safe code guarantees
1 parent fe16182 commit ebc0fb2

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

content/lessons/15_unsafe/index.md

+31
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,37 @@ In the following code sample, we show all superpowers of `unsafe` code:
3737

3838
Safe code may **_never_** cause Undefined Behaviour.
3939

40+
This is a valid _sound_ code, with a safe encapsulation over `unsafe` interior.
41+
42+
```rust
43+
fn index(idx: usize, arr: &[u8]) -> Option<u8> {
44+
if idx < 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+
fn index(idx: usize, arr: &[u8]) -> Option<u8> {
59+
if idx <= 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.
70+
4071
## Reading
4172

4273
- [The Book, Chapter 19.1](https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html)

0 commit comments

Comments
 (0)