use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(feature = "dir")]
mod dir;
#[cfg(feature = "dir")]
mod files;
mod list;
mod memory;
mod reference;
#[cfg(feature = "dir")]
mod workspaces;
#[cfg(feature = "dir")]
pub use dir::DirBackend;
#[cfg(feature = "dir")]
pub use files::FilesBackend;
pub use list::PART_BYTES;
pub use memory::MemoryBackend;
pub use reference::{ContentRef, content_address, is_sealed, valid_reference};
pub use tilo_content_types::{
BLOB_SCHEME, ContentMeta, DocumentFormat, FACTS_SCAN_BYTES, ImageFormat, MediaFacts, RECORDING,
RECORDING_MAGIC, document_format, facts, has_facts, image_format, image_size, opened_as,
opened_by, sniff, valid_hash,
};
#[cfg(feature = "dir")]
pub use workspaces::WorkspaceStores;
#[cfg(feature = "dir")]
const PAGE_STORE_OWNER: &str = "so.tilo.content";
#[cfg(feature = "dir")]
const PAGE_MAX_ITEM_BYTES: usize = 64 * 1024 * 1024;
#[cfg(feature = "dir")]
const PAGE_MAX_TOTAL_BYTES: usize = 256 * 1024 * 1024;
pub const SHARED_STORE_ENV: &str = "TILO_BLOB_STORE";
const SEALED_MIME: &str = "application/octet-stream";
fn address_of(reference: &str) -> String {
content_address(reference).unwrap_or_else(|| reference.to_owned())
}
pub fn hash_bytes(bytes: &[u8]) -> String {
blake3::hash(bytes).to_hex().to_string()
}
pub fn names(reference: &str, bytes: &[u8]) -> bool {
let Some(parsed) = ContentRef::parse(reference) else {
return false;
};
match parsed.key() {
None => verify(parsed.address(), bytes),
Some(key) => tilo_seal::content::seal(key, bytes)
.is_ok_and(|sealed| verify(parsed.address(), &sealed)),
}
}
fn convergent_hasher(secret: &tilo_seal::SymmetricKey) -> blake3::Hasher {
blake3::Hasher::new_keyed(&blake3::derive_key(
"tilo record content key v1",
secret.expose_secret(),
))
}
#[must_use]
pub fn part_key(secret: &tilo_seal::SymmetricKey, bytes: &[u8]) -> tilo_seal::SymmetricKey {
let mut hasher = convergent_hasher(secret);
hasher.update(bytes);
tilo_seal::SymmetricKey::from_bytes(*hasher.finalize().as_bytes())
}
const KEEP_PLAINTEXT: usize = 1024 * 1024;
static SPILL_COUNTER: AtomicU64 = AtomicU64::new(0);
struct Gathered {
kept: Vec<u8>,
spill: Option<Spill>,
}
impl Gathered {
const fn new() -> Self {
Self {
kept: Vec::new(),
spill: None,
}
}
fn keep(&mut self, chunk: &[u8], scratch: Option<&Path>) -> Result<(), ContentError> {
if self.spill.is_none()
&& let Some(dir) = scratch
&& self.kept.len().saturating_add(chunk.len()) > KEEP_PLAINTEXT
{
self.spill = Some(Spill::open(dir, &self.kept)?);
self.kept = Vec::new();
}
if let Some(spill) = &mut self.spill {
return spill.write(chunk);
}
self.kept.extend_from_slice(chunk);
Ok(())
}
fn source(&mut self) -> Result<Box<dyn Read + '_>, ContentError> {
if let Some(spill) = &mut self.spill {
return spill.source();
}
Ok(Box::new(self.kept.as_slice()))
}
}
struct Spill {
file: std::fs::File,
path: PathBuf,
}
impl Spill {
fn open(dir: &Path, kept: &[u8]) -> Result<Self, ContentError> {
std::fs::create_dir_all(dir)?;
let serial = SPILL_COUNTER.fetch_add(1, Ordering::Relaxed);
let path = dir.join(format!(".sealing-{}-{serial}", std::process::id()));
let file = std::fs::File::options()
.read(true)
.write(true)
.create_new(true)
.open(&path)?;
let mut spill = Self { file, path };
spill.write(kept)?;
Ok(spill)
}
fn write(&mut self, chunk: &[u8]) -> Result<(), ContentError> {
self.file.write_all(chunk)?;
Ok(())
}
fn source(&mut self) -> Result<Box<dyn Read + '_>, ContentError> {
self.file.rewind()?;
Ok(Box::new(&mut self.file))
}
}
impl Drop for Spill {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
struct Failed(Option<std::io::Error>);
impl Read for Failed {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
self.0.take().map_or(Ok(0), Err)
}
}
pub fn verify(hash: &str, bytes: &[u8]) -> bool {
hash_bytes(bytes) == hash
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ContentState {
Resolved,
Pending,
Waiting,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContentLimits {
pub max_item_bytes: usize,
pub max_total_bytes: usize,
pub max_entries: usize,
pub max_scan_entries: usize,
}
impl Default for ContentLimits {
fn default() -> Self {
Self {
max_item_bytes: 64 * 1024 * 1024,
max_total_bytes: 1024 * 1024 * 1024,
max_entries: 65_536,
max_scan_entries: 131_072,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ContentError {
#[error("content does not match the address it was stored under")]
HashMismatch,
#[error("{0:?} is not a content address")]
InvalidHash(String),
#[error("content is {actual} bytes; per-item limit is {limit} bytes")]
ItemTooLarge { actual: usize, limit: usize },
#[error("store total would be {attempted} bytes; limit is {limit} bytes")]
TotalQuotaExceeded { attempted: usize, limit: usize },
#[error("store would contain more than {limit} items")]
EntryLimitExceeded { limit: usize },
#[error("store index exceeded its {limit}-entry scan bound")]
ScanLimitExceeded { limit: usize },
#[error("this store cannot collect unreferenced content")]
CollectionUnsupported,
#[error(
"the disk holding this content has {free} bytes free, under the {keep_free} it keeps \
for the host's own state: nothing new is kept until there is room"
)]
DiskLow { free: u64, keep_free: u64 },
#[error("content store I/O: {0}")]
Io(String),
}
impl From<std::io::Error> for ContentError {
fn from(error: std::io::Error) -> Self {
Self::Io(error.to_string())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stored {
pub hash: String,
pub len: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Collected {
pub hashes: Vec<String>,
pub bytes: u64,
}
pub type ContentReader = Box<dyn Read + Send>;
pub trait ContentBackend: Send + Sync {
fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError>;
fn put_many(&self, items: &[(&[u8], &str)]) -> Vec<Result<Stored, ContentError>> {
items
.iter()
.map(|(bytes, mime)| self.put(&mut &bytes[..], mime))
.collect()
}
fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError>;
fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
let Some(mut reader) = self.open(hash)? else {
return Ok(None);
};
std::io::copy(&mut reader.by_ref().take(offset), &mut std::io::sink())?;
Ok(Some(reader))
}
fn has(&self, hash: &str) -> bool;
fn size(&self, hash: &str) -> Option<u64> {
let _ = hash;
None
}
fn state(&self, hash: &str) -> ContentState {
if self.has(hash) {
ContentState::Resolved
} else {
ContentState::Unavailable
}
}
fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
let _ = live;
Err(ContentError::CollectionUnsupported)
}
fn release(&self, hash: &str) -> Result<Collected, ContentError> {
let _ = hash;
Err(ContentError::CollectionUnsupported)
}
fn shared(&self) -> bool {
false
}
fn workspace_scoped(&self) -> bool {
false
}
fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
None
}
fn put_sealed(
&self,
reader: &mut dyn Read,
mime: &str,
) -> Option<Result<Stored, ContentError>> {
let _ = (reader, mime);
None
}
fn max_item_bytes(&self) -> usize {
ContentLimits::default().max_item_bytes
}
fn scratch_dir(&self) -> Option<PathBuf> {
None
}
}
struct OneWorkspace(Arc<dyn ContentBackend>);
impl ContentBackend for OneWorkspace {
fn put(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
self.0.put(reader, mime)
}
fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
self.0.open(hash)
}
fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
self.0.open_at(hash, offset)
}
fn has(&self, hash: &str) -> bool {
self.0.has(hash)
}
fn size(&self, hash: &str) -> Option<u64> {
self.0.size(hash)
}
fn state(&self, hash: &str) -> ContentState {
self.0.state(hash)
}
fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
self.0.collect_unreferenced(live)
}
fn release(&self, hash: &str) -> Result<Collected, ContentError> {
self.0.release(hash)
}
fn shared(&self) -> bool {
self.0.shared()
}
fn workspace_scoped(&self) -> bool {
true
}
fn content_secret(&self) -> Option<tilo_seal::SymmetricKey> {
self.0.content_secret()
}
fn max_item_bytes(&self) -> usize {
self.0.max_item_bytes()
}
fn scratch_dir(&self) -> Option<PathBuf> {
self.0.scratch_dir()
}
}
#[derive(Clone)]
pub struct ContentStore {
backend: Arc<dyn ContentBackend>,
seals: bool,
}
impl std::fmt::Debug for ContentStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ContentStore").finish_non_exhaustive()
}
}
impl ContentStore {
pub fn new(backend: impl ContentBackend + 'static) -> Self {
Self::from_backend(Arc::new(backend))
}
pub fn from_backend(backend: Arc<dyn ContentBackend>) -> Self {
Self {
backend,
seals: false,
}
}
#[must_use]
pub fn sealing(self) -> Self {
Self {
seals: true,
..self
}
}
#[must_use]
pub fn unsealed(self) -> Self {
Self {
seals: false,
..self
}
}
pub fn memory() -> Self {
Self::new(MemoryBackend::default())
}
#[cfg(feature = "dir")]
pub fn in_dir(root: impl Into<PathBuf>) -> Self {
Self::new(DirBackend::new(root))
}
#[cfg(feature = "dir")]
pub fn local_for_app() -> Self {
Self::for_app_with(&|name| std::env::var_os(name))
}
#[cfg(feature = "dir")]
fn for_app_with(env: &dyn Fn(&str) -> Option<std::ffi::OsString>) -> Self {
if let Some(shared) = env(SHARED_STORE_ENV).filter(|value| !value.is_empty()) {
return Self::in_dir(PathBuf::from(shared));
}
if !tilo_files::available(tilo_files::Feature::NativePaths) {
return Self::page_files();
}
let Some(data) = tilo_paths::data_dir() else {
tracing::warn!("no data directory; binary content is kept in memory only");
return Self::memory();
};
let mut backend = DirBackend::new(data.join("tilo").join("content"));
if let Some(cache) = tilo_paths::cache_dir() {
backend = backend.reading_also(cache.join("tilo").join("blobs"));
}
Self::new(backend)
}
#[cfg(feature = "dir")]
#[must_use]
pub fn page_files() -> Self {
let limits = ContentLimits {
max_item_bytes: PAGE_MAX_ITEM_BYTES,
max_total_bytes: PAGE_MAX_TOTAL_BYTES,
..ContentLimits::default()
};
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
let mirrored = tilo_files::web::is_mirrored(&tilo_paths::default_profile());
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
let mirrored = true;
match tilo_files::VPath::new("content") {
Ok(content) if mirrored => Self::new(FilesBackend::new(
tilo_paths::AppPaths::for_app(PAGE_STORE_OWNER)
.data()
.join(&content),
limits,
)),
_ => Self::new(MemoryBackend::new(limits)),
}
}
#[must_use]
pub const fn seals(&self) -> bool {
self.seals
}
pub fn put(&self, bytes: &[u8]) -> Result<String, ContentError> {
let mime = sniff(bytes).mime;
let mut reader = bytes;
self.put_reader(&mut reader, &mime)
.map(|stored| stored.hash)
}
pub fn put_public(&self, bytes: &[u8]) -> Result<String, ContentError> {
let mut reader = bytes;
self.backend
.put(&mut reader, &sniff(bytes).mime)
.map(|stored| stored.hash)
}
pub fn put_public_many(&self, items: &[&[u8]]) -> Vec<Result<String, ContentError>> {
let mimes: Vec<String> = items.iter().map(|bytes| sniff(bytes).mime).collect();
let with_mime: Vec<(&[u8], &str)> = items
.iter()
.zip(&mimes)
.map(|(bytes, mime)| (*bytes, mime.as_str()))
.collect();
self.backend
.put_many(&with_mime)
.into_iter()
.map(|stored| stored.map(|stored| stored.hash))
.collect()
}
pub fn put_as(&self, reference: &str, bytes: &[u8]) -> Result<(), ContentError> {
let parsed = ContentRef::parse(reference)
.ok_or_else(|| ContentError::InvalidHash(reference.to_owned()))?;
let stored = match parsed.key() {
None => self.put_public(bytes)?,
Some(key) => {
let sealed = tilo_seal::content::seal(key, bytes)
.map_err(|error| ContentError::Io(error.to_string()))?;
let mut reader = sealed.as_slice();
self.backend.put(&mut reader, SEALED_MIME)?.hash
}
};
if stored == parsed.address() {
Ok(())
} else {
Err(ContentError::HashMismatch)
}
}
pub fn put_reader(&self, reader: &mut dyn Read, mime: &str) -> Result<Stored, ContentError> {
if !self.seals {
return self.backend.put(reader, mime);
}
if let Some(stored) = self.backend.put_sealed(reader, mime) {
return stored;
}
let mut gathered = None;
let key = match self.backend.content_secret() {
Some(secret) => {
let mut hasher = convergent_hasher(&secret);
gathered = Some(self.gather(reader, &mut hasher)?);
tilo_seal::SymmetricKey::from_bytes(*hasher.finalize().as_bytes())
}
None => tilo_seal::SymmetricKey::generate()
.map_err(|error| ContentError::Io(error.to_string()))?,
};
let source: Box<dyn Read + '_> = match &mut gathered {
Some(gathered) => gathered.source()?,
None => Box::new(reader),
};
let mut sealed = tilo_seal::content::SealReader::new(&key, source)
.map_err(|error| ContentError::Io(error.to_string()))?;
let stored = self.backend.put(&mut sealed, SEALED_MIME)?;
Ok(Stored {
hash: ContentRef::sealed(&stored.hash, key).to_string(),
len: stored.len,
})
}
fn gather(
&self,
reader: &mut dyn Read,
hasher: &mut blake3::Hasher,
) -> Result<Gathered, ContentError> {
let limit = self.backend.max_item_bytes();
let scratch = self.backend.scratch_dir();
let mut gathered = Gathered::new();
let mut buf = vec![0_u8; 64 * 1024];
let mut read = 0_usize;
loop {
let want = limit.saturating_add(1).saturating_sub(read).min(buf.len());
let n = match reader.read(buf.get_mut(..want).unwrap_or_default()) {
Ok(0) => return Ok(gathered),
Ok(n) => n.min(want),
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error.into()),
};
read = read.saturating_add(n);
if read > limit {
return Err(ContentError::ItemTooLarge {
actual: read,
limit,
});
}
let chunk = buf.get(..n).unwrap_or_default();
hasher.update(chunk);
gathered.keep(chunk, scratch.as_deref())?;
}
}
pub fn put_inputs(
&self,
inputs: &ContentInputs,
) -> Result<BTreeMap<String, String>, ContentError> {
let mut references = BTreeMap::new();
for (hash, bytes) in inputs.iter() {
let reference = self.put(bytes)?;
if content_address(&reference).as_deref() != Some(hash) && !self.seals {
return Err(ContentError::HashMismatch);
}
references.insert(hash.to_owned(), reference);
}
Ok(references)
}
pub fn reseal(&self, reference: &str) -> Option<String> {
if !self.seals || is_sealed(reference) {
return None;
}
let bytes = self.read(reference)?;
self.put(&bytes)
.inspect_err(|error| tracing::warn!(%error, "content could not be sealed"))
.ok()
}
pub fn read(&self, reference: &str) -> Option<Vec<u8>> {
let mut reader = self.open(reference)?;
let mut bytes = Vec::new();
match reader.read_to_end(&mut bytes) {
Ok(_) => Some(bytes),
Err(error) => {
tracing::warn!(%error, "content store: unreadable content");
None
}
}
}
pub fn open(&self, reference: &str) -> Option<ContentReader> {
let mut item = self.open_item(reference)?;
match list::List::read(&mut item) {
Ok(Ok(list)) => {
let mut missing = false;
for (_, part) in &list.parts {
if !self.has(part) {
let _ = self.backend.open(&address_of(part));
missing = true;
}
}
if missing {
return None;
}
let mut left: Vec<String> = list.parts.into_iter().map(|(_, part)| part).collect();
left.reverse();
Some(Box::new(list::Parts {
store: self.clone(),
left,
current: None,
}))
}
Ok(Err(read)) => Some(Box::new(std::io::Cursor::new(read).chain(item))),
Err(error) => Some(Box::new(Failed(Some(error)))),
}
}
fn open_item(&self, reference: &str) -> Option<ContentReader> {
let parsed = ContentRef::parse(reference);
let address = parsed.as_ref().map_or(reference, ContentRef::address);
let reader = self.backend.open(address).ok().flatten()?;
match parsed.as_ref().and_then(ContentRef::key) {
None => Some(reader),
Some(key) => tilo_seal::content::OpenReader::new(key, reader)
.ok()
.map(|reader| Box::new(reader) as ContentReader),
}
}
#[cfg(test)]
fn read_item_whole(&self, reference: &str) -> Vec<u8> {
let mut bytes = Vec::new();
if let Some(mut item) = self.open_item(reference) {
let _ = item.read_to_end(&mut bytes);
}
bytes
}
fn list(&self, reference: &str) -> Option<list::List> {
let mut item = self.open_item(reference)?;
list::List::read(&mut item).ok()?.ok()
}
pub fn put_parts(&self, reader: &mut dyn Read) -> Result<Stored, ContentError> {
let mut parts = Vec::new();
let mut part = Vec::with_capacity(list::PART_BYTES);
loop {
part.clear();
(&mut *reader)
.take(list::PART_BYTES as u64)
.read_to_end(&mut part)?;
if part.is_empty() && !parts.is_empty() {
break;
}
let len = part.len() as u64;
parts.push((len, self.put(&part)?));
if part.len() < list::PART_BYTES {
break;
}
}
if let [(len, only)] = parts.as_slice() {
return Ok(Stored {
hash: only.clone(),
len: *len,
});
}
let list = list::List { parts };
let len = list.total();
Ok(Stored {
hash: self.put(&list.encode())?,
len,
})
}
pub fn size(&self, reference: &str) -> Option<u64> {
if let Some(list) = self.list(reference) {
return Some(list.total());
}
self.item_size(reference)
}
fn item_size(&self, reference: &str) -> Option<u64> {
let parsed = ContentRef::parse(reference);
let address = parsed.as_ref().map_or(reference, ContentRef::address);
let stored = self.backend.size(address)?;
match parsed.as_ref().and_then(ContentRef::key) {
None => Some(stored),
Some(_) => tilo_seal::content::plain_len(stored),
}
}
pub fn read_range(
&self,
reference: &str,
offset: u64,
length: u64,
) -> Result<(u64, Vec<u8>), ContentError> {
let Some(list) = self.list(reference) else {
return self.read_item_range(reference, offset, length);
};
let size = list.total();
let end = offset.saturating_add(length).min(size);
let mut bytes = Vec::new();
let mut start = 0_u64;
for (len, part) in &list.parts {
let stop = start.saturating_add(*len);
if stop > offset && start < end {
let from = offset.max(start).saturating_sub(start);
let to = end.min(stop).saturating_sub(start);
let (_, piece) = self.read_item_range(part, from, to.saturating_sub(from))?;
bytes.extend_from_slice(&piece);
}
start = stop;
}
Ok((size, bytes))
}
fn read_item_range(
&self,
reference: &str,
offset: u64,
length: u64,
) -> Result<(u64, Vec<u8>), ContentError> {
let missing = || ContentError::InvalidHash(reference.to_owned());
let size = self.item_size(reference).ok_or_else(missing)?;
let offset = offset.min(size);
let length = length.min(size.saturating_sub(offset));
let parsed = ContentRef::parse(reference);
let address = parsed.as_ref().map_or(reference, ContentRef::address);
let (mut reader, skip): (ContentReader, u64) =
match parsed.as_ref().and_then(ContentRef::key) {
None => (
self.backend.open_at(address, offset)?.ok_or_else(missing)?,
0,
),
Some(key) => {
let chunk = tilo_seal::content::CHUNK as u64;
let index = offset.checked_div(chunk).unwrap_or(0);
let sealed = self
.backend
.open_at(address, tilo_seal::content::sealed_offset(index))?
.ok_or_else(missing)?;
let opened = tilo_seal::content::OpenReader::at_chunk(key, sealed, index)
.map_err(|error| ContentError::Io(error.to_string()))?;
(
Box::new(opened),
offset.saturating_sub(index.saturating_mul(chunk)),
)
}
};
let unreadable = |error: std::io::Error| ContentError::Io(error.to_string());
std::io::copy(&mut reader.by_ref().take(skip), &mut std::io::sink()).map_err(unreadable)?;
let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
reader
.take(length)
.read_to_end(&mut bytes)
.map_err(unreadable)?;
if (bytes.len() as u64) < length {
return Err(ContentError::Io(format!(
"{reference} ended {} bytes short of the piece asked for",
length.saturating_sub(bytes.len() as u64)
)));
}
Ok((size, bytes))
}
pub fn has(&self, reference: &str) -> bool {
self.backend.has(&address_of(reference))
}
pub fn state(&self, reference: &str) -> ContentState {
self.backend.state(&address_of(reference))
}
pub fn shared(&self) -> bool {
self.backend.shared()
}
pub fn workspace_scoped(&self) -> bool {
self.backend.workspace_scoped()
}
pub fn scratch_dir(&self) -> Option<PathBuf> {
self.backend.scratch_dir()
}
#[must_use]
pub fn for_one_workspace(self) -> Self {
Self {
backend: Arc::new(OneWorkspace(self.backend)),
seals: self.seals,
}
}
pub fn memory_in_workspace() -> Self {
Self::memory().for_one_workspace()
}
pub fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
let addresses = live.iter().map(|reference| address_of(reference)).collect();
self.backend.collect_unreferenced(&addresses)
}
pub fn release(&self, reference: &str) -> Result<Collected, ContentError> {
self.backend.release(&address_of(reference))
}
}
pub trait ContentSource {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>>;
}
impl ContentSource for ContentStore {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
self.read(hash).map(Cow::Owned)
}
}
impl ContentSource for BTreeMap<String, Vec<u8>> {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
self.get(hash).map(|bytes| Cow::Borrowed(bytes.as_slice()))
}
}
impl<T: ContentSource + ?Sized> ContentSource for &T {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
(**self).content(hash)
}
}
impl<A: ContentSource, B: ContentSource> ContentSource for (A, B) {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
self.0.content(hash).or_else(|| self.1.content(hash))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoContent;
impl ContentSource for NoContent {
fn content(&self, _hash: &str) -> Option<Cow<'_, [u8]>> {
None
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContentInputs {
entries: BTreeMap<String, Vec<u8>>,
}
impl ContentInputs {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, bytes: impl Into<Vec<u8>>) -> String {
let bytes = bytes.into();
let hash = hash_bytes(&bytes);
self.entries.entry(hash.clone()).or_insert(bytes);
hash
}
pub fn get(&self, hash: &str) -> Option<&[u8]> {
self.entries.get(hash).map(Vec::as_slice)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &[u8])> {
self.entries
.iter()
.map(|(hash, bytes)| (hash.as_str(), bytes.as_slice()))
}
pub fn append(&mut self, other: &mut Self) {
self.entries.append(&mut other.entries);
}
}
impl IntoIterator for ContentInputs {
type Item = (String, Vec<u8>);
type IntoIter = std::collections::btree_map::IntoIter<String, Vec<u8>>;
fn into_iter(self) -> Self::IntoIter {
self.entries.into_iter()
}
}
impl ContentSource for ContentInputs {
fn content(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
self.get(hash).map(Cow::Borrowed)
}
}
#[cfg(feature = "dir")]
pub struct Verifying<R> {
inner: R,
hasher: blake3::Hasher,
expected: String,
done: bool,
}
#[cfg(feature = "dir")]
impl<R> Verifying<R> {
pub fn new(inner: R, expected: &str) -> Self {
Self {
inner,
hasher: blake3::Hasher::new(),
expected: expected.to_ascii_lowercase(),
done: false,
}
}
}
#[cfg(feature = "dir")]
impl<R: Read> Read for Verifying<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.done {
return Ok(0);
}
let n = self.inner.read(buf)?;
if n == 0 {
self.done = true;
if self.hasher.finalize().to_hex().as_str() != self.expected {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"content does not match its address",
));
}
return Ok(0);
}
self.hasher.update(buf.get(..n).unwrap_or_default());
Ok(n)
}
}
#[cfg(test)]
#[cfg(feature = "dir")]
mod tests;