Skip to content

Commit

Permalink
Merge pull request #31 from ChanTsune/feature/performance-improvement
Browse files Browse the repository at this point in the history
Improved performance by eliminating String creation by utilizing the original &str slice.
  • Loading branch information
hyunsik committed Aug 23, 2023
2 parents 5235bf4 + 68e74bc commit 8dd9145
Showing 1 changed file with 28 additions and 8 deletions.
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

0 comments on commit 8dd9145

Please sign in to comment.