mirror of
https://github.com/quickwit-oss/tantivy.git
synced 2026-11-24 19:44:11 +00:00
BitUnpacker::get_range: compute range bounds in u64 (#3177)
On 32-bit targets, the usize bound computation could wrap. The range check then passed and the fast path read out of bounds. In u64, it cannot overflow. On 64-bit targets, the generated code is the same.
This commit is contained in:
@@ -123,19 +123,23 @@ impl BitUnpacker {
|
||||
output.fill(0);
|
||||
return;
|
||||
}
|
||||
let start_idx = start_idx as usize;
|
||||
let end_bit = (start_idx + output.len()) * self.num_bits;
|
||||
// The bound computations are done in u64, so they cannot overflow on 32-bit targets:
|
||||
// `(u32::MAX + output.len()) * 64` fits in a u64. On 64-bit targets, this is the same
|
||||
// code as with usize.
|
||||
let end_bit: u64 = (start_idx as u64 + output.len() as u64) * self.num_bits as u64;
|
||||
debug_assert!(
|
||||
end_bit.div_ceil(8) <= data.len(),
|
||||
end_bit.div_ceil(8) <= data.len() as u64,
|
||||
"Requested range is out of bounds"
|
||||
);
|
||||
let start_idx = start_idx as usize;
|
||||
|
||||
// Fall back for ranges overlapping the end, where an eight-byte load would be partial.
|
||||
let last_bit_addr = (start_idx + output.len() - 1) * self.num_bits;
|
||||
let last_bit_addr: u64 =
|
||||
(start_idx as u64 + output.len() as u64 - 1) * self.num_bits as u64;
|
||||
// The optimization happening below requires reading full 8 bytes word.
|
||||
// We check that data is long enough to allow for the last read, and if not, fall back for
|
||||
// the following safe implementation
|
||||
if (last_bit_addr >> 3) + 8 > data.len() {
|
||||
if (last_bit_addr >> 3) + 8 > data.len() as u64 {
|
||||
for (offset, out) in output.iter_mut().enumerate() {
|
||||
*out = self.get((start_idx + offset) as u32, data);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user