use relate_core::RelId;
use super::bitpack::{bit_width, unzigzag, zigzag, BitReader, BitWriter};
use super::Hop;
pub(crate) const TS_BLOCK: usize = 128;
pub(crate) const ID_BLOCK: usize = 64;
pub(crate) trait WidthReader {
fn take(&mut self, rest: &[u8]) -> (u32, usize);
}
pub(crate) trait WidthWriter {
fn put(&mut self, width: u32, packed: &[u8], out: &mut Vec<u8>);
}
struct Inline;
impl WidthReader for Inline {
fn take(&mut self, rest: &[u8]) -> (u32, usize) {
(rest[0] as u32, 1)
}
}
impl WidthWriter for Inline {
fn put(&mut self, width: u32, packed: &[u8], out: &mut Vec<u8>) {
out.push(width as u8);
out.extend_from_slice(packed);
}
}
pub(crate) fn encode_chunk(hops: &[Hop]) -> Vec<u8> {
let mut out = Vec::new();
encode_stream(hops, &mut out, &mut Inline);
out
}
pub(crate) fn encode_stream(hops: &[Hop], out: &mut Vec<u8>, widths: &mut impl WidthWriter) {
let mut bitmap = vec![0u8; hops.len().div_ceil(8)];
for (i, hop) in hops.iter().enumerate() {
if hop.ts.is_some() {
bitmap[i / 8] |= 1 << (i % 8);
}
}
out.extend_from_slice(&bitmap);
let present: Vec<i64> = hops.iter().filter_map(|h| h.ts).collect();
if let Some((&first, rest)) = present.split_first() {
out.extend_from_slice(&first.to_le_bytes());
let mut gaps = Vec::with_capacity(rest.len());
let mut prev = first;
for &ts in rest {
gaps.push(prev.wrapping_sub(ts) as u64);
prev = ts;
}
for block in gaps.chunks(TS_BLOCK) {
let width = bit_width(
block
.iter()
.copied()
.max()
.expect("chunks() yields non-empty blocks"),
);
let mut w = BitWriter::new();
for &gap in block {
w.write(gap, width);
}
widths.put(width, &w.finish(), out);
}
}
if let Some((&head, tail)) = hops.split_first() {
out.extend_from_slice(&(head.id as u64).to_le_bytes());
let mut deltas = Vec::with_capacity(tail.len());
let mut prev = head.id;
for hop in tail {
deltas.push(zigzag(hop.id.wrapping_sub(prev)));
prev = hop.id;
}
for block in deltas.chunks(ID_BLOCK) {
let width = bit_width(
block
.iter()
.copied()
.max()
.expect("chunks() yields non-empty blocks"),
);
let mut w = BitWriter::new();
for &delta in block {
w.write(delta, width);
}
widths.put(width, &w.finish(), out);
}
}
}
pub(crate) fn stream_len(bytes: &[u8], n: usize) -> usize {
stream_len_with(bytes, n, &mut Inline)
}
pub(crate) fn stream_len_with(bytes: &[u8], n: usize, widths: &mut impl WidthReader) -> usize {
let bitmap_len = n.div_ceil(8);
let present: usize = bytes[..bitmap_len]
.iter()
.map(|b| b.count_ones() as usize)
.sum();
let mut rest = &bytes[bitmap_len..];
let mut consumed = bitmap_len;
if present > 0 {
consumed += 8;
rest = &rest[8..];
consumed += walk_section(&mut rest, present - 1, TS_BLOCK, widths, |_, _, _| {});
}
if n > 0 {
consumed += 8;
rest = &rest[8..];
consumed += walk_section(&mut rest, n - 1, ID_BLOCK, widths, |_, _, _| {});
}
consumed
}
fn walk_section<'a>(
rest: &mut &'a [u8],
count: usize,
block: usize,
widths: &mut impl WidthReader,
mut visit: impl FnMut(u32, &'a [u8], usize),
) -> usize {
let mut consumed = 0;
let mut remaining = count;
while remaining > 0 {
let take = remaining.min(block);
let (width, skip) = widths.take(rest);
let packed_len = (take * width as usize).div_ceil(8);
visit(width, &rest[skip..skip + packed_len], take);
consumed += skip + packed_len;
*rest = &rest[skip + packed_len..];
remaining -= take;
}
consumed
}
pub(crate) fn decode_chunk(bytes: &[u8], n: usize) -> Vec<Hop> {
decode_stream(bytes, n, &mut Inline)
}
pub(crate) fn decode_stream(bytes: &[u8], n: usize, widths: &mut impl WidthReader) -> Vec<Hop> {
let bitmap_len = n.div_ceil(8);
let (bitmap, mut rest) = bytes.split_at(bitmap_len);
let present = bitmap.iter().map(|b| b.count_ones() as usize).sum();
let mut tss: Vec<i64> = Vec::with_capacity(present);
if present > 0 {
let (raw, tail) = rest.split_at(8);
rest = tail;
let mut prev = i64::from_le_bytes(raw.try_into().expect("codec: ts head"));
tss.push(prev);
walk_section(
&mut rest,
present - 1,
TS_BLOCK,
widths,
|width, packed, take| {
let mut r = BitReader::new(packed);
for _ in 0..take {
prev = prev.wrapping_sub(r.read(width) as i64);
tss.push(prev);
}
},
);
}
let mut ids: Vec<RelId> = Vec::with_capacity(n);
if n > 0 {
let (raw, tail) = rest.split_at(8);
rest = tail;
let mut prev = i64::from_le_bytes(raw.try_into().expect("codec: id head"));
ids.push(prev);
walk_section(&mut rest, n - 1, ID_BLOCK, widths, |width, packed, take| {
let mut r = BitReader::new(packed);
for _ in 0..take {
prev = prev.wrapping_add(unzigzag(r.read(width)));
ids.push(prev);
}
});
}
let mut next_ts = tss.into_iter();
ids.iter()
.enumerate()
.map(|(i, &id)| Hop {
ts: (bitmap[i / 8] & (1 << (i % 8)) != 0)
.then(|| next_ts.next().expect("codec: ts stream short")),
id,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn roundtrip(hops: &[Hop]) {
let bytes = encode_chunk(hops);
assert_eq!(decode_chunk(&bytes, hops.len()), hops);
assert_eq!(stream_len(&bytes, hops.len()), bytes.len());
}
#[test]
fn roundtrips_the_chunk_shapes_the_store_holds() {
roundtrip(&[]);
roundtrip(&[Hop { ts: None, id: 7 }]);
roundtrip(&[Hop {
ts: Some(42),
id: i64::MAX,
}]);
let mut ordered: Vec<Hop> = (0..300)
.map(|i| Hop {
ts: if i % 4 == 0 { None } else { Some(1000 - i) },
id: i,
})
.collect();
ordered.sort_unstable_by(crate::adjacency::cmp_ts_desc);
roundtrip(&ordered);
for n in [63usize, 64, 65, 127, 129] {
let hops: Vec<Hop> = (0..n as i64)
.map(|i| Hop {
ts: Some(i64::MAX - i),
id: i64::MIN + i,
})
.collect();
roundtrip(&hops);
}
}
}