use std::collections::BTreeSet;
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PieceHash(pub [u8; 32]);
impl PieceHash {
pub fn of(bytes: &[u8]) -> PieceHash {
PieceHash(blake3::hash(bytes).into())
}
pub fn to_hex(self) -> String {
let mut s = String::with_capacity(64);
for b in self.0 {
s.push_str(&format!("{b:02x}"));
}
s
}
}
impl fmt::Debug for PieceHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "piece:{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3])
}
}
impl fmt::Display for PieceHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContentHash(pub [u8; 32]);
impl ContentHash {
pub fn of(bytes: &[u8]) -> ContentHash {
ContentHash(blake3::hash(bytes).into())
}
pub fn to_hex(self) -> String {
let mut s = String::with_capacity(64);
for b in self.0 {
s.push_str(&format!("{b:02x}"));
}
s
}
}
impl fmt::Debug for ContentHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "content:{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3])
}
}
impl fmt::Display for ContentHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
#[derive(Clone, Debug)]
pub enum AttrValue {
Str(String),
Int(i64),
Float(f64),
Bool(bool),
UInt(u64),
Bytes(Vec<u8>),
TimestampNs(i64),
Null,
}
impl PartialEq for AttrValue {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(AttrValue::Str(a), AttrValue::Str(b)) => a == b,
(AttrValue::Int(a), AttrValue::Int(b)) => a == b,
(AttrValue::Float(a), AttrValue::Float(b)) => a.to_bits() == b.to_bits(),
(AttrValue::Bool(a), AttrValue::Bool(b)) => a == b,
(AttrValue::UInt(a), AttrValue::UInt(b)) => a == b,
(AttrValue::Bytes(a), AttrValue::Bytes(b)) => a == b,
(AttrValue::TimestampNs(a), AttrValue::TimestampNs(b)) => a == b,
(AttrValue::Null, AttrValue::Null) => true,
_ => false,
}
}
}
impl Eq for AttrValue {}
impl AttrValue {
pub fn type_tag(&self) -> u8 {
match self {
AttrValue::Str(_) => 0,
AttrValue::Int(_) => 1,
AttrValue::Float(_) => 2,
AttrValue::Bool(_) => 3,
AttrValue::UInt(_) => 4,
AttrValue::Bytes(_) => 5,
AttrValue::TimestampNs(_) => 6,
AttrValue::Null => 7,
}
}
}
pub const BODY_CONTENT: &str = "body";
#[derive(Clone, Debug, PartialEq)]
pub enum ContentOp {
Lit(Vec<u8>),
Piece { hash: PieceHash, len: u32 },
}
impl ContentOp {
pub fn len(&self) -> u64 {
match self {
ContentOp::Lit(b) => b.len() as u64,
ContentOp::Piece { len, .. } => *len as u64,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub type BodyOp = ContentOp;
#[derive(Clone, Debug, PartialEq)]
pub struct Content {
pub name: String,
pub ops: Vec<ContentOp>,
pub identity: Option<ContentHash>,
}
impl Content {
pub fn new(name: impl Into<String>, ops: Vec<ContentOp>) -> Content {
Content { name: name.into(), ops, identity: None }
}
pub fn identified(
name: impl Into<String>,
ops: Vec<ContentOp>,
identity: ContentHash,
) -> Content {
Content { name: name.into(), ops, identity: Some(identity) }
}
pub fn len(&self) -> u64 {
self.ops.iter().map(ContentOp::len).sum()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Record {
pub id: String,
pub contents: Vec<Content>,
pub attrs: Vec<(String, AttrValue)>,
}
impl Record {
pub fn new(
id: impl Into<String>,
mut contents: Vec<Content>,
attrs: Vec<(String, AttrValue)>,
) -> anyhow::Result<Record> {
let id = id.into();
if id.is_empty() {
anyhow::bail!("record id must not be empty");
}
validate_contents(&contents)?;
contents.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
Ok(Record { id, contents, attrs })
}
pub fn content(&self, name: &str) -> Option<&Content> {
self.contents.iter().find(|c| c.name == name)
}
pub fn body(&self) -> Option<&[ContentOp]> {
self.content(BODY_CONTENT).map(|c| c.ops.as_slice())
}
pub fn content_len(&self, name: &str) -> Option<u64> {
self.content(name).map(Content::len)
}
pub fn body_len(&self) -> u64 {
self.content_len(BODY_CONTENT).unwrap_or(0)
}
}
pub fn validate_contents(contents: &[Content]) -> anyhow::Result<()> {
let mut names = BTreeSet::new();
for content in contents {
if content.name.is_empty() {
anyhow::bail!("content name must not be empty");
}
if !names.insert(content.name.as_str()) {
anyhow::bail!("duplicate content name {:?}", content.name);
}
}
Ok(())
}