Skip to content

Commit bc689e5

Browse files
committed
cat: Optimized inc_one function
Gets to 1% better than original implementation.
1 parent 606655e commit bc689e5

File tree

1 file changed

+10
-24
lines changed

1 file changed

+10
-24
lines changed

src/uu/cat/src/cat.rs

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -44,34 +44,20 @@ const ABOUT: &str = help_about!("cat.md");
4444
/// We also assume that there is enough space in val to expand if start needs
4545
/// to be updated.
4646
#[inline]
47-
fn fast_inc(val: &mut [u8], start: usize, end: usize, inc: &[u8]) -> usize {
47+
fn fast_inc_one(val: &mut [u8], start: usize, end: usize) -> usize {
4848
// To avoid a lot of casts to signed integers, we make sure to decrement pos
4949
// as late as possible, so that it does not ever go negative.
50-
let mut pos = end;
51-
let mut carry = 0u8;
50+
let mut pos = end - 1;
5251

53-
// First loop, add all digits of inc into val.
54-
for inc_pos in (0..inc.len()).rev() {
55-
pos -= 1;
56-
57-
let mut new_val = inc[inc_pos] + carry;
58-
// Be careful here, only add existing digit of val.
59-
if pos >= start {
60-
new_val += val[pos] - b'0';
61-
}
62-
if new_val > b'9' {
63-
carry = 1;
64-
new_val -= 10;
65-
} else {
66-
carry = 0;
67-
}
68-
val[pos] = new_val;
52+
val[pos] = 1 + val[pos];
53+
if val[pos] > b'9' {
54+
val[pos] -= 10;
55+
} else {
56+
return start;
6957
}
7058

71-
// Done, now, if we have a carry, add that to the upper digits of val.
72-
if carry == 0 {
73-
return start.min(pos);
74-
}
59+
// We have a carry
60+
7561
while pos > start {
7662
pos -= 1;
7763

@@ -125,7 +111,7 @@ impl LineNumber {
125111
}
126112

127113
fn increment(&mut self) {
128-
self.start = fast_inc(self.buf.as_mut_slice(), self.start, self.num_end, &[b'1']);
114+
self.start = fast_inc_one(self.buf.as_mut_slice(), self.start, self.num_end);
129115
self.print_start = self.print_start.min(self.start);
130116
}
131117

0 commit comments

Comments
 (0)