Sub topic 2
UTF-8 and what a Rust string really holds
This chapter explains the data inside a str or String. It assumes you know basic Rust syntax, ownership and borrowing, and Option and Result. It also assumes you know the difference between &str and String from the previous chapter. Here the focus is on bytes, code points, and the guarantee Rust makes about them.
The guarantee: valid UTF-8, always
A Rust str is a sequence of bytes that is always valid UTF-8. A String is an owned, growable buffer with the same guarantee. Internally, String wraps a Vec<u8>.
The guarantee is an invariant. Safe code cannot create a str that breaks it, and the standard library relies on it. Methods such as chars() and to_uppercase() can skip validation because the data is already known to be valid. Functions that accept untrusted bytes, such as String::from_utf8, check them first. A later chapter covers that case.
Rust strings are not null-terminated, and they are not arrays of characters. They are byte buffers plus a length. A \0 byte is legal inside a str.
Code points, scalar values, and bytes
Three terms are easy to mix up:
- A code point is a number from U+0000 to U+10FFFF that Unicode assigns to a character or symbol.
- A Unicode scalar value is any code point except the surrogate range U+D800 to U+DFFF. Surrogates exist only for UTF-16 and are never valid on their own.
- A byte is an 8-bit value. UTF-8 stores each scalar value as one to four bytes.
Rust's char type holds exactly one Unicode scalar value. It always takes 4 bytes in memory, whatever the character is. The compiler rejects '\u{D800}', and char::from_u32(0xD800) returns None.
fn main() {
println!("{:?}", char::from_u32(0x1F980));
println!("{:?}", char::from_u32(0xD800));
println!("{:?}", char::from_u32(0x110000));
}This prints Some('🦀'), None, and None.
How UTF-8 encodes a scalar value
UTF-8 is a variable-width encoding. The number of bytes depends on the size of the code point.
| Scalar value range | Bytes | Byte pattern |
|---|---|---|
| U+0000 to U+007F | 1 | `0xxxxxxx` |
| U+0080 to U+07FF | 2 | `110xxxxx 10xxxxxx` |
| U+0800 to U+FFFF | 3 | `1110xxxx 10xxxxxx 10xxxxxx` |
| U+10000 to U+10FFFF | 4 | `11110xxx 10xxxxxx 10xxxxxx 10xxxxxx` |
The x bits hold the code point's binary digits. The leading bits of each byte tell a decoder what kind of byte it is:
- A byte starting with
0is a complete ASCII character. - A byte starting with
11begins a multi-byte sequence. The count of leading1bits gives the sequence length. - A byte starting with
10is a continuation byte and never starts a character.
Two consequences follow:
- Every ASCII string is already valid UTF-8, with identical bytes.
- UTF-8 is self-synchronizing. From any byte position, you can tell whether you are at the start of a character by checking whether the byte starts with
10. Rust uses this to find character boundaries.
Seeing the bytes
The char::encode_utf8 method writes a character's encoding into a buffer. A 4-byte buffer is always large enough.
fn main() {
for ch in ['h', 'é', '€', '🦀'] {
let mut buf = [0u8; 4];
let encoded = ch.encode_utf8(&mut buf);
println!(
"{ch} U+{:04X} -> {} bytes: {:02X?}",
ch as u32,
encoded.len(),
encoded.as_bytes()
);
}
}The output is:
h U+0068 -> 1 bytes: [68]
é U+00E9 -> 2 bytes: [C3, A9]
€ U+20AC -> 3 bytes: [E2, 82, AC]
🦀 U+1F980 -> 4 bytes: [F0, 9F, A6, 80]Take é, U+00E9. In binary the code point is 11101001. It falls in the 2-byte range, so those bits fill the pattern 110xxxxx 10xxxxxx. The result is 11000011 10101001, which is C3 A9.
The as_bytes() method gives you a &[u8] view of any str without copying. The call is free, because the string is already stored as bytes.
Length is bytes, not characters
len() on a str or String returns the number of bytes. It does not return the number of characters. This is the most common surprise for people coming from languages with UTF-16 or fixed-width strings.
fn main() {
let s = "héllo";
println!("{}", s.len());
println!("{}", s.chars().count());
}The first line prints 6 and the second prints 5. The letter é takes two bytes. Counting characters means decoding the whole string, so chars().count() is O(n). len() is O(1) because the length is stored.
Choose the one that matches what you need:
- Use
len()to size buffers, check byte limits in a protocol, or compute slice ranges. - Use
chars().count()to count scalar values. - Neither one counts what a person sees as "characters". The next sections and a later chapter on graphemes explain why.
Character boundaries
Because characters have different widths, not every byte offset is a valid place to cut a string. A char boundary is an offset at the start of a character or at the end of the string. The is_char_boundary method tests an offset.
fn main() {
let s = "héllo";
for i in 0..=s.len() {
println!("{i}: {}", s.is_char_boundary(i));
}
}The bytes of héllo are h, C3, A9, l, l, o. Offset 2 points at A9, a continuation byte inside é, so it is the only offset from 0 to 6 that prints false. Offset 6 is the end of the string, and it counts as a boundary.
Slicing with a non-boundary offset panics. A later chapter covers slicing in detail. For now, remember that the boundary rule comes directly from how UTF-8 is laid out.
Layers: bytes, scalar values, and what users see
A string can be viewed at three levels. Each level groups the one below it.
Rust's standard library works at the first two levels. bytes() gives the bottom level and chars() gives the middle one. The top level needs an external crate such as unicode-segmentation, because grapheme rules change with Unicode versions.
Same appearance, different data
One visible character can be built in more than one way. The letter é can be the single scalar value U+00E9, or it can be e followed by U+0301, a combining acute accent.
fn main() {
let precomposed = "\u{e9}";
let decomposed = "e\u{301}";
println!("{precomposed} {decomposed}");
println!("{} {}", precomposed.len(), decomposed.len());
println!("{} {}", precomposed.chars().count(), decomposed.chars().count());
println!("{}", precomposed == decomposed);
}Both strings usually render the same. The output of the last three lines is:
2 3
1 2
falseRust compares strings byte by byte. It does not normalize Unicode, so these two strings are unequal. If you compare user-entered text such as usernames, normalize it first. The unicode-normalization crate provides NFC and NFD forms. The standard library has no normalization.
Case conversion can change length
Because Rust strings are Unicode-aware, to_uppercase and to_lowercase follow Unicode rules, not a simple ASCII shift. Some characters expand. The German ß uppercases to SS, which turns one scalar value into two.
fn main() {
let s = "straße";
let upper = s.to_uppercase();
println!("{upper}");
println!("{} {}", s.len(), upper.len());
}The output is STRASSE, then 7 7. The lengths match here by coincidence: ß takes 2 bytes and SS takes 2 bytes. The character count changes from 6 to 7. Never assume that case conversion preserves length. The methods to_ascii_uppercase and make_ascii_uppercase change only ASCII letters and keep the length.
Common mistakes
- Treating
len()as a character count. Usechars().count()when you mean scalar values. - Cutting a string at an arbitrary byte offset. Check
is_char_boundary, or useget, which returnsNoneinstead of panicking. - Assuming one
charis one visible character. Combining marks and emoji sequences span severalcharvalues. - Comparing text that may be in different normalization forms. Equal-looking strings can be unequal in Rust.
- Expecting a string to hold arbitrary bytes. Binary data belongs in
Vec<u8>or&[u8]. Astrmust be valid UTF-8, and\xFFis not allowed in a string literal.
Exercises
Exercise
What do "a€🦀".len() and "a€🦀".chars().count() return, and why do the two differ?
Show answer
len() returns 8 and chars().count() returns 3. The string has three scalar values. a takes 1 byte, € (U+20AC) takes 3 bytes, and 🦀 (U+1F980) takes 4 bytes, so the byte total is 1 + 3 + 4 = 8. len() counts bytes, while chars().count() decodes the string and counts scalar values.
Exercise
For let s = "a€🦀";, which offsets from 0 to s.len() inclusive are char boundaries?
Show answer
Offsets 0, 1, 4, and 8. Offset 0 is the start of a, offset 1 is the start of €, offset 4 is the start of 🦀, and offset 8 is the end of the string. Offsets 2 and 3 fall inside €, and offsets 5, 6, and 7 fall inside 🦀, so those are not boundaries.
Exercise
Two strings both display as é, but a == b is false and a.len() != b.len(). What is the most likely cause, and how would you fix the comparison?
Show answer
One string probably uses the single scalar value U+00E9 (2 bytes) and the other uses e plus the combining accent U+0301 (3 bytes). Rust compares bytes and does not normalize. Normalize both strings to the same form, such as NFC with the unicode-normalization crate, before comparing.