Calling Unsafe Functions

A function or method can be marked unsafe if it has extra preconditions you must uphold to avoid undefined behaviour:

1. fn main() {
2. let emojis = "🗻∈🌏";

4. // Safe because the indices are in the correct order, within the bounds of
5. // the string slice, and lie on UTF-8 sequence boundaries.
6. unsafe {
7. println!("emoji: {}", emojis.get_unchecked(0..4));
8. println!("emoji: {}", emojis.get_unchecked(4..7));
9. println!("emoji: {}", emojis.get_unchecked(7..11));
10. }

12. println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..7) }));

14. // Not upholding the UTF-8 encoding requirement breaks memory safety!
15. // println!("emoji: {}", unsafe { emojis.get_unchecked(0..3) });
16. // println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..3) }));
17. }

19. fn count_chars(s: &str) -> usize {
20. s.chars().map(|_| 1).sum()
21. }