1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-19 06:42:38 +02:00

Add example where breaking UTF-8 encoding leads to a crash. (#387)

This commit is contained in:
gendx 2023-02-16 03:19:44 +00:00 committed by GitHub
parent fe21b773e7
commit 29b6b90bfc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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()
}
```