Skip to content

Commit

Permalink
rust: use while let in trim_whitespace implementation
Browse files Browse the repository at this point in the history
originally proposed in a comment at #911 (comment)

- using while let allows us to combine all tests and
  the reminder construction  into one pattern
- without slice indexing and as such  the use of the `Index` trait
  we can now also make the function `const`
- a quick comparison on [Compiler Explorer](https://godbolt.org/z/Ex5dT8ffr)
  shows no changes in the resulting instructions,
  at least for the checked constellation

Signed-off-by: Bennet Bleßmann <[email protected]>
  • Loading branch information
Skgland committed Oct 19, 2022
1 parent 71bc611 commit 42571a8
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions rust/kernel/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,16 +608,12 @@ macro_rules! fmt {
/// assert_eq!(trim_whitespace(b" foo"), b"foo");
/// assert_eq!(trim_whitespace(b" foo "), b"foo");
/// ```
pub fn trim_whitespace(mut data: &[u8]) -> &[u8] {
while !data.is_empty() && (data[0] == b' ' || data[0] == b'\t' || data[0] == b'\n') {
data = &data[1..];
}
while !data.is_empty()
&& (data[data.len() - 1] == b' '
|| data[data.len() - 1] == b'\t'
|| data[data.len() - 1] == b'\n')
{
data = &data[..data.len() - 1];
pub const fn trim_whitespace(mut data: &[u8]) -> &[u8] {
while let [b' ' | b'\t' | b'\n', remainder @ ..] = data {
data = remainder;
}
while let [remainder @ .., b' ' | b'\t' | b'\n'] = data {
data = remainder;
}
data
}

0 comments on commit 42571a8

Please sign in to comment.