Rust provides a trim method for strings: str.trim() removing leading and trailing whitespace. I want to have a method that does the same for bytestrings. It should take a Vec<u8>
and remove leading and trailing whitespace (space, 0x20 and htab, 0x09).
Writing a trim_left()
is easy, you can just use an iterator with skip_while()
: Rust Playground
fn main() {
let a: &[u8] = b" fo o ";
let b: Vec<u8> = a.iter().map(|x| x.clone()).skip_while(|x| x == &0x20 || x == &0x09).collect();
println!("{:?}", b);
}
But to trim the right characters I would need to look ahead if no other letter is in the list after whitespace was found.
Here's an implementation that returns a slice, rather than a new
Vec<u8>
, asstr::trim()
does. It's also implemented on[u8]
, since that's more general thanVec<u8>
(you can obtain a slice from a vector cheaply, but creating a vector from a slice is more costly, since it involves a heap allocation and a copy).If you really need a
Vec<u8>
after thetrim()
, you can just callinto()
on the slice to turn it into aVec<u8>
.All we have to do is find the index of the first non-whitespace character, one time counting forward from the start, and another time counting backwards from the end.