#206
Jun 16, 2026
206. trim_ascii — Trim Whitespace From &[u8] Without Going Through str
Got a &[u8] with leading or trailing whitespace? You don’t need to validate it as UTF-8 just to trim it.
The reflex is to convert to str first — which can fail and forces a UTF-8 check you may not want:
| |
Since Rust 1.80, byte slices trim themselves directly — no str, no validation, no panic path:
| |
It strips ASCII whitespace (space, tab, newline, carriage return, form feed, vertical tab) from a &[u8] and hands back a borrowed sub-slice — zero allocation.
Best part: it’s a const fn, so it works where str::trim can’t:
| |
Reach for it when you’re parsing bytes straight off a socket, file, or buffer and want to clean up edges before validating the rest.