use serde::{Serialize, de::DeserializeOwned};
use crate::error::{BlobError, Result};
pub const WIRE_VERSION: u16 = 2;
pub const ENC_MANIFEST: &str = "zblob/manifest;v=2";
pub const ENC_SLICE: &str = "zblob/bao4;v=2";
pub const ENC_INDEX: &str = "zblob/index;v=2";
pub const ENC_CHUNK: &str = "zblob/chunk";
pub const ENC_PUSH: &str = "zblob/push;v=2";
pub const ENC_AVAIL: &str = "zblob/have;v=2";
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Availability {
pub version: u16,
pub chunk_count: u32,
pub bits: Vec<u8>,
}
impl Availability {
pub fn full(chunk_count: u32) -> Self {
let mut bits = vec![0xffu8; chunk_count.div_ceil(8) as usize];
if let Some(last) = bits.last_mut()
&& !chunk_count.is_multiple_of(8)
{
*last = (1u8 << (chunk_count % 8)) - 1;
}
Availability {
version: WIRE_VERSION,
chunk_count,
bits,
}
}
pub fn is_set(&self, i: u32) -> bool {
i < self.chunk_count
&& (i / 8) < self.bits.len() as u32
&& self.bits[(i / 8) as usize] & (1 << (i % 8)) != 0
}
pub fn count(&self) -> u32 {
self.bits.iter().map(|b| b.count_ones()).sum()
}
}
pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> {
postcard::to_stdvec(value).map_err(BlobError::encode)
}
pub fn decode<T: DeserializeOwned>(data: &[u8]) -> Result<T> {
postcard::from_bytes(data).map_err(BlobError::encode)
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Sample {
version: u16,
a: u32,
b: String,
}
#[test]
fn postcard_roundtrip() {
let s = Sample {
version: 2,
a: 7,
b: "hi".into(),
};
let bytes = encode(&s).unwrap();
assert_eq!(decode::<Sample>(&bytes).unwrap(), s);
}
#[test]
fn truncated_input_rejected() {
let s = Sample {
version: 2,
a: 7,
b: "hello world".into(),
};
let bytes = encode(&s).unwrap();
assert!(decode::<Sample>(&bytes[..bytes.len() - 3]).is_err());
}
}