str::trim_ascii_end¶
Level: reference · for working programmers
One line: trim_ascii at the back only — const, ASCII-only, trailing bytes removed.
Stable since 1.80.0. Usable in a const context.
The ASCII, const-capable counterpart of trim_end.
Its most common job is dropping a line ending from ASCII input — it removes \n and a preceding \r together, since both are in its set, which makes it a cheap line.trim_ascii_end() for protocol text.
Example¶
str_trim_ascii_end.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let line = " GET /index.html \r\n";
println!("{:?}", line.trim_ascii_end());
println!("{:?}", line.trim_ascii());
// \r\n both go, since both are ASCII whitespace.
for raw in ["ok\n", "ok\r\n", "ok"] {
println!("{:<8} -> {:?}", format!("{raw:?}"), raw.trim_ascii_end());
}
// const.
const PADDED: &str = "value ";
const TIDY: &str = PADDED.trim_ascii_end();
println!("{TIDY:?} ({} bytes)", TIDY.len());
}
Verified output of str_trim_ascii_end.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::trim_ascii— both endsstr::trim_ascii_start— the other endstr::trim_end— the Unicode-aware versionstr::lines— when the whole job is line endings
str::trim_ascii_end in the standard library ↗
Po polsku¶
Praktyczny powód, dla którego ta metoda przydaje się osobno, to windowsowe zakończenia wierszy: \r i \n należą do tego samego zestawu pięciu bajtów, więc "ok\r\n".trim_ascii_end() zdejmuje oba za jednym razem, podczas gdy strip_suffix('\n') zostawiłoby osierocone \r. Początek zostaje przy tym nietknięty — " GET /index.html \r\n" daje " GET /index.html", ze spacjami z lewej strony na miejscu; jeśli mają zniknąć oba końce, potrzebne jest trim_ascii. Metoda jest const, więc literał wolno przyciąć już w czasie kompilacji, i to jest właściwy wybór do tekstu protokołów; do wiersza napisanego przez człowieka lepsze będzie trim_end, które rozumie też unikodowe białe znaki.
Szukaj po polsku: zakończenie wiersza CRLF · obcinanie z prawej strony · rust trim_ascii_end · rust remove trailing newline