crates/kleene-graph/src/slices/coder.rs
//! [`Found`] to bytes and back on kept buffers: the bytes of [`Found::to_bytes`] (the same
//! format), made with no copy of the whole set before compression and no compressor made per
//! piece. A worker of the device writes a piece's bytes straight from the set into its own
//! scratch and compresses them with its own kept compressor; the frames are joined once into
//! the output. Read back, each worker decompresses its pieces with its kept decompressor and
//! writes the vertices straight into the kept buffers of the [`Found`] it fills: no
//! [`NodeSet`] is built from a copy.
use std::ops::Range;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize};
use kleene_sparse::{CpuDevice, atomic_u32s, atomic_words};
use super::frame::{Compressor, Decompressor};
use super::{Found, LEVEL, NodeSet, PACK_FROM, PIECE, refuse};
/// One worker's kept buffers.
#[derive(Default)]
struct Worker {
compressor: Option<Compressor>,
decompressor: Decompressor,
/// A piece before compression.
raw: Vec<u8>,
/// Its pieces (compressed when encoding, decompressed when reading), one after another.
out: Vec<u8>,
/// Per piece it took: (piece, start in `out`, length).
index: Vec<(usize, usize, usize)>,
}
impl std::fmt::Debug for Worker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Worker")
.field("raw", &self.raw.capacity())
.field("out", &self.out.capacity())
.finish_non_exhaustive()
}
}
/// Kept buffers for [`Found::to_bytes_with`] and [`Found::read_into`]: per thread of the
/// device a compressor, a decompressor and scratch; once warm (the same sizes or smaller),
/// coding allocates nothing but the output bytes.
#[derive(Debug, Default)]
pub struct FoundCoder {
workers: Vec<Worker>,
/// Per piece: (worker, start, length).
places: Vec<(usize, usize, usize)>,
/// The other form's buffer of the last [`Found`] read into, kept for the next.
spare_words: Vec<u64>,
spare_list: Vec<u32>,
}
impl FoundCoder {
/// No buffers yet.
pub fn new() -> Self {
Self::default()
}
/// Workers for `pieces` pieces on `device`; how many take part.
fn ready(&mut self, device: &CpuDevice, pieces: usize) -> usize {
let n = device.threads().min(pieces).max(1);
if self.workers.len() < n {
self.workers.resize_with(n, Worker::default);
}
n
}
/// The pieces the workers took, in piece order (checked: each once).
fn order(&mut self, workers: usize, pieces: usize) -> bool {
self.places.clear();
self.places.resize(pieces, (usize::MAX, 0, 0));
for (t, w) in self.workers[..workers].iter().enumerate() {
for &(i, at, len) in &w.index {
self.places[i] = (t, at, len);
}
}
self.places.iter().all(|p| p.0 != usize::MAX)
}
}
/// The form byte and the header word of a set's bytes before compression.
fn head(set: &NodeSet) -> [u8; 5] {
let (form, head) = match set {
NodeSet::List(l) => (0u8, l.len() as u32),
NodeSet::Bits { first, .. } => (1, *first),
};
let h = head.to_le_bytes();
[form, h[0], h[1], h[2], h[3]]
}
/// Bytes `range` of `set`'s bytes before compression ([`NodeSet::encode_raw`]'s), appended
/// to `out`.
fn raw_into(set: &NodeSet, range: Range<usize>, out: &mut Vec<u8>) {
let h = head(set);
if range.start < 5 {
out.extend_from_slice(&h[range.start..range.end.min(5)]);
}
if range.end <= 5 {
return;
}
let (lo, hi) = (range.start.max(5) - 5, range.end - 5);
match set {
NodeSet::List(l) => {
let delta = |j: usize| {
let before = if j == 0 { 0 } else { l[j - 1] };
(l[j] - before).to_le_bytes()
};
elements(lo, hi, out, delta);
}
NodeSet::Bits { words, .. } => {
elements(lo, hi, out, |j| words[j].to_le_bytes());
}
}
}
/// Body bytes `lo..hi` of elements of `E` bytes each (element `j`'s bytes `bytes(j)`).
fn elements<const E: usize>(
lo: usize,
hi: usize,
out: &mut Vec<u8>,
bytes: impl Fn(usize) -> [u8; E],
) {
let (first, last) = (lo / E, (hi - 1) / E);
for j in first..=last {
let b = bytes(j);
let (s, t) = (j * E, j * E + E);
out.extend_from_slice(&b[lo.max(s) - s..hi.min(t) - s]);
}
}
impl Found {
/// [`Found::to_bytes`] (the same format) on the device's threads with `coder`'s kept
/// compressors and scratch: the set's bytes go straight from the set to the compressor,
/// piece by piece, and the frames once into the output.
pub fn to_bytes_with(&self, device: &CpuDevice, coder: &mut FoundCoder) -> Vec<u8> {
let raw_len = 5 + self.nodes.raw_bytes();
let pieces = raw_len.div_ceil(PIECE);
let mut frames = None;
if raw_len >= PACK_FROM {
let workers = coder.ready(device, pieces);
let (next, failed) = (AtomicUsize::new(0), AtomicBool::new(false));
device.each_block(&mut coder.workers[..workers], |_, w| {
w.out.clear();
w.index.clear();
loop {
let i = next.fetch_add(1, Relaxed);
if i >= pieces {
break;
}
w.raw.clear();
raw_into(
&self.nodes,
i * PIECE..((i + 1) * PIECE).min(raw_len),
&mut w.raw,
);
if w.compressor.is_none() {
w.compressor = Compressor::new(LEVEL).ok();
}
let at = w.out.len();
match w
.compressor
.as_mut()
.map(|c| c.compress_append(&w.raw, &mut w.out))
{
Some(Ok(len)) => w.index.push((i, at, len)),
_ => failed.store(true, Relaxed),
}
}
});
if !failed.load(Relaxed) && coder.order(workers, pieces) {
let total: usize = 4 + coder.places.iter().map(|p| 4 + p.2).sum::<usize>();
if total < raw_len {
frames = Some(total);
}
}
}
let mut out = Vec::with_capacity(25 + frames.unwrap_or(raw_len));
out.extend_from_slice(&self.examined.to_le_bytes());
out.extend_from_slice(&self.edges.to_le_bytes());
out.extend_from_slice(&(raw_len as u64).to_le_bytes());
match frames {
Some(_) => {
out.push(1);
out.extend_from_slice(&(pieces as u32).to_le_bytes());
for p in &coder.places {
out.extend_from_slice(&(p.2 as u32).to_le_bytes());
}
for &(t, at, len) in &coder.places {
out.extend_from_slice(&coder.workers[t].out[at..at + len]);
}
}
None => {
out.push(0);
raw_into(&self.nodes, 0..raw_len, &mut out);
}
}
out
}
/// [`Found::from_bytes`] into `into`, on the device's threads with `coder`'s kept
/// decompressors: each piece is decompressed into its worker's scratch and its vertices
/// written straight into `into`'s kept buffers (a list or a bit map, as sent).
pub fn read_into(
bytes: &[u8],
device: &CpuDevice,
coder: &mut FoundCoder,
into: &mut Found,
) -> crate::Result<()> {
let Some((examined, rest)) = bytes.split_first_chunk::<8>() else {
return refuse("a found set shorter than its header");
};
let Some((edges, rest)) = rest.split_first_chunk::<8>() else {
return refuse("a found set shorter than its header");
};
let Some((len, rest)) = rest.split_first_chunk::<8>() else {
return refuse("packed bytes shorter than their header");
};
let len = u64::from_le_bytes(*len) as usize;
into.examined = u64::from_le_bytes(*examined);
into.edges = u64::from_le_bytes(*edges);
if len < 5 {
return refuse("a node set body shorter than its header");
}
let pieces = len.div_ceil(PIECE);
match rest.split_first() {
Some((0, raw)) => {
if raw.len() != len {
return refuse("packed bytes of another length than their header says");
}
let h: [u8; 5] = raw[..5].try_into().expect("5 bytes");
fill(into, coder, h, len, device, |each| {
let next = AtomicUsize::new(0);
let workers = device.threads().min(pieces).max(1);
let mut seats = vec![(); workers];
device.each_block(&mut seats, |_, ()| {
loop {
let i = next.fetch_add(1, Relaxed);
if i >= pieces {
break;
}
let at = i * PIECE;
each(at, &raw[at..(at + PIECE).min(len)]);
}
});
})?;
}
Some((1, body)) => {
let Some((count, body)) = body.split_first_chunk::<4>() else {
return refuse("packed pieces without their count");
};
let count = u32::from_le_bytes(*count) as usize;
if count != pieces || body.len() < 4 * count {
return refuse("packed pieces of another count than their length says");
}
let (lens, mut frames) = body.split_at(4 * count);
// Each frame's place in the body (the lengths are read once, in order).
coder.places.clear();
let mut at = 0;
for l in lens.as_chunks::<4>().0 {
let l = u32::from_le_bytes(*l) as usize;
if frames.len() < l {
return refuse("packed pieces cut short");
}
coder.places.push((0, at, l));
at += l;
frames = &frames[l..];
}
let frames = &body[4 * count..4 * count + at];
let workers = coder.ready(device, pieces);
let (next, bad) = (AtomicUsize::new(0), AtomicBool::new(false));
let places = &coder.places;
device.each_block(&mut coder.workers[..workers], |_, w| {
w.out.clear();
w.index.clear();
loop {
let i = next.fetch_add(1, Relaxed);
if i >= pieces {
break;
}
let (_, f, l) = places[i];
let cap = PIECE.min(len - i * PIECE);
let at = w.out.len();
match w
.decompressor
.decompress_append(&frames[f..f + l], cap, &mut w.out)
{
Ok(n) if n == cap => w.index.push((i, at, n)),
_ => bad.store(true, Relaxed),
}
}
});
if bad.load(Relaxed) || !coder.order(workers, pieces) {
return refuse("a zstd frame or a packed piece of another length");
}
let (t, at, _) = coder.places[0];
let h: [u8; 5] = coder.workers[t].out[at..at + 5]
.try_into()
.expect("a first piece of 5 bytes or more");
let mut workers_out = std::mem::take(&mut coder.workers);
let result = fill(into, coder, h, len, device, |each| {
device.each_block(&mut workers_out[..workers], |_, w| {
for &(i, at, n) in &w.index {
each(i * PIECE, &w.out[at..at + n]);
}
});
});
coder.workers = workers_out;
result?;
}
_ => return refuse("packed bytes with an unknown flag"),
}
Ok(())
}
}
/// `into`'s set from bytes before compression of length `len` whose first five are `h`:
/// `pieces` calls its argument with each piece of those bytes (its place, its bytes) on the
/// device's threads; the elements whole inside a piece are stored, those cut by a piece's
/// edge are joined by OR.
fn fill(
into: &mut Found,
coder: &mut FoundCoder,
h: [u8; 5],
len: usize,
device: &CpuDevice,
pieces: impl FnOnce(&(dyn Fn(usize, &[u8]) + Sync)),
) -> crate::Result<()> {
let head = u32::from_le_bytes([h[1], h[2], h[3], h[4]]);
let body = len - 5;
// The other form's buffer goes back to the coder; this form's comes from `into` or it.
let old = std::mem::take(&mut into.nodes);
match old {
NodeSet::List(l) => coder.spare_list = l,
NodeSet::Bits { words, .. } => coder.spare_words = words,
}
match h[0] {
0 => {
if !body.is_multiple_of(4) || body / 4 != head as usize {
return refuse("a node list of another length than it says");
}
let mut list = std::mem::take(&mut coder.spare_list);
zeroed(&mut list, body / 4, device);
{
let out = atomic_u32s(&mut list);
pieces(&|at, bytes| join::<4>(at, bytes, |j, v, whole| put32(out, j, v, whole)));
}
// The differences summed into places, rising.
let mut at = 0u32;
for (i, d) in list.iter_mut().enumerate() {
if i > 0 && *d == 0 {
return refuse("a node list that does not rise");
}
at = at
.checked_add(*d)
.ok_or_else(|| crate::GraphError::Slices("a node past u32".into()))?;
*d = at;
}
into.nodes = NodeSet::List(list);
}
1 => {
if !body.is_multiple_of(8) {
return refuse("a bit map of a broken word");
}
if (u64::from(head) + (body / 8) as u64) * 64 > 1 << 32 {
return refuse("a bit map past u32");
}
let mut words = std::mem::take(&mut coder.spare_words);
zeroed(&mut words, body / 8, device);
{
let out = atomic_words(&mut words);
pieces(&|at, bytes| join::<8>(at, bytes, |j, v, whole| put64(out, j, v, whole)));
}
into.nodes = NodeSet::Bits { first: head, words };
}
_ => return refuse("a node set of an unknown form"),
}
Ok(())
}
/// `v` of `n` zero values, its buffer kept (set on the device's workers).
fn zeroed<T: Copy + Default + Send + Sync + Zero>(v: &mut Vec<T>, n: usize, device: &CpuDevice) {
let keep = v.len().min(n);
v.truncate(keep);
T::zero_on(&mut v[..], device);
v.resize(n, T::default());
}
/// Values zeroed on the device's workers.
trait Zero: Sized {
fn zero_on(v: &mut [Self], device: &CpuDevice);
}
impl Zero for u64 {
fn zero_on(v: &mut [u64], device: &CpuDevice) {
let a = atomic_words(v);
device.split(a.len(), |r| a[r].iter().for_each(|w| w.store(0, Relaxed)));
}
}
impl Zero for u32 {
fn zero_on(v: &mut [u32], device: &CpuDevice) {
let a = atomic_u32s(v);
device.split(a.len(), |r| a[r].iter().for_each(|w| w.store(0, Relaxed)));
}
}
/// The elements of `E` bytes (after the 5 header bytes) that bytes `at..at + bytes.len()`
/// hold: `put(j, value, whole)` per element `j`, `value` its bytes here in place (the
/// others zero), `whole` when all its bytes are here.
fn join<const E: usize>(at: usize, bytes: &[u8], put: impl Fn(usize, u64, bool)) {
let end = at + bytes.len();
let (lo, hi) = (at.max(5), end);
if hi <= lo {
return;
}
let (first, last) = ((lo - 5) / E, (hi - 5 - 1) / E);
for j in first..=last {
let (s, t) = (5 + j * E, 5 + j * E + E);
let (a, b) = (s.max(lo), t.min(hi));
let mut v = [0u8; 8];
v[a - s..b - s].copy_from_slice(&bytes[a - at..b - at]);
put(j, u64::from_le_bytes(v), a == s && b == t);
}
}
fn put64(out: &[AtomicU64], j: usize, v: u64, whole: bool) {
if whole {
out[j].store(v, Relaxed);
} else {
out[j].fetch_or(v, Relaxed);
}
}
fn put32(out: &[AtomicU32], j: usize, v: u64, whole: bool) {
if whole {
out[j].store(v as u32, Relaxed);
} else {
out[j].fetch_or(v as u32, Relaxed);
}
}