Skip to content

Commit 0b3311c

Browse files
committed
std::io: Optimize u64_from_be_bytes()
Instead of reading a byte at a time in a loop we copy the relevant bytes into a temporary vector of size eight. We can then read the value from the temporary vector using a single u64 read. LLVM seems to be able to optimize this almost scarily good.
1 parent 326e631 commit 0b3311c

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

src/libstd/io/extensions.rs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@
1313
// XXX: Not sure how this should be structured
1414
// XXX: Iteration should probably be considered separately
1515

16+
use container::Container;
1617
use iter::Iterator;
1718
use option::Option;
1819
use io::Reader;
19-
use vec::OwnedVector;
20+
use vec::{OwnedVector, ImmutableVector};
2021

2122
/// An iterator that reads a single byte on each iteration,
2223
/// until `.read_byte()` returns `None`.
@@ -117,16 +118,23 @@ pub fn u64_from_be_bytes(data: &[u8],
117118
start: uint,
118119
size: uint)
119120
-> u64 {
120-
let mut sz = size;
121-
assert!((sz <= 8u));
122-
let mut val = 0_u64;
123-
let mut pos = start;
124-
while sz > 0u {
125-
sz -= 1u;
126-
val += (data[pos] as u64) << ((sz * 8u) as u64);
127-
pos += 1u;
128-
}
129-
return val;
121+
use ptr::{copy_nonoverlapping_memory, offset, mut_offset};
122+
use unstable::intrinsics::from_be64;
123+
use vec::MutableVector;
124+
125+
assert!(size <= 8u);
126+
127+
if data.len() - start < size {
128+
fail!("index out of bounds");
129+
}
130+
131+
let mut buf = [0u8, ..8];
132+
unsafe {
133+
let ptr = offset(data.as_ptr(), start as int);
134+
let out = buf.as_mut_ptr();
135+
copy_nonoverlapping_memory(mut_offset(out, (8 - size) as int), ptr, size);
136+
from_be64(*(out as *i64)) as u64
137+
}
130138
}
131139

132140
#[cfg(test)]

0 commit comments

Comments
 (0)