Sub topic 2
UTF-8 and what a Rust string really holds
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option and Result work. It explains what a str or String stores in memory. That model explains the byte-boundary rules you will meet when slicing and indexing in later chapters.
Bytes, code points, and UTF-8
Computers store bytes. Text needs a rule that maps characters to bytes. Unicode assigns each character a number called a code point, such as U+0068 for h and U+00E9 for é. Rust works with Unicode scalar values, which are code points excluding the surrogate range reserved for UTF-16.
UTF-8 is an encoding that turns each scalar value into one to four bytes:
| Scalar value range | Bytes used | Example |
|---|---|---|
| U+0000 to U+007F | 1 | `h` |
| U+0080 to U+07FF | 2 | `é` |
| U+0800 to U+FFFF | 3 | `€` |
| U+10000 to U+10FFFF | 4 | `🦀` |
ASCII text is stored exactly as ASCII. Everything else takes more than one byte per character.
The guarantee Rust makes
Both str and String are guaranteed to contain valid UTF-8. A String is essentially a Vec<u8> with that guarantee attached. The standard library checks the guarantee wherever bytes enter, and safe code cannot break it. Because every operation can rely on it, chars() and to_uppercase() need no extra validation.
Length is measured in bytes
The consequence shows up immediately. len() returns the number of bytes, not the number of characters. To count characters, iterate over them.
fn main() {
let s = "héllo";
println!("{}", s.len());
println!("{}", s.chars().count());
}This prints 6 and then 5. The letter é takes two bytes, so the string has five characters but occupies six bytes.
chars().count() walks the whole string, so it takes time proportional to the length. len() is constant time because the byte count is stored.
Character boundaries
Within a UTF-8 string, some byte positions start a character and others fall in the middle of one. A position that starts a character, or sits at the very end of the string, is called a character boundary. In héllo, the boundaries are at byte offsets 0, 1, 3, 4, 5, and 6. Offset 2 is inside é.
You can check this with is_char_boundary:
fn main() {
let s = "héllo";
for i in 0..=s.len() {
println!("{i}: {}", s.is_char_boundary(i));
}
}Offsets 0, 1, 3, 4, 5, and 6 print true. Offset 2 prints false.
Rust APIs that take byte offsets must receive boundary positions, or they cannot return valid UTF-8. The next chapters build on this rule when slicing.
Common mistakes
- Assuming
len()is the number of characters. It is the number of bytes. - Assuming a character is always one byte. This holds only for ASCII.
- Assuming one
charis one thing a reader sees as a character. Acharis a single scalar value. Some visible characters combine several scalar values, which a later chapter covers under graphemes. - Treating a
Stringas arbitrary bytes. If you hold bytes that might not be valid UTF-8, useVec<u8>or validate them first.
Exercise
What do "€".len() and "€".chars().count() return, and why?
Show answer
len() returns 3 and chars().count() returns 1. The euro sign is a single Unicode scalar value (U+20AC), and UTF-8 encodes it in three bytes. len() counts bytes, while chars().count() counts scalar values.
Exercise
For the string "a🦀b", which byte offsets are character boundaries?
Show answer
Offsets 0, 1, 5, and 6. The letter a takes 1 byte, the crab emoji takes 4 bytes (offsets 1 to 4 are its bytes), and b takes 1 byte. Offsets 2, 3, and 4 fall inside the emoji.