Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change trim_whitespace implementation to use while let #913

Open
wants to merge 3 commits into
base: rust
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions rust/kernel/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,3 +595,25 @@ impl Deref for CString {
macro_rules! fmt {
($($f:tt)*) => ( core::format_args!($($f)*) )
}

/// Trims leading and trailing whitespace (` `, `\t` and `\n`).
///
/// # Examples
///
/// ```
/// # use kernel::str::trim_whitespace;
/// assert_eq!(trim_whitespace(b"" ), b"");
/// assert_eq!(trim_whitespace(b" "), b"");
/// assert_eq!(trim_whitespace(b"foo "), b"foo");
/// assert_eq!(trim_whitespace(b" foo"), b"foo");
/// assert_eq!(trim_whitespace(b" foo "), b"foo");
/// ```
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
}
28 changes: 1 addition & 27 deletions rust/kernel/sysctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
bindings,
error::code::*,
io_buffer::IoBufferWriter,
str::CStr,
str::{trim_whitespace, CStr},
types,
user_ptr::{UserSlicePtr, UserSlicePtrWriter},
Result,
Expand All @@ -31,20 +31,6 @@ pub trait SysctlStorage: Sync {
fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, Result);
}

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];
}
data
}

impl<T> SysctlStorage for &T
where
T: SysctlStorage,
Expand Down Expand Up @@ -185,15 +171,3 @@ impl<T: SysctlStorage> Drop for Sysctl<T> {
self.header = ptr::null_mut();
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_trim_whitespace() {
assert_eq!(trim_whitespace(b"foo "), b"foo");
assert_eq!(trim_whitespace(b" foo"), b"foo");
assert_eq!(trim_whitespace(b" foo "), b"foo");
}
}