A Rust CSV parser slices fields with `&line[start..end]` on untrusted input — which inputs make it panic, and how do you make it panic-free?
answer
- past the end, backwards, mid-character
- an empty range at the end is fine
- Option instead of a panic
- indices that come from find or split
basics
~20 s&line[a..b] panics when b exceeds the length, when a is greater than b, and, on a str, when a or b falls inside a multi-byte character. On untrusted input use line.get(a..b), which returns None instead, or let split and find produce the boundaries.
solid answer
~40 sRange indexing on `str` and `[T]` checks bounds at run time and **panics** on a bad range: an end past the length ("end byte index 20 is out of bounds for string of length 8"), a start after the end, and, for `str` only, a start or end inside a multi-byte UTF-8 character ("end byte index 7 is not a char boundary"). An empty range at the very end, `&v[v.len()..]`, is fine. On untrusted input a panic is a denial of service: one malformed line unwinds the worker thread, or ends the process under `panic = "abort"`. The fix is the checked API: `str::get(a..b)` and `<[T]>::get(a..b)` return `Option`, and `split_at_checked` (Rust 1.80) does the same for a split point. Better still, avoid hand-computed offsets: `find(',')` and `split(',')` only produce valid boundaries.
code
rust · 18 linesfn field(line: &str, start: usize, end: usize) -> Option<&str> {
line.get(start..end)
}
fn main() {
let line = String::from("42,café"); // 8 bytes: 'é' takes two
println!("{:?}", field(&line, 3, 8)); // Some("café")
println!("{:?}", field(&line, 3, 7)); // None: byte 7 is inside 'é'
println!("{:?}", field(&line, 3, 20)); // None: past the end
println!("{:?}", field(&line, 5, 3)); // None: start after end
// Bytes have no char boundaries, only the length check.
println!("{:?}", line.as_bytes().get(3..7));
// Direct indexing with the same bad range panics.
let end = 7;
println!("{}", &line[3..end]);
}go deeper
Recall that slicing with a range outside the data panics at run time instead of returning an error.
Explain all three panic causes, including the str-only char-boundary rule, and that an empty range at the end is valid.
Treat a panicking slice on hostile input as a denial of service, and show the fix: get returning Option, boundaries from find and split, outside offsets validated.
Argue for a no-panic rule in parser modules, enforced with clippy's indexing_slicing and string_slice lints rather than by reviewer memory.
## Range indexing checks at run time `&s[a..b]` on a `str` and `&v[a..b]` on a slice (a `Vec` or an array reaches the same code) go through the `Index` trait. The bounds are ordinary run-time values, so the check happens at run time, and a failed check is a **panic**, not an `Err`. The doc comment on `str`'s range indexing lists the conditions: it panics if `begin` or `end` does not point to the starting byte offset of a character, if `begin > end`, or if `end > len`. Messages printed by rustc 1.99.1 for `line = "42,café"` (8 bytes, because `é` takes two) and `v = vec![1, 2, 3]`: | Expression | Result | |---|---| | `&line[3..20]` | panics: `end byte index 20 is out of bounds for string of length 8` | | `&line[5..3]` | panics: `byte range starts at 5 but ends at 3` | | `&line[3..7]` | panics: `end byte index 7 is not a char boundary; it is inside 'é' (bytes 6..8 of string)` | | `&v[2..5]` | panics: `range end index 5 out of range for slice of length 3` | | `&v[2..1]` | panics: `slice index starts at 2 but ends at 1` | | `&v[4..]` | panics: `range start index 4 out of range for slice of length 3` | | `&v[3..]` | an empty slice, no panic | | `&line[3..8]` | `"café"` | Two details are easy to get wrong: - **An empty range at the end is legal.** `&v[v.len()..]` and `&v[0..0]` are valid empty slices; only an index *past* the length fails. - **The char-boundary rule exists only for `str`.** `line.as_bytes()[3..7]` succeeds and yields four bytes, the last of them half of `é`, because a `&[u8]` knows nothing about characters. (How UTF-8 encodes characters is covered with strings.) ## Why it matters on untrusted input A parser that computes `start` and `end` from data it does not control, such as a length header in a network frame, a column width counted in characters, or an offset sent by a peer, hands whoever writes that data a way to trigger the panic. With the default unwinding strategy a panic unwinds the current thread, so one malformed line can take down a worker; in a build with `panic = "abort"` it ends the whole process. For a node accepting transactions from the network, or a service parsing uploaded CSV, that is a **denial of service** reachable with a single request. Offsets typically go wrong in three ways: - **Trusting a declared length.** A record header says the next field is 40 bytes long, but the line holds 12; `&line[start..start + 40]` panics on the end bound. - **Counting characters, then slicing bytes.** A fixed-width format says column two starts at position 5; with `é` or any other multi-byte character earlier in the line, byte 5 is no longer that position and may sit mid-character. - **Arithmetic that runs backwards.** Trimming a quote from both ends of `""` with `&field[1..field.len() - 1]` asks for `1..1` on a 2-byte field, which is fine, but on a 1-byte field `"` it asks for `1..0`, a start after the end. ## Making it panic-free 1. **Use the checked accessors.** `str::get(a..b)` returns `Option<&str>` and `<[T]>::get(a..b)` returns `Option<&[T]>`; both return `None` for every panicking row in the table above. `split_at_checked(mid)`, stable since Rust 1.80 on both `str` and slices, returns `None` where `split_at` would panic, and `split_at_mut_checked` is its mutable twin. 2. **Let the string produce the boundaries.** `str::find(',')` returns the byte index where the match starts, which for a `char` or `&str` pattern always lies on a character boundary; `split(',')`, `split_once(',')` and `lines()` hand back slices without exposing an index at all. A parser built only from these cannot hit the char-boundary panic. 3. **Validate offsets that come from outside.** Check them with `str::is_char_boundary` before slicing, or turn the `None` from `get` into the parser's own error type with `ok_or` and propagate it with `?`. 4. **Let the linter watch.** Clippy's restriction-group lints `indexing_slicing` and `string_slice` flag panicking index expressions in a crate that opts in, which suits a parser module that must never panic. ```rust fn field(line: &str, start: usize, end: usize) -> Option<&str> { line.get(start..end) } ``` The `Option` turns a crash into a value the caller has to handle. ## What to say in an interview - Name the panic causes: end past the length, start after end, and, for `str` only, an index inside a multi-byte character. - Point out that `&v[v.len()..]` is fine and returns an empty slice. - Reach for `get` first, and explain why indices derived from `find` and `split` are safe while outside offsets are not. - Frame the panic as an availability bug on hostile input, not as a style issue.
- Why is an index from `line.find(',')` safe to slice with, while a column width read from a file header is not?`find` returns the byte offset where a match starts in this very string, and for a `char` or `&str` pattern that is always a character boundary. A width from a header is usually a count of characters, not bytes, so on any non-ASCII text it lands mid-character or past the end. Treat it as untrusted: slice with `get` or check `is_char_boundary` first.
- How should the parser report a bad range to its caller?Return a `Result` and convert the `Option` from `get` into the parser's own error type with `ok_or` or `ok_or_else`, then propagate with `?`. The caller sees which line and offset were bad and decides whether to skip the row or reject the file, instead of the process deciding for it by panicking.
- Slicing past the end returns a shorter slice, clamped to the length.
- &v[v.len()..] panics because the start index is out of range.
- Slicing a str returns an Err when the index splits a character.
- Slicing as_bytes() also panics on an index inside a character.
- Byte indices returned by str::find can land inside a multi-byte character.
Assumes Rust 1.99 on edition 2024; get and the indexing panics are long-standing, while split_at_checked and split_at_mut_checked need Rust 1.80 or later.