diff --git a/bitpacker/src/bitpacker.rs b/bitpacker/src/bitpacker.rs index ebe687c51..4b48b528c 100644 --- a/bitpacker/src/bitpacker.rs +++ b/bitpacker/src/bitpacker.rs @@ -111,6 +111,30 @@ impl BitUnpacker { val_shifted & self.mask } + #[cold] + #[inline(never)] + fn get_pair_slow_path(&self, idx: u32, data: &[u8]) -> (u64, u64) { + (self.get(idx, data), self.get(idx + 1, data)) + } + + /// Reads two consecutive bit-packed values at `idx` and `idx + 1`. + #[inline(always)] + pub fn get_pair(&self, idx: u32, data: &[u8]) -> (u64, u64) { + let addr_in_bits = idx as usize * self.num_bits; + let addr = addr_in_bits >> 3; + // Two consecutive values fit in a single 8-byte load when `num_bits <= 28` + // (`7 + 2 * 28 = 63 <= 64` bits). + if self.num_bits <= 28 && addr + 8 <= data.len() { + let bit_shift = addr_in_bits & 7; + let bytes: [u8; 8] = (&data[addr..addr + 8]).try_into().unwrap(); + let shifted = u64::from_le_bytes(bytes) >> bit_shift; + let first = shifted & self.mask; + let second = (shifted >> self.num_bits) & self.mask; + return (first, second); + } + self.get_pair_slow_path(idx, data) + } + /// Decodes consecutive values into `output`. /// /// Panics if the requested bits are outside `data`. @@ -508,4 +532,34 @@ mod test { } } } + + #[test] + fn test_get_pair_all_bit_widths() { + for num_bits in (0u8..=56).chain(std::iter::once(64)) { + let mask: u64 = if num_bits == 64 { + u64::MAX + } else { + (1u64 << num_bits) - 1 + }; + for len in [2usize, 3, 7, 8, 9, 32, 65] { + let vals: Vec = (0..len) + .map(|i| (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) & mask) + .collect(); + let mut buffer: Vec = Vec::new(); + let mut bitpacker = BitPacker::new(); + for &val in &vals { + bitpacker.write(val, num_bits, &mut buffer).unwrap(); + } + bitpacker.close(&mut buffer).unwrap(); + let bitunpacker = BitUnpacker::new(num_bits); + for i in 0..len - 1 { + assert_eq!( + bitunpacker.get_pair(i as u32, &buffer), + (vals[i], vals[i + 1]), + "mismatch for num_bits={num_bits}, len={len}, i={i}" + ); + } + } + } + } } diff --git a/columnar/benches/bench_plain_block.rs b/columnar/benches/bench_plain_block.rs index ef495f76e..1f167c94b 100644 --- a/columnar/benches/bench_plain_block.rs +++ b/columnar/benches/bench_plain_block.rs @@ -133,14 +133,11 @@ fn main() { // Divide by `num_values` to get the cost of reading one value. group.register("read_all_values", |input| { - let mut codes_buffer: Vec = Vec::new(); let mut value: Vec = Vec::new(); let mut total_len = 0; for slot in 0..input.num_values { value.clear(); - input - .open_block - .append_value(slot, &mut codes_buffer, &mut value); + input.open_block.append_value(slot, &mut value); total_len += value.len(); } black_box(total_len); @@ -149,9 +146,8 @@ fn main() { // A point lookup: open the block, then read one value. group.register("open_and_read_one_value", |input| { let block = PlainBlock::open(input.block_bytes.clone(), input.num_values); - let mut codes_buffer: Vec = Vec::new(); let mut value: Vec = Vec::new(); - block.append_value(input.num_values / 2, &mut codes_buffer, &mut value); + block.append_value(input.num_values / 2, &mut value); black_box(value); }); diff --git a/columnar/src/column/plain/block/mod.rs b/columnar/src/column/plain/block/mod.rs index 0b2bc1c2d..c81ed13c4 100644 --- a/columnar/src/column/plain/block/mod.rs +++ b/columnar/src/column/plain/block/mod.rs @@ -7,19 +7,16 @@ //! - `BLOCK_KIND_RAW`: values stored as is, see `raw_block`. //! - `BLOCK_KIND_ONPAIR16`: values compressed with OnPair16, see `onpair16_block`. +mod offsets; mod onpair16_block; mod raw_block; use std::io; -use std::num::NonZeroU64; use common::OwnedBytes; use self::onpair16_block::{OnPair16Block, encode_onpair16_block}; use self::raw_block::{RAW_HEADER_NUM_BYTES, RawBlock, encode_raw_block}; -use crate::column_values::{ - BlockwiseLinearCodec, BlockwiseLinearReader, ColumnCodec, ColumnStats, ColumnValues, -}; /// Kind of a block storing its values as is. const BLOCK_KIND_RAW: u8 = 0; @@ -52,43 +49,6 @@ fn read_u32(bytes: &mut &[u8]) -> u32 { u32::from_le_bytes(*u32_bytes) } -/// Serializes block offsets directly with `BlockwiseLinearCodec` (no 1-byte codec tag, no -/// estimation pass, and no stats pass). -/// -/// Precondition: `offsets` is sorted in increasing order, which holds for value offsets. -/// -/// Format evolution is handled by the block's leading kind byte and the plain column footer's -/// format version. -pub(super) fn serialize_offsets(sorted_offsets: &[u32], output: &mut Vec) -> io::Result<()> { - debug_assert!(sorted_offsets.is_sorted()); - let min_value: u32 = sorted_offsets.first().copied().unwrap_or(0); - let max_value: u32 = sorted_offsets.last().copied().unwrap_or(0); - let stats = ColumnStats { - gcd: NonZeroU64::MIN, - min_value: min_value as u64, - max_value: max_value as u64, - num_rows: sorted_offsets.len() as u32, - }; - BlockwiseLinearCodec::serialize( - &stats, - sorted_offsets.iter().map(|&offset| offset as u64), - output, - ) -} - -/// Loads `BlockwiseLinearReader` offsets with `expected_num_vals` values. -/// -/// Panics if `bytes` is corrupted. -pub(super) fn load_offsets(bytes: OwnedBytes, expected_num_vals: u32) -> BlockwiseLinearReader { - let offsets = BlockwiseLinearCodec::load(bytes).expect("corrupted offsets in plain block"); - assert_eq!( - offsets.num_vals(), - expected_num_vals, - "unexpected number of offsets in plain block" - ); - offsets -} - /// Encodes the values of a block into `output`. /// /// `bytes` holds the `n` values of the block, concatenated. `offsets` has `n + 1` entries, with @@ -148,20 +108,17 @@ impl PlainBlock { /// Appends the bytes of the value at position `slot` in the block to `output`. /// /// Output is NOT cleared beforehand. - /// - /// `codes_buffer` is scratch space to contain the token codes. - pub fn append_value(&self, slot: u32, codes_buffer: &mut Vec, output: &mut Vec) { + #[inline] + pub fn append_value(&self, slot: u32, output: &mut Vec) { match self { - PlainBlock::OnPair16(onpair16_block) => { - onpair16_block.append_value(slot, codes_buffer, output) - } + PlainBlock::OnPair16(onpair16_block) => onpair16_block.append_value(slot, output), PlainBlock::Raw(raw_block) => raw_block.append_value(slot, output), } } // TODO add a batched version - // pub(crate) fn append_value_batch(&self, slots: &[u32], codes_buffer: &mut Vec, - // concatenated_output: &mut Vec, ouput_lens: &[u32]); + // pub(crate) fn append_value_batch(&self, slots: &[u32], concatenated_output: &mut Vec, + // ouput_lens: &[u32]); } #[cfg(test)] @@ -205,11 +162,10 @@ mod tests { fn decode_all(block_bytes: Vec, num_values: usize) -> Vec> { let block = PlainBlock::open(OwnedBytes::new(block_bytes), num_values as u32); - let mut codes_buffer = Vec::new(); (0..num_values as u32) .map(|slot| { let mut value = Vec::new(); - block.append_value(slot, &mut codes_buffer, &mut value); + block.append_value(slot, &mut value); value }) .collect() diff --git a/columnar/src/column/plain/block/offsets.rs b/columnar/src/column/plain/block/offsets.rs new file mode 100644 index 000000000..bc4233675 --- /dev/null +++ b/columnar/src/column/plain/block/offsets.rs @@ -0,0 +1,267 @@ +//! Two-level bitpacked offset codec for plain blocks. +//! +//! Encodes a non-decreasing `u32` sequence `offsets[0..num_vals]` in two levels, with zero +//! allocation and O(1) work on open: +//! - Level 1 (`bases`): the first value of each `BLOCK_SIZE`-element block, +//! `bases[block_id] = offsets[block_id * BLOCK_SIZE]`, bitpacked on `base_bit_width` bits. +//! - Level 2 (`deltas`): within-block deltas for elements `1..BLOCK_SIZE` of each block +//! (omitting element `0`, whose delta is always `0`), bitpacked on `delta_bit_width` bits. +//! +//! ```text +//! offset size field +//! 0 4 num_vals (u32 LE) +//! 4 1 base_bit_width (0..=32) +//! 5 1 delta_bit_width (0..=32) +//! 6 ceil(num_blocks * base_bit_width / 8) bitpacked block bases +//! .. ceil(num_deltas * delta_bit_width / 8) bitpacked within-block deltas +//! ``` +//! +//! `num_blocks = num_vals.div_ceil(BLOCK_SIZE)` and `num_deltas = num_vals - num_blocks`. + +use tantivy_bitpacker::{BitPacker, BitUnpacker, compute_num_bits}; + +use super::read_u32; + +const HEADER_NUM_BYTES: usize = 6; + +/// Number of offsets per Level 1 block (must be a power of 2). +/// +/// With element 0 omitted from Level 2, the cost per value is approximately +/// `base_bit_width / B + ((B - 1) / B) * log2((B - 1) * mean_step)`. Empirically across +/// `B in {4, 8, 16, 32}`, `B = 8` minimizes total offset size on both small (`apache_2k`) and +/// large (`varied_logs_1m`) plain blocks. +const BLOCK_SIZE: u32 = 8; + +/// Serializes `sorted_offsets` in two-level bitpacked format into `output`. +/// +/// Precondition: `sorted_offsets` is sorted in non-decreasing order. +pub(super) fn serialize_offsets(sorted_offsets: &[u32], output: &mut Vec) { + debug_assert!(sorted_offsets.is_sorted()); + let num_vals: u32 = sorted_offsets + .len() + .try_into() + .expect("too many offsets in plain block"); + let block_size = BLOCK_SIZE as usize; + + let max_base: u32 = sorted_offsets + .chunks(block_size) + .last() + .and_then(|chunk| chunk.first().copied()) + .unwrap_or(0); + let max_delta: u32 = sorted_offsets + .chunks(block_size) + .map(|chunk| chunk[chunk.len() - 1] - chunk[0]) + .max() + .unwrap_or(0); + + let base_bit_width: u8 = compute_num_bits(max_base as u64); + let delta_bit_width: u8 = compute_num_bits(max_delta as u64); + + output.extend_from_slice(&num_vals.to_le_bytes()); + output.push(base_bit_width); + output.push(delta_bit_width); + + if base_bit_width > 0 { + let mut base_packer = BitPacker::new(); + for chunk in sorted_offsets.chunks(block_size) { + base_packer + .write(chunk[0] as u64, base_bit_width, output) + .expect("writing to a Vec cannot fail"); + } + base_packer + .close(output) + .expect("writing to a Vec cannot fail"); + } + + if delta_bit_width > 0 { + let mut delta_packer = BitPacker::new(); + for chunk in sorted_offsets.chunks(block_size) { + let base = chunk[0]; + for &offset in &chunk[1..] { + let delta = offset - base; + delta_packer + .write(delta as u64, delta_bit_width, output) + .expect("writing to a Vec cannot fail"); + } + } + delta_packer + .close(output) + .expect("writing to a Vec cannot fail"); + } +} + +/// Zero-copy reader for two-level bitpacked offsets stored inside a plain block's byte buffer. +/// +/// Invariant, checked by `open`: `bases_start <= deltas_start <= end <= block_bytes.len()` for +/// the block buffer passed to `open`, and callers must pass that same slice to `get_pair`. +pub(super) struct BlockOffsets { + bases_start: usize, + deltas_start: usize, + end: usize, + base_unpacker: BitUnpacker, + delta_unpacker: BitUnpacker, + num_vals: u32, +} + +impl BlockOffsets { + /// Opens the offsets encoded in `block_bytes[start..start + len]` and validates that it + /// contains `expected_num_vals` entries. + /// + /// Precondition: `start + len <= block_bytes.len()`. + /// Panics if the header or byte length is corrupted, or if `num_vals != expected_num_vals`. + pub(super) fn open( + block_bytes: &[u8], + start: usize, + len: usize, + expected_num_vals: u32, + ) -> BlockOffsets { + let end = start + .checked_add(len) + .expect("offsets range overflow in plain block"); + assert!(end <= block_bytes.len(), "truncated offsets in plain block"); + let slice = &block_bytes[start..end]; + assert!( + slice.len() >= HEADER_NUM_BYTES, + "corrupted offsets in plain block" + ); + let mut header = &slice[..HEADER_NUM_BYTES]; + let num_vals = read_u32(&mut header); + let base_bit_width = header[0]; + let delta_bit_width = header[1]; + assert_eq!( + num_vals, expected_num_vals, + "unexpected number of offsets in plain block" + ); + assert!( + base_bit_width <= 32 && delta_bit_width <= 32, + "corrupted offsets bit width in plain block" + ); + + let num_blocks = num_vals.div_ceil(BLOCK_SIZE) as usize; + let num_deltas = num_vals as usize - num_blocks; + let bases_num_bytes = (num_blocks * base_bit_width as usize).div_ceil(8); + let deltas_num_bytes = (num_deltas * delta_bit_width as usize).div_ceil(8); + assert_eq!( + slice.len(), + HEADER_NUM_BYTES + bases_num_bytes + deltas_num_bytes, + "corrupted offsets in plain block" + ); + + let bases_start = start + HEADER_NUM_BYTES; + let deltas_start = bases_start + bases_num_bytes; + BlockOffsets { + bases_start, + deltas_start, + end, + base_unpacker: BitUnpacker::new(base_bit_width), + delta_unpacker: BitUnpacker::new(delta_bit_width), + num_vals, + } + } + + /// Returns `(offsets[idx], offsets[idx + 1])`. + /// + /// Precondition: `block_bytes` is the same buffer passed to `open`, and + /// `idx + 1 < num_vals`. + #[inline(always)] + pub(super) fn get_pair(&self, block_bytes: &[u8], idx: u32) -> (u32, u32) { + debug_assert!((idx as usize) + 1 < self.num_vals as usize); + debug_assert!(self.end <= block_bytes.len()); + // SAFETY: `open` validated `bases_start <= deltas_start <= end <= block_bytes.len()`. + let bases = unsafe { block_bytes.get_unchecked(self.bases_start..self.deltas_start) }; + let deltas = unsafe { block_bytes.get_unchecked(self.deltas_start..self.end) }; + let block_id = idx / BLOCK_SIZE; + let in_block = idx % BLOCK_SIZE; + if in_block == 0 { + let base = self.base_unpacker.get(block_id, bases) as u32; + let delta1 = self.delta_unpacker.get(idx - block_id, deltas) as u32; + (base, base.wrapping_add(delta1)) + } else if in_block + 1 < BLOCK_SIZE { + let base = self.base_unpacker.get(block_id, bases) as u32; + let (delta0, delta1) = self.delta_unpacker.get_pair(idx - block_id - 1, deltas); + ( + base.wrapping_add(delta0 as u32), + base.wrapping_add(delta1 as u32), + ) + } else { + let (base0, base1) = self.base_unpacker.get_pair(block_id, bases); + let delta0 = self.delta_unpacker.get(idx - block_id - 1, deltas) as u32; + // The first element of block `block_id + 1` has delta 0, so its value is `base1`. + ((base0 as u32).wrapping_add(delta0), base1 as u32) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip_and_check(offsets: &[u32]) { + let mut buf: Vec = vec![0xAA; 7]; + let start = buf.len(); + serialize_offsets(offsets, &mut buf); + let len = buf.len() - start; + buf.extend_from_slice(&[0xBB; 5]); + + let reader = BlockOffsets::open(&buf, start, len, offsets.len() as u32); + for i in 0..offsets.len().saturating_sub(1) { + assert_eq!( + reader.get_pair(&buf, i as u32), + (offsets[i], offsets[i + 1]), + "mismatch at idx {i} for len {}", + offsets.len() + ); + } + } + + #[test] + fn test_offsets_edge_cases() { + roundtrip_and_check(&[0]); + roundtrip_and_check(&[0, 0]); + roundtrip_and_check(&[0, 0, 0, 0, 0]); + roundtrip_and_check(&[0, 1]); + roundtrip_and_check(&[0, u32::MAX]); + roundtrip_and_check(&[0, 0, u32::MAX, u32::MAX]); + } + + #[test] + fn test_offsets_around_block_boundaries() { + for num_vals in [ + 1usize, + 2, + BLOCK_SIZE as usize - 1, + BLOCK_SIZE as usize, + BLOCK_SIZE as usize + 1, + BLOCK_SIZE as usize * 2 - 1, + BLOCK_SIZE as usize * 2, + BLOCK_SIZE as usize * 2 + 1, + 1_000, + ] { + let mut offsets: Vec = Vec::with_capacity(num_vals); + let mut acc: u32 = 0; + for i in 0..num_vals { + offsets.push(acc); + acc += ((i * 7) % 31) as u32; + } + roundtrip_and_check(&offsets); + } + } + + #[test] + #[should_panic(expected = "unexpected number of offsets")] + fn test_offsets_wrong_num_vals_panics() { + let offsets = [0u32, 3, 7, 12]; + let mut buf = Vec::new(); + serialize_offsets(&offsets, &mut buf); + BlockOffsets::open(&buf, 0, buf.len(), offsets.len() as u32 + 1); + } + + #[test] + #[should_panic(expected = "corrupted offsets")] + fn test_offsets_truncated_panics() { + let offsets: Vec = (0..100).map(|i| i * 5).collect(); + let mut buf = Vec::new(); + serialize_offsets(&offsets, &mut buf); + BlockOffsets::open(&buf, 0, buf.len() - 1, offsets.len() as u32); + } +} diff --git a/columnar/src/column/plain/block/onpair16_block.rs b/columnar/src/column/plain/block/onpair16_block.rs index f6acde680..ab009056d 100644 --- a/columnar/src/column/plain/block/onpair16_block.rs +++ b/columnar/src/column/plain/block/onpair16_block.rs @@ -1,7 +1,7 @@ //! Blocks compressed with OnPair16. //! -//! Each block has its own dictionary of at most 2^16 tokens of at most 16 bytes. A value is a -//! sequence of codes, each code being a token of the dictionary. +//! Each block has its own dictionary of at most 2^12 tokens (`MAX_CODE_BITS`) of at most 16 +//! bytes. A value is a sequence of codes, each code being a token of the dictionary. //! //! ```text //! offset size field @@ -21,17 +21,18 @@ //! `code_bits` is not stored: it is `ceil(log2(num_tokens))`, the minimal width of a token id. use std::mem::MaybeUninit; +use std::ops::Range; use common::OwnedBytes; -use onpair::{CompactDictionaryView, MaxDictBits, Threshold}; -use tantivy_bitpacker::{BitPacker, BitUnpacker}; +use onpair::{MaxDictBits, Threshold}; +use tantivy_bitpacker::BitPacker; -use super::{BLOCK_KIND_ONPAIR16, load_offsets, read_u16, read_u32, serialize_offsets}; -use crate::column_values::{BlockwiseLinearReader, ColumnValues}; +use super::offsets::{BlockOffsets, serialize_offsets}; +use super::{BLOCK_KIND_ONPAIR16, read_u16, read_u32}; const ONPAIR16_HEADER_NUM_BYTES: usize = 15; -/// Zero bytes appended after the codes, so that the bit unpacker can always do 8-byte loads. +/// Zero bytes appended after the codes, so that `load_codes` can always do 8-byte loads. const CODES_PADDING_NUM_BYTES: usize = 7; /// Minimum dictionary budget, in bits: the minimum accepted by onpair. @@ -43,8 +44,331 @@ const MIN_CODE_BITS: u8 = 9; /// dictionary when new tokens no longer pay off: it always fills the whole budget. A larger /// budget means wider codes and a larger dictionary to decode on every block open. We expect /// 12 bits to be enough for logs. +/// +/// The writer never exceeds it (see `max_dict_bits_for`), and the reader rejects blocks that do. const MAX_CODE_BITS: u8 = 12; +/// Maximum number of codes decoded in one chunk: `append_value` reserves +/// `DECODE_CHUNK_CODES * MAX_TOKEN_SIZE` = 4 KiB at a time, even for very large values. +const DECODE_CHUNK_CODES: usize = 256; + +/// Location of a token in the dictionary bytes. See `decode_dict_entries`. +/// +/// Layout contract: same size and alignment as a `u32`, `start` at byte offset 0 and `len` at +/// byte offset 2. The SIMD decoders rely on it: they store interleaved `(start, len)` `u16` lanes +/// directly into a `[DictEntry]`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(C, align(4))] +struct DictEntry { + /// Offset of the token in the dictionary bytes. + start: u16, + /// Length of the token, in `1..=MAX_TOKEN_SIZE`. + len: u16, +} + +const _: () = { + assert!(size_of::() == size_of::()); + assert!(align_of::() == align_of::()); + assert!(std::mem::offset_of!(DictEntry, start) == 0); + assert!(std::mem::offset_of!(DictEntry, len) == 2); +}; + +/// Decodes the 4-bit token lengths into one `DictEntry` per token. +/// +/// A token start fits on 16 bits: there are at most `2^MAX_CODE_BITS = 4096` tokens of at most 16 +/// bytes, so the last token starts at most at `4095 * 16 = 65_520`. +/// +/// Precondition: `1 <= num_tokens <= 2^MAX_CODE_BITS` and +/// `token_lens.len() == num_tokens.div_ceil(2)`. +fn decode_dict_entries(token_lens: &[u8], num_tokens: usize) -> Vec { + debug_assert!((1..=1 << MAX_CODE_BITS).contains(&num_tokens)); + debug_assert_eq!(token_lens.len(), num_tokens.div_ceil(2)); + let num_slots = token_lens.len() * 2; + let mut dict_entries: Vec = Vec::with_capacity(num_slots); + let spare = &mut dict_entries.spare_capacity_mut()[..num_slots]; + // SIMD for the first `8 * k` bytes, if available, then scalar for the rest. + let (num_simd_bytes, token_start) = decode_dict_entries_simd(token_lens, spare); + decode_dict_entries_scalar_uninit( + &token_lens[num_simd_bytes..], + &mut spare[num_simd_bytes * 2..], + token_start, + ); + // SAFETY: `decode_dict_entries_simd` initialized `spare[..num_simd_bytes * 2]` and + // `decode_dict_entries_scalar_uninit` initialized `spare[num_simd_bytes * 2..num_slots]`. + // Since `num_tokens <= num_slots`, the first `num_tokens` entries are initialized. + // If `num_tokens` is odd, the last high nibble is padding and is left out. + unsafe { + dict_entries.set_len(num_tokens); + } + dict_entries +} + +/// Decodes the entries of the tokens of `token_lens` (2 tokens per byte) into uninitialized +/// memory, the first token starting at `token_start`. +/// +/// Precondition: `dict_entries.len() == 2 * token_lens.len()`. +fn decode_dict_entries_scalar_uninit( + token_lens: &[u8], + dict_entries: &mut [MaybeUninit], + mut token_start: u32, +) { + debug_assert_eq!(dict_entries.len(), 2 * token_lens.len()); + let (entry_pairs, _) = dict_entries.as_chunks_mut::<2>(); + // Token 2k is in the low nibble. + // `token_start` is a `u32`: after the last pair of a 4096-token dictionary, it reaches 65_536. + // The stored starts are at most 65_520 (see `decode_dict_entries`), the dropped padding entry + // included, so the `as u16` casts are lossless. + for (&nibbles, entry_pair) in token_lens.iter().zip(entry_pairs) { + let low_len = (nibbles & 0x0F) as u32 + 1; + let high_len = (nibbles >> 4) as u32 + 1; + entry_pair[0].write(DictEntry { + start: token_start as u16, + len: low_len as u16, + }); + entry_pair[1].write(DictEntry { + start: (token_start + low_len) as u16, + len: high_len as u16, + }); + // One addition per pair of tokens on the dependency chain. + token_start += low_len + high_len; + } +} + +#[cfg(test)] +fn decode_dict_entries_scalar( + token_lens: &[u8], + dict_entries: &mut [DictEntry], + token_start: u32, +) { + // SAFETY: `MaybeUninit` has the same layout as `DictEntry`, and + // `decode_dict_entries_scalar_uninit` only writes initialized `DictEntry` values. + let uninit = unsafe { + std::slice::from_raw_parts_mut( + dict_entries.as_mut_ptr().cast::>(), + dict_entries.len(), + ) + }; + decode_dict_entries_scalar_uninit(token_lens, uninit, token_start); +} + +/// Decodes the entries of the tokens of the first `8 * k` bytes of `token_lens` (16 tokens per 8 +/// bytes) with SIMD, `k` being as large as possible. +/// +/// Returns the number of bytes of `token_lens` decoded, and the start of the next token. Returns +/// `(0, 0)` on targets without SIMD support. +/// +/// Precondition: `dict_entries.len() == 2 * token_lens.len()`. +fn decode_dict_entries_simd( + token_lens: &[u8], + dict_entries: &mut [MaybeUninit], +) -> (usize, u32) { + debug_assert_eq!(dict_entries.len(), 2 * token_lens.len()); + #[cfg(all(target_arch = "aarch64", target_endian = "little"))] + { + // SAFETY: NEON is always available on aarch64. + return unsafe { decode_dict_entries_neon(token_lens, dict_entries) }; + } + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + // SAFETY: SSE2 is enabled at compile time (`target_feature = "sse2"`). + return unsafe { decode_dict_entries_sse2(token_lens, dict_entries) }; + } + #[allow(unreachable_code)] + (0, 0) +} + +/// NEON version of `decode_dict_entries_simd`. +/// +/// Processes 16 bytes (32 tokens = two 16-token `u8` vectors) per iteration, then an optional +/// 8-byte (16-token) tail. +/// +/// Because each token length is in `1..=16`, the exclusive prefix sum of 16 tokens is at most +/// `15 * 16 = 240 <= 255`, so it is computed directly in `uint8x16_t` without overflow. The +/// running offset stays in a NEON `uint16x8_t` register to avoid SIMD-to-GPR transfers, with a +/// single vector add on the loop-carried dependency chain per 32 tokens. +/// +/// If all 4096 tokens have length 16, `running_start` wraps to `0` after the final chunk, which +/// is harmless because no scalar tail remains. +#[cfg(all(target_arch = "aarch64", target_endian = "little"))] +#[target_feature(enable = "neon")] +unsafe fn decode_dict_entries_neon( + token_lens: &[u8], + dict_entries: &mut [MaybeUninit], +) -> (usize, u32) { + use std::arch::aarch64::*; + + /// Exclusive prefix sum of 16 token lengths in `1..=16` (max lane value `15 * 16 = 240`). + #[inline(always)] + unsafe fn excl_prefix_sum_u8x16(lens: uint8x16_t, zeros_u8: uint8x16_t) -> uint8x16_t { + unsafe { + // Sliding 8-element inclusive sum (max `8 * 16 = 128`). + let sum = vaddq_u8(lens, vextq_u8::<15>(zeros_u8, lens)); + let sum = vaddq_u8(sum, vextq_u8::<14>(zeros_u8, sum)); + let sum = vaddq_u8(sum, vextq_u8::<12>(zeros_u8, sum)); + // Shift right by 1 to make it exclusive, then add lane `k - 8` (max `15 * 16 = 240`). + let shifted = vextq_u8::<15>(zeros_u8, sum); + vaddq_u8(shifted, vextq_u8::<8>(zeros_u8, shifted)) + } + } + + #[inline(always)] + unsafe fn store_group(dst: *mut u16, starts: uint16x8_t, group_lens: uint16x8_t) { + // Interleaved `(start, len)` `u16` pairs are `DictEntry`s in memory. + unsafe { + vst1q_u16(dst, vzip1q_u16(starts, group_lens)); + vst1q_u16(dst.add(8), vzip2q_u16(starts, group_lens)); + } + } + + let (len_chunks16, len_rem) = token_lens.as_chunks::<16>(); + let (entry_chunks32, entry_rem) = dict_entries.as_chunks_mut::<32>(); + // SAFETY: loads read within `len_chunks16` / `len_rem`, stores write within + // `entry_chunks32` / `entry_rem`. Storing `u16` lanes into `MaybeUninit` memory is + // valid: see `DictEntry`'s layout contract, and any bit pattern is a valid `u16`. + unsafe { + let mask_0f = vdupq_n_u8(0x0F); + let ones = vdupq_n_u8(1); + let zeros_u8 = vdupq_n_u8(0); + let mut running_start = vdupq_n_u16(0); + + for (len_chunk, entry_chunk) in len_chunks16.iter().zip(entry_chunks32.iter_mut()) { + let packed = vld1q_u8(len_chunk.as_ptr()); + let low = vandq_u8(packed, mask_0f); + let high = vshrq_n_u8::<4>(packed); + // Token 2k is in the low nibble: interleave low and high nibbles. + let lens_a = vaddq_u8(vzip1q_u8(low, high), ones); + let lens_b = vaddq_u8(vzip2q_u8(low, high), ones); + + // Exclusive prefix sums of 16 tokens each in `u8` (in parallel). + let excl_a = excl_prefix_sum_u8x16(lens_a, zeros_u8); + let excl_b = excl_prefix_sum_u8x16(lens_b, zeros_u8); + + let g0 = vmovl_u8(vget_low_u8(lens_a)); + let g1 = vmovl_high_u8(lens_a); + let g2 = vmovl_u8(vget_low_u8(lens_b)); + let g3 = vmovl_high_u8(lens_b); + + let excl0 = vmovl_u8(vget_low_u8(excl_a)); + let excl1 = vmovl_high_u8(excl_a); + let excl2 = vmovl_u8(vget_low_u8(excl_b)); + let excl3 = vmovl_high_u8(excl_b); + + // Lane 7 of `excl_hi + g_hi` is the total of all 16 tokens (at most 256). + let tot_a = vdupq_laneq_u16::<7>(vaddq_u16(excl1, g1)); + let tot_b = vdupq_laneq_u16::<7>(vaddq_u16(excl3, g3)); + let tot_ab = vaddq_u16(tot_a, tot_b); + + let base_a = running_start; + let base_b = vaddq_u16(running_start, tot_a); + running_start = vaddq_u16(running_start, tot_ab); + + let dst = entry_chunk.as_mut_ptr().cast::(); + store_group(dst, vaddq_u16(base_a, excl0), g0); + store_group(dst.add(16), vaddq_u16(base_a, excl1), g1); + store_group(dst.add(32), vaddq_u16(base_b, excl2), g2); + store_group(dst.add(48), vaddq_u16(base_b, excl3), g3); + } + + let mut num_decoded_bytes = len_chunks16.len() * 16; + if len_rem.len() >= 8 { + let packed = vld1_u8(len_rem.as_ptr()); + let low = vand_u8(packed, vget_low_u8(mask_0f)); + let high = vshr_n_u8::<4>(packed); + let nibbles = vzip_u8(low, high); + let lens_a = vaddq_u8(vcombine_u8(nibbles.0, nibbles.1), ones); + let excl_a = excl_prefix_sum_u8x16(lens_a, zeros_u8); + + let g0 = vmovl_u8(vget_low_u8(lens_a)); + let g1 = vmovl_high_u8(lens_a); + let excl0 = vmovl_u8(vget_low_u8(excl_a)); + let excl1 = vmovl_high_u8(excl_a); + + let tot_a = vdupq_laneq_u16::<7>(vaddq_u16(excl1, g1)); + let base_a = running_start; + running_start = vaddq_u16(running_start, tot_a); + + let dst = entry_rem.as_mut_ptr().cast::(); + store_group(dst, vaddq_u16(base_a, excl0), g0); + store_group(dst.add(16), vaddq_u16(base_a, excl1), g1); + num_decoded_bytes += 8; + } + + (num_decoded_bytes, vgetq_lane_u16::<0>(running_start) as u32) + } +} + +/// SSE2 version of `decode_dict_entries_simd`. See `decode_dict_entries_neon` for the lane widths +/// and why the 16-token exclusive prefix sum fits in `u8` without overflow. +#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] +#[target_feature(enable = "sse2")] +unsafe fn decode_dict_entries_sse2( + token_lens: &[u8], + dict_entries: &mut [MaybeUninit], +) -> (usize, u32) { + use std::arch::x86_64::*; + + /// Exclusive prefix sum of 16 token lengths in `1..=16` (max lane value `15 * 16 = 240`). + #[inline(always)] + unsafe fn excl_prefix_sum_epi8(lens: __m128i) -> __m128i { + unsafe { + let sum = _mm_add_epi8(lens, _mm_slli_si128::<1>(lens)); + let sum = _mm_add_epi8(sum, _mm_slli_si128::<2>(sum)); + let sum = _mm_add_epi8(sum, _mm_slli_si128::<4>(sum)); + let shifted = _mm_slli_si128::<1>(sum); + _mm_add_epi8(shifted, _mm_slli_si128::<8>(shifted)) + } + } + + #[inline(always)] + unsafe fn broadcast_lane7_epi16(vec: __m128i) -> __m128i { + unsafe { + let hi = _mm_shufflehi_epi16::<0xFF>(vec); + _mm_shuffle_epi32::<0xFF>(hi) + } + } + + let (len_chunks, _) = token_lens.as_chunks::<8>(); + let (entry_chunks, _) = dict_entries.as_chunks_mut::<16>(); + // SAFETY: loads read the 8 bytes of `len_chunk`, stores write within the 16 entries of + // `entry_chunk`. Storing `u16` lanes into `MaybeUninit` memory is valid: see its + // layout contract, and any bit pattern is a valid `u16`. + unsafe { + let mask_0f = _mm_set1_epi8(0x0F); + let ones = _mm_set1_epi8(1); + let zeros = _mm_setzero_si128(); + let mut running_start = zeros; + for (len_chunk, entry_chunk) in len_chunks.iter().zip(entry_chunks.iter_mut()) { + let packed = _mm_loadl_epi64(len_chunk.as_ptr().cast::<__m128i>()); + // Token 2k is in the low nibble: interleave low and high nibbles. + let low_nibbles = _mm_and_si128(packed, mask_0f); + let high_nibbles = _mm_and_si128(_mm_srli_epi16::<4>(packed), mask_0f); + let lens = _mm_add_epi8(_mm_unpacklo_epi8(low_nibbles, high_nibbles), ones); + let excl = excl_prefix_sum_epi8(lens); + + let g0 = _mm_unpacklo_epi8(lens, zeros); + let g1 = _mm_unpackhi_epi8(lens, zeros); + let excl0 = _mm_unpacklo_epi8(excl, zeros); + let excl1 = _mm_unpackhi_epi8(excl, zeros); + + let starts0 = _mm_add_epi16(running_start, excl0); + let starts1 = _mm_add_epi16(running_start, excl1); + let tot = broadcast_lane7_epi16(_mm_add_epi16(excl1, g1)); + running_start = _mm_add_epi16(running_start, tot); + + // Interleaved `(start, len)` `u16` pairs are `DictEntry`s in memory. + let dst = entry_chunk.as_mut_ptr().cast::<__m128i>(); + _mm_storeu_si128(dst, _mm_unpacklo_epi16(starts0, g0)); + _mm_storeu_si128(dst.add(1), _mm_unpackhi_epi16(starts0, g0)); + _mm_storeu_si128(dst.add(2), _mm_unpacklo_epi16(starts1, g1)); + _mm_storeu_si128(dst.add(3), _mm_unpackhi_epi16(starts1, g1)); + } + ( + len_chunks.len() * 8, + _mm_extract_epi16::<0>(running_start) as u16 as u32, + ) + } +} + /// Returns the OnPair dictionary budget (in bits) for a block of `num_bytes` raw bytes. /// /// This is called max_dict_bits to follow OnPair's naming, but could have been called @@ -80,8 +404,8 @@ pub(super) fn encode_onpair16_block(bytes: &[u8], offsets: &[u32], output: &mut let code_bits: u8 = dictionary.code_bits(); let dict_offsets: &[u32] = dictionary.offsets(); let dict_bytes: &[u8] = dictionary.bytes(); - // The header stores `num_tokens - 1` on a u16. - assert!((1..=16).contains(&code_bits)); + // The reader rejects blocks with more than `2^MAX_CODE_BITS` tokens. + assert!((1..=MAX_CODE_BITS).contains(&code_bits)); // Codes are token ids, smaller than `num_tokens`: they must fit on `code_bits` bits. assert!((1..=(1 << code_bits)).contains(&num_tokens)); @@ -105,7 +429,7 @@ pub(super) fn encode_onpair16_block(bytes: &[u8], offsets: &[u32], output: &mut output.extend_from_slice(dict_bytes); let code_offsets_start = output.len(); - serialize_offsets(&code_offsets, output).expect("writing to a Vec cannot fail"); + serialize_offsets(&code_offsets, output); let code_offsets_len = (output.len() - code_offsets_start) as u32; output[code_offsets_len_pos..code_offsets_len_pos + 4] .copy_from_slice(&code_offsets_len.to_le_bytes()); @@ -131,19 +455,87 @@ fn codes_num_bytes(num_codes: usize, code_bits: u8) -> usize { (num_codes * code_bits as usize).div_ceil(8) + CODES_PADDING_NUM_BYTES } +/// Reads the 64 bits of `codes` starting at bit offset `bit_pos`. +/// +/// # Safety +/// +/// `bit_pos / 8 + 8 <= codes.len()`. +#[inline(always)] +unsafe fn load_codes_at_bit(codes: &[u8], bit_pos: usize) -> u64 { + debug_assert!(bit_pos / 8 + 8 <= codes.len()); + let packed = unsafe { + codes + .as_ptr() + .add(bit_pos >> 3) + .cast::() + .read_unaligned() + }; + u64::from_le(packed) >> (bit_pos & 7) +} + +/// Reads the 64 bits of `codes` starting at code `code_pos`: code `code_pos` is in the low +/// `code_bits` bits, followed by the next codes. With `code_bits <= 12`, the next 3 codes are +/// complete too: 4 codes span at most `7 + 4 * 12 = 55` bits. +/// +/// # Safety +/// +/// `codes` was written by `write_codes` with `code_bits` bits per code, and +/// `code_pos < num_codes`. The 8 bytes read from the byte of code `code_pos` are then in +/// bounds, thanks to the `CODES_PADDING_NUM_BYTES` trailing bytes. +#[cfg(test)] +#[inline(always)] +unsafe fn load_codes(codes: &[u8], code_pos: usize, code_bits: usize) -> u64 { + unsafe { load_codes_at_bit(codes, code_pos * code_bits) } +} + +/// Copies the token of `dict_entry` to the start of `dst`, and returns the token length. +/// +/// Copies a whole `MAX_TOKEN_SIZE` block (onpair's over-copy): the bytes written after the +/// token length are garbage. +/// +/// # Safety +/// +/// `dict_entry.start + MAX_TOKEN_SIZE <= dict_bytes.len()` and `dst.len() >= MAX_TOKEN_SIZE`. +#[inline(always)] +unsafe fn copy_token( + dict_bytes: &[u8], + dict_entry: DictEntry, + dst: &mut [MaybeUninit], +) -> usize { + let token_start = dict_entry.start as usize; + debug_assert!(token_start + onpair::MAX_TOKEN_SIZE <= dict_bytes.len()); + debug_assert!(dst.len() >= onpair::MAX_TOKEN_SIZE); + // `[u8; MAX_TOKEN_SIZE]` has alignment 1, and `MaybeUninit` has the layout of `u8`. + unsafe { + let token = dict_bytes + .as_ptr() + .add(token_start) + .cast::<[u8; onpair::MAX_TOKEN_SIZE]>() + .read_unaligned(); + dst.as_mut_ptr() + .cast::<[u8; onpair::MAX_TOKEN_SIZE]>() + .write_unaligned(token); + } + dict_entry.len as usize +} + #[doc(hidden)] pub struct OnPair16Block { - /// Token bytes, read padding included. - dict_bytes: OwnedBytes, - /// `num_tokens + 1` offsets of the tokens in `dict_bytes`. + /// The block bytes. The dictionary bytes and the codes are read in place. + bytes: OwnedBytes, + /// Start of the dictionary bytes in `bytes`. + dict_bytes_start: usize, + /// Start of the codes in `bytes`. + codes_start: usize, + /// One entry per token, see `decode_dict_entries`. /// - /// Invariant: `(dict_bytes, dict_offsets)` passed `CompactDictionaryView::validate_safety`. - dict_offsets: Vec, + /// Invariant, checked by `open`: each token is readable for `MAX_TOKEN_SIZE` bytes in the + /// dictionary bytes (onpair's read padding). + dict_entries: Vec, /// `num_values + 1` offsets of the values in the code stream. - code_offsets: BlockwiseLinearReader, - code_unpacker: BitUnpacker, - /// Bitpacked codes, followed by `CODES_PADDING_NUM_BYTES` zero bytes. - codes: OwnedBytes, + code_offsets: BlockOffsets, + /// Width of a code, in `1..=MAX_CODE_BITS`. + code_bits: u8, num_codes: u32, } @@ -153,90 +545,188 @@ impl OnPair16Block { /// Precondition: the first byte of `bytes` is `BLOCK_KIND_ONPAIR16`. /// Panics if `bytes` is corrupted. pub(super) fn open(bytes: OwnedBytes, num_values: u32) -> OnPair16Block { - // `OwnedBytes::split` panics on a truncated (corrupted) block. - let (header, body) = bytes.split(ONPAIR16_HEADER_NUM_BYTES); + let block_bytes = bytes.as_slice(); + assert!( + block_bytes.len() >= ONPAIR16_HEADER_NUM_BYTES, + "truncated onpair16 block header" + ); // Skip the block kind, checked by `PlainBlock::open`. - let mut header: &[u8] = &header.as_slice()[1..]; + let mut header: &[u8] = &block_bytes[1..ONPAIR16_HEADER_NUM_BYTES]; let num_tokens: usize = read_u16(&mut header) as usize + 1; + assert!( + num_tokens <= 1 << MAX_CODE_BITS, + "too many tokens in plain block" + ); let dict_bytes_len = read_u32(&mut header) as usize; let code_offsets_len = read_u32(&mut header) as usize; let num_codes = read_u32(&mut header); debug_assert!(header.is_empty()); // The writer uses the minimal width of the token ids, computed by onpair. - let code_bits = onpair::code_bits_for_num_tokens(num_tokens); - let (token_lens, body) = body.split(num_tokens.div_ceil(2)); - let (dict_bytes, body) = body.split(dict_bytes_len); - let (code_offsets_bytes, codes) = body.split(code_offsets_len); + let code_bits: u8 = (usize::BITS - (num_tokens - 1).leading_zeros()).max(1) as u8; + debug_assert_eq!(code_bits, onpair::code_bits_for_num_tokens(num_tokens)); + + let dict_bytes_start = ONPAIR16_HEADER_NUM_BYTES + num_tokens.div_ceil(2); + let code_offsets_start = dict_bytes_start + dict_bytes_len; + let codes_start = code_offsets_start + code_offsets_len; + assert!(codes_start <= block_bytes.len(), "truncated plain block"); assert_eq!( - codes.len(), + block_bytes.len() - codes_start, codes_num_bytes(num_codes as usize, code_bits), "invalid codes length in plain block" ); - let mut dict_offsets: Vec = Vec::with_capacity(num_tokens + 1); - dict_offsets.push(0u32); - let mut dict_offset = 0u32; - for token_id in 0..num_tokens { - let nibbles = token_lens.as_slice()[token_id / 2]; - let token_len = ((nibbles >> (4 * (token_id % 2))) & 15u8) as u32 + 1; - dict_offset += token_len; - dict_offsets.push(dict_offset); - } - // Required by `dictionary_view`, which skips the checks. + + let dict_entries = decode_dict_entries( + &block_bytes[ONPAIR16_HEADER_NUM_BYTES..dict_bytes_start], + num_tokens, + ); + // Token starts are increasing: if the last token has its read padding, all tokens do. + let last_token_start = dict_entries[num_tokens - 1].start as usize; assert!( - CompactDictionaryView::validate_safety(dict_bytes.as_slice(), &dict_offsets).is_ok(), + last_token_start + onpair::MAX_TOKEN_SIZE <= dict_bytes_len, "invalid dictionary in plain block" ); - let code_offsets = load_offsets(code_offsets_bytes, num_values + 1); + + let code_offsets = BlockOffsets::open( + block_bytes, + code_offsets_start, + code_offsets_len, + num_values + 1, + ); OnPair16Block { - dict_bytes, - dict_offsets, + bytes, + dict_bytes_start, + codes_start, + dict_entries, code_offsets, - code_unpacker: BitUnpacker::new(code_bits), - codes, + code_bits, num_codes, } } - fn dictionary_view(&self) -> CompactDictionaryView<'_> { - // SAFETY: the buffers passed `validate_safety` in `open`, and they are never mutated. - unsafe { - CompactDictionaryView::new_unchecked(self.dict_bytes.as_slice(), &self.dict_offsets) - } - } - /// Appends the bytes of the value at position `slot` in the block to `output`. - /// - /// `codes_buffer` is scratch space. - pub(super) fn append_value( - &self, - slot: u32, - codes_buffer: &mut Vec, - output: &mut Vec, - ) { - let (code_start, code_end) = self.code_offsets.get_pair(slot); - let code_start = code_start as u32; - let code_end = code_end as u32; + pub(super) fn append_value(&self, slot: u32, output: &mut Vec) { + let (code_start, code_end) = self.code_offsets.get_pair(self.bytes.as_slice(), slot); assert!( code_start <= code_end && code_end <= self.num_codes, "invalid code offsets in plain block" ); - codes_buffer.clear(); - let codes_data = self.codes.as_slice(); - codes_buffer.reserve((code_end - code_start) as usize); - codes_buffer.extend( - (code_start..code_end) - .map(|code_pos| self.code_unpacker.get(code_pos, codes_data) as u16), - ); - let dictionary = self.dictionary_view(); - // Panics if a code is out of the dictionary range: corrupted data never causes UB. - let decoded_len = onpair::decoded_len(codes_buffer, dictionary); - output.reserve(decoded_len + onpair::DECODE_PADDING); - let spare_capacity: &mut [MaybeUninit] = output.spare_capacity_mut(); - // SAFETY: `spare_capacity` holds at least `decoded_len + DECODE_PADDING` bytes. - let num_written = unsafe { onpair::decode_into(codes_buffer, dictionary, spare_capacity) }; - debug_assert_eq!(num_written, decoded_len); - // SAFETY: `decode_into` initialized the first `num_written` bytes of the spare capacity. - unsafe { output.set_len(output.len() + num_written) }; + let code_start = code_start as usize; + let code_end = code_end as usize; + let num_value_codes = code_end - code_start; + if num_value_codes == 0 { + return; + } + if num_value_codes <= DECODE_CHUNK_CODES { + // Each token copy writes `MAX_TOKEN_SIZE` bytes, and advances the output by the token + // length, at most `MAX_TOKEN_SIZE`: the value writes at most this many bytes. + output.reserve(num_value_codes * onpair::MAX_TOKEN_SIZE); + // SAFETY: `code_start..code_end` is within `0..num_codes`, and the spare capacity of + // `output` has room for `MAX_TOKEN_SIZE` bytes per code. + let num_written = + unsafe { self.decode_codes(code_start..code_end, output.spare_capacity_mut()) }; + // SAFETY: `decode_codes` wrote the first `num_written` bytes of the spare capacity. + unsafe { output.set_len(output.len() + num_written) }; + } else { + self.append_value_chunked(code_start, code_end, output); + } + } + + #[cold] + #[inline(never)] + fn append_value_chunked(&self, mut code_pos: usize, code_end: usize, output: &mut Vec) { + while code_pos < code_end { + let chunk_end = (code_pos + DECODE_CHUNK_CODES).min(code_end); + // Each token copy writes `MAX_TOKEN_SIZE` bytes, and advances the output by the token + // length, at most `MAX_TOKEN_SIZE`: the chunk writes at most this many bytes. + output.reserve((chunk_end - code_pos) * onpair::MAX_TOKEN_SIZE); + // SAFETY: `code_pos..chunk_end` is within `0..num_codes`, and the spare capacity of + // `output` has room for `MAX_TOKEN_SIZE` bytes per code. + let num_written = + unsafe { self.decode_codes(code_pos..chunk_end, output.spare_capacity_mut()) }; + // SAFETY: `decode_codes` wrote the first `num_written` bytes of the spare capacity. + unsafe { output.set_len(output.len() + num_written) }; + code_pos = chunk_end; + } + } + + /// Decodes the codes at positions `code_range` to `dst`, and returns the number of bytes + /// written. + /// + /// Each token is copied as a whole `MAX_TOKEN_SIZE` block (onpair's over-copy): the bytes + /// written after the returned length are garbage. + /// + /// Panics if a code is out of the dictionary. + /// + /// # Safety + /// + /// `code_range.end <= self.num_codes`, and + /// `dst.len() >= code_range.len() * MAX_TOKEN_SIZE`. + #[inline(always)] + unsafe fn decode_codes(&self, code_range: Range, dst: &mut [MaybeUninit]) -> usize { + debug_assert!(dst.len() >= code_range.len() * onpair::MAX_TOKEN_SIZE); + let block_bytes = self.bytes.as_slice(); + // SAFETY: `open` checks `dict_bytes_start <= codes_start <= block_bytes.len()`. + // `dict_bytes` also covers the code offsets and the codes: `copy_token` reads within the + // dictionary bytes by the `dict_entries` invariant, and within this slice in any case. + let dict_bytes = unsafe { block_bytes.get_unchecked(self.dict_bytes_start..) }; + let codes = unsafe { block_bytes.get_unchecked(self.codes_start..) }; + let dict_entries: &[DictEntry] = &self.dict_entries; + let code_bits = self.code_bits as usize; + let code_mask = (1u64 << code_bits) - 1; + // SAFETY: `codes` was written by `write_codes` (length checked by `open`), and the + // caller guarantees `code_pos < code_range.end <= num_codes`. + let load_codes = |bit_pos: usize| -> u64 { unsafe { load_codes_at_bit(codes, bit_pos) } }; + // `copy_token` calls below. SAFETY: the entry comes from `dict_entries`, so its token has + // `MAX_TOKEN_SIZE` readable bytes in `dict_bytes` (invariant of `dict_entries`). Each + // call advances `num_written` by at most `MAX_TOKEN_SIZE`, and `dst` has room for + // `MAX_TOKEN_SIZE` bytes per code of `code_range`: before each call, + // `num_written + MAX_TOKEN_SIZE <= dst.len()`, so `dst[num_written..]` is in bounds and + // at least `MAX_TOKEN_SIZE` long. + let mut num_written = 0; + let mut code_pos = code_range.start; + let mut bit_pos = code_pos * code_bits; + let four_code_bits = 4 * code_bits; + // 4 codes per load: `code_bits <= 12`, so they span at most `7 + 4 * 12 = 55` bits. + while code_pos + 4 <= code_range.end { + let packed = load_codes(bit_pos); + let codes = [ + (packed & code_mask) as usize, + ((packed >> code_bits) & code_mask) as usize, + ((packed >> (2 * code_bits)) & code_mask) as usize, + ((packed >> (3 * code_bits)) & code_mask) as usize, + ]; + // One check for the 4 codes. It is the bounds check of the `get_unchecked` below. + assert!( + codes[0].max(codes[1]).max(codes[2].max(codes[3])) < dict_entries.len(), + "code index out of range in plain block" + ); + // SAFETY: checked just above. + let entries = codes.map(|code| unsafe { *dict_entries.get_unchecked(code) }); + for dict_entry in entries { + // SAFETY: see above. + num_written += unsafe { + copy_token(dict_bytes, dict_entry, dst.get_unchecked_mut(num_written..)) + }; + } + code_pos += 4; + bit_pos += four_code_bits; + } + // Remaining 1..=3 codes all fit in a single 64-bit load (`7 + 3 * 12 = 43 <= 64` bits). + if code_pos < code_range.end { + let mut packed = load_codes(bit_pos); + for _ in code_pos..code_range.end { + let code = (packed & code_mask) as usize; + packed >>= code_bits; + let dict_entry = *dict_entries + .get(code) + .expect("code index out of range in plain block"); + // SAFETY: see above. + num_written += unsafe { + copy_token(dict_bytes, dict_entry, dst.get_unchecked_mut(num_written..)) + }; + } + } + num_written } } @@ -263,10 +753,9 @@ mod tests { encode_onpair16_block(&bytes, &offsets, &mut block_bytes); assert_eq!(block_bytes[0], BLOCK_KIND_ONPAIR16); let onpair16_block = OnPair16Block::open(OwnedBytes::new(block_bytes), values.len() as u32); - let mut codes_buffer = Vec::new(); for (slot, expected_value) in values.iter().enumerate() { let mut value = Vec::new(); - onpair16_block.append_value(slot as u32, &mut codes_buffer, &mut value); + onpair16_block.append_value(slot as u32, &mut value); assert_eq!(&value, expected_value); } } @@ -296,24 +785,82 @@ mod tests { #[test] fn test_codes_roundtrip_all_code_bits() { - for code_bits in 1u8..=16 { - let max_code = (1u32 << code_bits) - 1; - let codes: Vec = (0..1_000u32) - .map(|i| (i.wrapping_mul(2_654_435_761) % (max_code + 1)) as u16) - .collect(); - let mut output = Vec::new(); - write_codes(&codes, code_bits, &mut output); - assert_eq!(output.len(), codes_num_bytes(codes.len(), code_bits)); - let bit_unpacker = BitUnpacker::new(code_bits); - for (code_pos, &code) in codes.iter().enumerate() { - assert_eq!(bit_unpacker.get(code_pos as u32, &output) as u16, code); - } - if code_bits == 16 { + // `write_codes` against `load_codes`, as used by `decode_codes`: one code per load, and + // 4 codes per load. Small code counts exercise the loads that reach into the padding. + for code_bits in 1u8..=MAX_CODE_BITS { + let code_mask = (1u64 << code_bits) - 1; + for num_codes in [1usize, 2, 3, 4, 5, 7, 8, 9, 1_000] { + let codes: Vec = (0..num_codes as u64) + .map(|i| (i.wrapping_mul(2_654_435_761) & code_mask) as u16) + .collect(); + let mut output = Vec::new(); + write_codes(&codes, code_bits, &mut output); + assert_eq!(output.len(), codes_num_bytes(num_codes, code_bits)); + let load = + |code_pos: usize| unsafe { load_codes(&output, code_pos, code_bits as usize) }; for (code_pos, &code) in codes.iter().enumerate() { - let code_bytes = [output[code_pos * 2], output[code_pos * 2 + 1]]; - assert_eq!(u16::from_le_bytes(code_bytes), code); + assert_eq!(load(code_pos) & code_mask, code as u64); + } + for code_pos in 0..num_codes.saturating_sub(3) { + let packed = load(code_pos); + for i in 0..4 { + let code = (packed >> (i * code_bits as usize)) & code_mask; + assert_eq!(code, codes[code_pos + i] as u64); + } } } } } + + #[test] + fn test_decode_dict_entries() { + for num_tokens in [1usize, 2, 7, 8, 9, 15, 16, 17, 127, 128, 3312, 4096] { + for all_max_len in [false, true] { + let mut token_lens = vec![0u8; num_tokens.div_ceil(2)]; + let mut expected_entries: Vec = Vec::with_capacity(num_tokens); + let mut offset: u32 = 0; + for token_id in 0..num_tokens { + let token_len: u32 = if all_max_len { + 16 + } else { + (token_id % 16) as u32 + 1 + }; + token_lens[token_id / 2] |= ((token_len - 1) as u8) << (4 * (token_id % 2)); + expected_entries.push(DictEntry { + start: offset as u16, + len: token_len as u16, + }); + offset += token_len; + } + // SIMD (if available) then scalar. + assert_eq!( + decode_dict_entries(&token_lens, num_tokens), + expected_entries + ); + // Scalar only. + let mut scalar_entries = vec![DictEntry::default(); token_lens.len() * 2]; + decode_dict_entries_scalar(&token_lens, &mut scalar_entries, 0); + scalar_entries.truncate(num_tokens); + assert_eq!(scalar_entries, expected_entries); + } + } + } + + #[test] + fn test_onpair16_block_large_value_chunked_decode() { + // Exercises values whose code count exceeds `DECODE_CHUNK_CODES` (256). + let long_value: Vec = (0..10_000usize).map(|i| b'a' + (i % 26) as u8).collect(); + let mut values = log_lines(200); + values.push(long_value); + let value_refs: Vec<&[u8]> = values.iter().map(|value| value.as_slice()).collect(); + let (bytes, offsets) = concatenate_values(&value_refs); + let mut block_bytes = Vec::new(); + encode_onpair16_block(&bytes, &offsets, &mut block_bytes); + let block = OnPair16Block::open(OwnedBytes::new(block_bytes), values.len() as u32); + for (slot, expected_value) in values.iter().enumerate() { + let mut decoded = Vec::new(); + block.append_value(slot as u32, &mut decoded); + assert_eq!(&decoded, expected_value); + } + } } diff --git a/columnar/src/column/plain/block/raw_block.rs b/columnar/src/column/plain/block/raw_block.rs index d03762649..1dcfe4631 100644 --- a/columnar/src/column/plain/block/raw_block.rs +++ b/columnar/src/column/plain/block/raw_block.rs @@ -14,8 +14,8 @@ use std::io; use common::OwnedBytes; -use super::{BLOCK_KIND_RAW, load_offsets, read_u32, serialize_offsets}; -use crate::column_values::{BlockwiseLinearReader, ColumnValues}; +use super::offsets::{BlockOffsets, serialize_offsets}; +use super::{BLOCK_KIND_RAW, read_u32}; pub(super) const RAW_HEADER_NUM_BYTES: usize = 5; @@ -32,7 +32,7 @@ pub(super) fn encode_raw_block( let offsets_len_pos = output.len(); output.extend_from_slice(&0u32.to_le_bytes()); let offsets_start = output.len(); - serialize_offsets(offsets, output)?; + serialize_offsets(offsets, output); let offsets_len = (output.len() - offsets_start) as u32; output[offsets_len_pos..offsets_len_pos + 4].copy_from_slice(&offsets_len.to_le_bytes()); output.extend_from_slice(bytes); @@ -42,7 +42,7 @@ pub(super) fn encode_raw_block( #[doc(hidden)] pub struct RawBlock { /// `num_values + 1` offsets of the values in `bytes[values_start..]`. - byte_offsets: BlockwiseLinearReader, + byte_offsets: BlockOffsets, bytes: OwnedBytes, values_start: usize, } @@ -63,8 +63,8 @@ impl RawBlock { .checked_add(offsets_len) .expect("raw block offsets length overflow"); assert!(values_start <= slice.len(), "truncated raw block"); - let offsets_bytes = bytes.slice(RAW_HEADER_NUM_BYTES..values_start); - let byte_offsets = load_offsets(offsets_bytes, num_values + 1); + let byte_offsets = + BlockOffsets::open(slice, RAW_HEADER_NUM_BYTES, offsets_len, num_values + 1); RawBlock { byte_offsets, bytes, @@ -74,8 +74,9 @@ impl RawBlock { /// Appends the bytes of the value at position `slot` in the block to `output`. pub(super) fn append_value(&self, slot: u32, output: &mut Vec) { - let (start, end) = self.byte_offsets.get_pair(slot); - let value_bytes = &self.bytes.as_slice()[self.values_start..]; + let block_bytes = self.bytes.as_slice(); + let (start, end) = self.byte_offsets.get_pair(block_bytes, slot); + let value_bytes = &block_bytes[self.values_start..]; let start = start as usize; let end = end as usize; assert!( diff --git a/columnar/src/column/plain/mod.rs b/columnar/src/column/plain/mod.rs index 2382bdf2a..9fd679f38 100644 --- a/columnar/src/column/plain/mod.rs +++ b/columnar/src/column/plain/mod.rs @@ -183,7 +183,6 @@ impl PlainBytesColumn { PlainValueReader { column: self.clone(), current_block: None, - codes_buffer: Vec::new(), value_buffer: Vec::new(), } } @@ -246,7 +245,6 @@ pub struct PlainValueReader { column: PlainBytesColumn, /// The id of the last block read, and the block. current_block: Option<(u32, PlainBlock)>, - codes_buffer: Vec, value_buffer: Vec, } @@ -306,7 +304,7 @@ impl PlainValueReader { .expect("load_block_for_value sets the current block"); let block_index = &self.column.inner.block_index; let slot = value_idx - block_index.value_range(*current_block_id).start; - current_block.append_value(slot, &mut self.codes_buffer, output); + current_block.append_value(slot, output); Ok(()) } diff --git a/columnar/src/column_values/mod.rs b/columnar/src/column_values/mod.rs index 13a2a4c58..a909af6ee 100644 --- a/columnar/src/column_values/mod.rs +++ b/columnar/src/column_values/mod.rs @@ -30,8 +30,6 @@ pub use u64_based::{ ALL_U64_CODEC_TYPES, CodecType, load_u64_based_column_values, serialize_and_load_u64_based_column_values, serialize_u64_based_column_values, }; -#[cfg(feature = "plain_codec")] -pub(crate) use u64_based::{BlockwiseLinearCodec, BlockwiseLinearReader, ColumnCodec}; pub use u128_based::{ CompactHit, CompactSpaceU64Accessor, open_u128_as_compact_u64, open_u128_mapped, serialize_column_values_u128, diff --git a/columnar/src/column_values/u64_based/blockwise_linear.rs b/columnar/src/column_values/u64_based/blockwise_linear.rs index d3c18ab5d..ae55082c1 100644 --- a/columnar/src/column_values/u64_based/blockwise_linear.rs +++ b/columnar/src/column_values/u64_based/blockwise_linear.rs @@ -193,19 +193,22 @@ impl ColumnCodec for BlockwiseLinearCodec { let footer_len: u32 = (&bytes[bytes.len() - 4..]).deserialize()?; let footer_offset = bytes.len() - 4 - footer_len as usize; let num_blocks = compute_num_blocks(stats.num_rows) as usize; - let mut blocks: Vec = Vec::with_capacity(num_blocks); + let mut blocks = Arc::<[Block]>::new_uninit_slice(num_blocks); let mut start_offset = 0; { let mut footer: &[u8] = &bytes.as_slice()[footer_offset..bytes.len() - 4]; - for _ in 0..num_blocks { + let blocks_slice = Arc::get_mut(&mut blocks).unwrap(); + for block_slot in blocks_slice.iter_mut() { let mut block = Block::deserialize(&mut footer)?; block.data_start_offset = start_offset; start_offset += (block.bit_unpacker.bit_width() as usize) * BLOCK_SIZE as usize / 8; - blocks.push(block); + block_slot.write(block); } } + // SAFETY: every element of `blocks` was initialized in the loop above. + let blocks = unsafe { blocks.assume_init() }; Ok(BlockwiseLinearReader { - blocks: blocks.into(), + blocks, data: bytes, stats, }) diff --git a/columnar/src/column_values/u64_based/mod.rs b/columnar/src/column_values/u64_based/mod.rs index 6ba09d2da..313cd2251 100644 --- a/columnar/src/column_values/u64_based/mod.rs +++ b/columnar/src/column_values/u64_based/mod.rs @@ -15,8 +15,6 @@ use crate::column_values::monotonic_mapping::{ }; pub use crate::column_values::u64_based::bitpacked::BitpackedCodec; pub use crate::column_values::u64_based::blockwise_linear::BlockwiseLinearCodec; -#[cfg(feature = "plain_codec")] -pub(crate) use crate::column_values::u64_based::blockwise_linear::BlockwiseLinearReader; pub use crate::column_values::u64_based::linear::LinearCodec; pub use crate::column_values::u64_based::stats_collector::StatsCollector; use crate::column_values::{ColumnStats, monotonic_map_column};