//! [STAR](https://dasl.ing/star.html), DASL's streaming archive:
//!
//! ```text
//! 2a 6c 01 00 | varint len | meta | ( 01 | varint len | key | varint len | value )* | 00
//! ```
//!
//! the writers are free functions over any [`Write`]. the header and the end byte can go in zstd
//! frames of their own.
use std::io::{self, BufRead, Write};
use ipld_core::ipld::Ipld;
use serde::Serialize;
pub const MAGIC: [u8; 4] = [0x2a, 0x6c, 0x01, 0x00];
pub const PAIR: u8 = 0x01;
pub const END: u8 = 0x00;
/// a varint holds 63 bits, 7 per byte
const VARINT_MAX_BYTES: u32 = 9;
const SHORT_KEY: usize = 64;
pub type Pair = (Vec, Vec);
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(io::Error),
#[error("not a STAR")]
Magic,
#[error("a STAR cut short")]
Truncated,
#[error("a varint {0}")]
Varint(&'static str),
#[error("a header {0}")]
Meta(String),
#[error("control byte {0:#04x}, neither a pair nor the end")]
Control(u8),
#[error("bytes after the end of a STAR")]
TrailingData,
}
impl From for Error {
fn from(e: io::Error) -> Self {
match e.kind() {
io::ErrorKind::UnexpectedEof => Self::Truncated,
_ => Self::Io(e),
}
}
}
/// refuses a `meta` that isn't a DRISL map with a text `$type`
pub fn write_header(out: &mut impl Write, meta: &impl Serialize) -> Result<(), Error> {
let meta = serde_ipld_dagcbor::to_vec(meta)
.map_err(|e| Error::Meta(format!("that can't be encoded: {e}")))?;
check_meta(&meta)?;
out.write_all(&MAGIC)?;
write_varint(out, meta.len() as u64)?;
out.write_all(&meta)?;
Ok(())
}
/// a short key goes out in one write with the control byte and both lengths, because a zstd writer
/// pays for every call
pub fn write_pair(out: &mut impl Write, key: &[u8], value: &[u8]) -> io::Result<()> {
if key.len() > SHORT_KEY {
out.write_all(&[PAIR])?;
write_varint(out, key.len() as u64)?;
out.write_all(key)?;
write_varint(out, value.len() as u64)?;
return out.write_all(value);
}
let mut head = [0; 1 + 2 * VARINT_MAX_BYTES as usize + SHORT_KEY];
head[0] = PAIR;
let mut at = 1;
at += put_varint(&mut head[at..], key.len() as u64);
head[at..at + key.len()].copy_from_slice(key);
at += key.len();
at += put_varint(&mut head[at..], value.len() as u64);
out.write_all(&head[..at])?;
out.write_all(value)
}
/// nothing may be written after it
pub fn write_end(out: &mut impl Write) -> io::Result<()> {
out.write_all(&[END])
}
fn write_varint(out: &mut impl Write, n: u64) -> io::Result<()> {
let mut buf = [0; VARINT_MAX_BYTES as usize];
let len = put_varint(&mut buf, n);
out.write_all(&buf[..len])
}
/// lengths are at most `isize::MAX`, which fits in the 63 bits a varint holds
fn put_varint(buf: &mut [u8], mut n: u64) -> usize {
let mut len = 0;
while n >= 0x80 {
buf[len] = n as u8 | 0x80;
n >>= 7;
len += 1;
}
buf[len] = n as u8;
len + 1
}
/// the first error ends it. pairs before the error come from an invalid archive.
/// collect them all first if you can't take them back
pub struct Reader {
inner: R,
meta: Vec,
/// the current pair, key then value
buf: Vec,
done: bool,
}
impl Reader {
pub fn new(mut inner: R) -> Result {
let mut magic = [0; 4];
inner.read_exact(&mut magic)?;
if magic != MAGIC {
return Err(Error::Magic);
}
let len = read_varint(&mut inner)?;
let mut meta = Vec::new();
read_into(&mut inner, &mut meta, len)?;
check_meta(&meta)?;
Ok(Self {
inner,
meta,
buf: Vec::new(),
done: false,
})
}
/// the header's DRISL bytes, already checked to be a map with a text `$type`
pub fn meta(&self) -> &[u8] {
&self.meta
}
// llvm stops inlining the read path once a program uses both this and the iterator, and short
// pairs then read twice as slow in `benches/star.rs`
#[inline(always)]
#[allow(clippy::type_complexity)]
pub fn next_pair(&mut self) -> Result