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

Improved performance by eliminating String creation by utilizing the original &str slice. #31

Merged
merged 1 commit into from
Aug 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 28 additions & 8 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ impl std::str::FromStr for ByteSize {
if let Ok(v) = value.parse::<u64>() {
return Ok(Self(v));
}
let number: String = value
.chars()
.take_while(|c| c.is_ascii_digit() || c == &'.')
.collect();
let number = take_while(value, |c| c.is_ascii_digit() || c == '.');
match number.parse::<f64>() {
Ok(v) => {
let suffix: String = value
.chars()
.skip_while(|c| c.is_whitespace() || c.is_ascii_digit() || c == &'.')
.collect();
let suffix = skip_while(value, |c| {
c.is_whitespace() || c.is_ascii_digit() || c == '.'
});
match suffix.parse::<Unit>() {
Ok(u) => Ok(Self((v * u) as u64)),
Err(error) => Err(format!(
Expand All @@ -33,6 +29,30 @@ impl std::str::FromStr for ByteSize {
}
}

fn take_while<P>(s: &str, mut predicate: P) -> &str
where
P: FnMut(char) -> bool,
{
let offset = s
.chars()
.take_while(|ch| predicate(*ch))
.map(|ch| ch.len_utf8())
.sum();
&s[..offset]
}

fn skip_while<P>(s: &str, mut predicate: P) -> &str
where
P: FnMut(char) -> bool,
{
let offset: usize = s
.chars()
.skip_while(|ch| predicate(*ch))
.map(|ch| ch.len_utf8())
.sum();
&s[(s.len() - offset)..]
}

enum Unit {
Byte,
// power of tens
Expand Down