2022-12-21 16:36:30 +01:00
|
|
|
# Calling Unsafe Functions
|
|
|
|
|
|
|
|
A function or method can be marked `unsafe` if it has extra preconditions you
|
2023-01-17 16:35:39 +00:00
|
|
|
must uphold to avoid undefined behaviour:
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
let emojis = "🗻∈🌏";
|
2023-01-17 16:35:39 +00:00
|
|
|
|
|
|
|
// Safe because the indices are in the correct order, within the bounds of
|
|
|
|
// the string slice, and lie on UTF-8 sequence boundaries.
|
2022-12-21 16:36:30 +01:00
|
|
|
unsafe {
|
2023-02-16 03:19:44 +00:00
|
|
|
println!("emoji: {}", emojis.get_unchecked(0..4));
|
|
|
|
println!("emoji: {}", emojis.get_unchecked(4..7));
|
|
|
|
println!("emoji: {}", emojis.get_unchecked(7..11));
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
2023-02-16 03:19:44 +00:00
|
|
|
|
|
|
|
println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..7) }));
|
|
|
|
|
|
|
|
// Not upholding the UTF-8 encoding requirement breaks memory safety!
|
|
|
|
// println!("emoji: {}", unsafe { emojis.get_unchecked(0..3) });
|
|
|
|
// println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..3) }));
|
|
|
|
}
|
|
|
|
|
|
|
|
fn count_chars(s: &str) -> usize {
|
|
|
|
s.chars().map(|_| 1).sum()
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|