diff --git a/src/unsafe/calling-unsafe-functions.md b/src/unsafe/calling-unsafe-functions.md index 042e2182..6c0bc920 100644 --- a/src/unsafe/calling-unsafe-functions.md +++ b/src/unsafe/calling-unsafe-functions.md @@ -10,9 +10,19 @@ fn main() { // Safe because the indices are in the correct order, within the bounds of // the string slice, and lie on UTF-8 sequence boundaries. unsafe { - println!("{}", emojis.get_unchecked(0..4)); - println!("{}", emojis.get_unchecked(4..7)); - println!("{}", emojis.get_unchecked(7..11)); + println!("emoji: {}", emojis.get_unchecked(0..4)); + println!("emoji: {}", emojis.get_unchecked(4..7)); + println!("emoji: {}", emojis.get_unchecked(7..11)); } + + 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() } ```