use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use crate::ArchivePath;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TocError {
InvalidFileBlocks,
MissingBlockReference { path: ArchivePath, block_index: u32 },
MissingPath(ArchivePath),
WrongEntryKind(ArchivePath),
FileAncestor(ArchivePath),
FileHasDescendants(ArchivePath),
InvalidSourceCommit { path: ArchivePath, commit: [u8; 4] },
DuplicateCommitId([u8; 4]),
}
impl fmt::Display for TocError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFileBlocks => f.write_str("file block references are invalid"),
Self::MissingBlockReference { path, block_index } => {
write!(f, "file {path} references missing block {block_index}")
}
Self::MissingPath(path) => write!(f, "archive path does not exist: {path}"),
Self::WrongEntryKind(path) => {
write!(f, "archive path has the wrong entry kind: {path}")
}
Self::FileAncestor(path) => write!(f, "a file blocks this archive path: {path}"),
Self::FileHasDescendants(path) => {
write!(
f,
"cannot replace a directory with descendants by a file: {path}"
)
}
Self::InvalidSourceCommit { path, commit } => write!(
f,
"file {path} references missing or mismatched source commit {:08x}",
u32::from_le_bytes(*commit)
),
Self::DuplicateCommitId(commit) => {
write!(f, "duplicate commit ID {:08x}", u32::from_le_bytes(*commit))
}
}
}
}
impl std::error::Error for TocError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileGroupKind {
EmptyFiles,
TinyFiles,
SmallFiles,
BigFiles,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEntry {
pub size: u64,
pub block_indices: Vec<u32>,
pub offset_in_block: Option<u32>,
pub checksum: Option<u64>,
pub source_commit: Option<[u8; 4]>,
}
impl FileEntry {
pub fn new(size: u64, block_indices: Vec<u32>) -> Result<Self, TocError> {
if (size == 0) != block_indices.is_empty() {
return Err(TocError::InvalidFileBlocks);
}
let mut unique = block_indices.clone();
unique.sort_unstable();
unique.dedup();
if unique.len() != block_indices.len() {
return Err(TocError::InvalidFileBlocks);
}
Ok(Self {
size,
block_indices,
offset_in_block: None,
checksum: None,
source_commit: None,
})
}
pub fn with_block_offset(mut self, offset: u32) -> Self {
self.offset_in_block = Some(offset);
self
}
pub fn with_checksum(mut self, checksum: u64) -> Self {
self.checksum = Some(checksum);
self
}
pub fn with_source_commit(mut self, commit: [u8; 4]) -> Self {
self.source_commit = Some(commit);
self
}
pub fn group_kind(&self, block_size: u32) -> FileGroupKind {
assert!(block_size > 0, "block size must be nonzero");
if self.size >= u64::from(block_size) {
FileGroupKind::BigFiles
} else {
match self.size {
0 => FileGroupKind::EmptyFiles,
1..=8 => FileGroupKind::TinyFiles,
_ => FileGroupKind::SmallFiles,
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceKind {
Character,
Block,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TocEntry {
File(FileEntry),
Directory,
Symlink {
target: String,
},
NamedPipe,
Device {
kind: DeviceKind,
major: u32,
minor: u32,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TocChange {
PutFile {
path: ArchivePath,
entry: FileEntry,
},
PutDirectory {
path: ArchivePath,
},
PutSymlink {
path: ArchivePath,
target: String,
},
PutNamedPipe {
path: ArchivePath,
},
PutDevice {
path: ArchivePath,
kind: DeviceKind,
major: u32,
minor: u32,
},
RemoveFile {
path: ArchivePath,
},
RemoveDirectory {
path: ArchivePath,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Toc {
entries: BTreeMap<ArchivePath, TocEntry>,
sources: HashMap<[u8; 4], Vec<FileEntry>>,
ambiguous_sources: HashSet<[u8; 4]>,
file_origins: BTreeMap<ArchivePath, [u8; 4]>,
}
impl Toc {
pub fn get(&self, path: &ArchivePath) -> Option<&TocEntry> {
self.entries.get(path)
}
pub(crate) fn file_origin(&self, path: &ArchivePath) -> Option<[u8; 4]> {
self.file_origins.get(path).copied()
}
pub fn iter(&self) -> impl Iterator<Item = (&ArchivePath, &TocEntry)> {
self.entries.iter()
}
pub(crate) fn filter_entries(
&self,
mut include: impl FnMut(&ArchivePath, &TocEntry) -> bool,
) -> Self {
Self {
entries: self
.entries
.iter()
.filter(|(path, entry)| include(path, entry))
.map(|(path, entry)| (path.clone(), entry.clone()))
.collect(),
..Self::default()
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub(crate) fn forget_empty_commit(&mut self, commit: [u8; 4]) -> Result<(), TocError> {
if self.sources.get(&commit).is_some_and(Vec::is_empty) {
self.sources.remove(&commit);
Ok(())
} else {
Err(TocError::DuplicateCommitId(commit))
}
}
pub fn apply_archive_commit(
&mut self,
commit: [u8; 4],
changes: &[TocChange],
) -> Result<(), TocError> {
self.apply_archive_commit_inner(commit, changes, false, true)
}
pub(crate) fn apply_overlay_commit(
&mut self,
commit: [u8; 4],
changes: &[TocChange],
) -> Result<(), TocError> {
self.apply_archive_commit_inner(commit, changes, true, true)
}
pub(crate) fn apply_selected_archive_commit(
&mut self,
commit: [u8; 4],
changes: &[TocChange],
selected: bool,
) -> Result<(), TocError> {
self.apply_archive_commit_inner(commit, changes, false, selected)
}
fn apply_archive_commit_inner(
&mut self,
commit: [u8; 4],
changes: &[TocChange],
allow_overlay_collision: bool,
selected: bool,
) -> Result<(), TocError> {
let collision = self.sources.contains_key(&commit);
if collision && !allow_overlay_collision {
return Err(TocError::DuplicateCommitId(commit));
}
if selected {
for change in changes {
if let TocChange::PutFile { path, entry } = change
&& let Some(source) = entry.source_commit
{
let mut expected = entry.clone();
expected.source_commit = None;
if self.ambiguous_sources.contains(&source)
|| (collision && source == commit)
|| !self
.sources
.get(&source)
.is_some_and(|entries| entries.contains(&expected))
{
return Err(TocError::InvalidSourceCommit {
path: path.clone(),
commit: source,
});
}
}
}
}
if selected {
self.apply_commit(changes)?;
for change in changes {
if let TocChange::PutFile { path, entry } = change {
self.file_origins
.insert(path.clone(), entry.source_commit.unwrap_or(commit));
}
}
self.file_origins
.retain(|path, _| matches!(self.entries.get(path), Some(TocEntry::File(_))));
}
let entries = changes
.iter()
.filter_map(|change| match change {
TocChange::PutFile { entry, .. } if entry.source_commit.is_none() => {
Some(entry.clone())
}
_ => None,
})
.collect();
if collision {
self.ambiguous_sources.insert(commit);
} else {
self.sources.insert(commit, entries);
}
Ok(())
}
pub fn apply_commit_with_available_blocks(
&mut self,
changes: &[TocChange],
available_blocks: &HashSet<u32>,
) -> Result<(), TocError> {
Self::check_available_blocks(changes, available_blocks)?;
self.apply_commit(changes)
}
pub fn check_available_blocks(
changes: &[TocChange],
available_blocks: &HashSet<u32>,
) -> Result<(), TocError> {
for change in changes {
if let TocChange::PutFile { path, entry } = change
&& entry.source_commit.is_none()
&& let Some(&block_index) = entry
.block_indices
.iter()
.find(|&&index| !available_blocks.contains(&index))
{
return Err(TocError::MissingBlockReference {
path: path.clone(),
block_index,
});
}
}
Ok(())
}
pub fn apply_commit(&mut self, changes: &[TocChange]) -> Result<(), TocError> {
let mut updated = self.entries.clone();
for change in changes {
apply_change(&mut updated, change)?;
}
self.entries = updated;
Ok(())
}
}
fn apply_change(
entries: &mut BTreeMap<ArchivePath, TocEntry>,
change: &TocChange,
) -> Result<(), TocError> {
match change {
TocChange::PutFile { path, entry } => {
if (entry.size == 0) != entry.block_indices.is_empty() {
return Err(TocError::InvalidFileBlocks);
}
if entry.offset_in_block.is_some_and(|offset| {
entry.size == 0
|| entry.block_indices.len() != 1
|| u64::from(offset)
.checked_add(entry.size)
.is_none_or(|end| end > u64::from(u32::MAX) + 1)
}) {
return Err(TocError::InvalidFileBlocks);
}
let mut unique = entry.block_indices.clone();
unique.sort_unstable();
unique.dedup();
if unique.len() != entry.block_indices.len() {
return Err(TocError::InvalidFileBlocks);
}
ensure_no_non_directory_ancestor(entries, path)?;
if has_descendant(entries, path) {
return Err(TocError::FileHasDescendants(path.clone()));
}
entries.insert(path.clone(), TocEntry::File(entry.clone()));
}
TocChange::PutDirectory { path } => {
ensure_no_non_directory_ancestor(entries, path)?;
entries.insert(path.clone(), TocEntry::Directory);
}
TocChange::PutSymlink { path, target } => {
if target.is_empty() || target.as_bytes().contains(&0) {
return Err(TocError::InvalidFileBlocks);
}
ensure_no_non_directory_ancestor(entries, path)?;
if has_descendant(entries, path) {
return Err(TocError::FileHasDescendants(path.clone()));
}
entries.insert(
path.clone(),
TocEntry::Symlink {
target: target.clone(),
},
);
}
TocChange::PutNamedPipe { path } => {
ensure_no_non_directory_ancestor(entries, path)?;
if has_descendant(entries, path) {
return Err(TocError::FileHasDescendants(path.clone()));
}
entries.insert(path.clone(), TocEntry::NamedPipe);
}
TocChange::PutDevice {
path,
kind,
major,
minor,
} => {
if !matches!(kind, DeviceKind::Character | DeviceKind::Block) {
return Err(TocError::InvalidFileBlocks);
}
ensure_no_non_directory_ancestor(entries, path)?;
if has_descendant(entries, path) {
return Err(TocError::FileHasDescendants(path.clone()));
}
entries.insert(
path.clone(),
TocEntry::Device {
kind: *kind,
major: *major,
minor: *minor,
},
);
}
TocChange::RemoveFile { path } => match entries.get(path) {
None => {}
Some(
TocEntry::File(_)
| TocEntry::Symlink { .. }
| TocEntry::NamedPipe
| TocEntry::Device { .. },
) => {
entries.remove(path);
}
Some(TocEntry::Directory) => return Err(TocError::WrongEntryKind(path.clone())),
},
TocChange::RemoveDirectory { path } => match entries.get(path) {
None => entries.retain(|existing, _| !is_descendant(existing, path)),
Some(
TocEntry::File(_)
| TocEntry::Symlink { .. }
| TocEntry::NamedPipe
| TocEntry::Device { .. },
) => return Err(TocError::WrongEntryKind(path.clone())),
Some(TocEntry::Directory) => {
entries.retain(|existing, _| existing != path && !is_descendant(existing, path));
}
},
}
Ok(())
}
fn ensure_no_non_directory_ancestor(
entries: &BTreeMap<ArchivePath, TocEntry>,
path: &ArchivePath,
) -> Result<(), TocError> {
ensure_no_entry_ancestor(entries, path, |entry| !matches!(entry, TocEntry::Directory))
}
fn ensure_no_entry_ancestor(
entries: &BTreeMap<ArchivePath, TocEntry>,
path: &ArchivePath,
is_blocking: impl Fn(&TocEntry) -> bool,
) -> Result<(), TocError> {
let mut parent = path.as_str();
while let Some(separator) = parent.rfind('/') {
parent = &parent[..separator];
if entries.get(parent).is_some_and(&is_blocking) {
return Err(TocError::FileAncestor(
ArchivePath::new(parent.to_owned()).expect("validated path prefix"),
));
}
}
Ok(())
}
fn has_descendant(entries: &BTreeMap<ArchivePath, TocEntry>, ancestor: &ArchivePath) -> bool {
let prefix = format!("{}/", ancestor.as_str());
entries
.range::<str, _>((
std::ops::Bound::Included(prefix.as_str()),
std::ops::Bound::Unbounded,
))
.next()
.is_some_and(|(existing, _)| existing.as_str().starts_with(&prefix))
}
fn is_descendant(candidate: &ArchivePath, ancestor: &ArchivePath) -> bool {
candidate
.as_str()
.strip_prefix(ancestor.as_str())
.is_some_and(|suffix| suffix.starts_with('/'))
}
#[cfg(test)]
mod tests {
use super::*;
fn path(value: &str) -> ArchivePath {
ArchivePath::try_from(value).unwrap()
}
fn file(size: u64, block_indices: &[u32]) -> FileEntry {
FileEntry::new(size, block_indices.to_vec()).unwrap()
}
#[test]
fn descendant_lookup_handles_prefixes_and_unicode() {
let mut toc = Toc::default();
toc.apply_commit(&[
TocChange::PutFile {
path: path("name-else"),
entry: file(1, &[0]),
},
TocChange::PutDirectory { path: path("name") },
TocChange::PutFile {
path: path("name/\u{10ffff}child"),
entry: file(1, &[1]),
},
])
.unwrap();
assert!(matches!(
toc.apply_commit(&[TocChange::PutFile {
path: path("name"),
entry: file(1, &[2]),
}]),
Err(TocError::FileHasDescendants(_))
));
toc.apply_commit(&[TocChange::PutFile {
path: path("name-other"),
entry: file(1, &[3]),
}])
.unwrap();
assert!(matches!(
toc.apply_commit(&[TocChange::PutFile {
path: path("name-other/child"),
entry: file(1, &[4]),
}]),
Err(TocError::FileAncestor(_))
));
}
#[test]
fn special_file_entries_conflict_with_descendants_and_replace_in_order() {
let mut toc = Toc::default();
toc.apply_commit(&[TocChange::PutSymlink {
path: path("node"),
target: "target".to_owned(),
}])
.unwrap();
assert!(
toc.apply_commit(&[TocChange::PutFile {
path: path("node/child"),
entry: FileEntry::new(1, vec![0]).unwrap()
}])
.is_err()
);
toc.apply_commit(&[TocChange::PutNamedPipe { path: path("node") }])
.unwrap();
assert_eq!(toc.get(&path("node")), Some(&TocEntry::NamedPipe));
toc.apply_commit(&[TocChange::RemoveFile { path: path("node") }])
.unwrap();
assert!(toc.get(&path("node")).is_none());
}
#[test]
fn file_group_kinds_cover_tiny_small_and_big_boundaries() {
let block_size = 64 * 1024;
assert_eq!(
file(0, &[]).group_kind(block_size),
FileGroupKind::EmptyFiles
);
for size in 1..=8 {
assert_eq!(
file(size, &[0]).group_kind(block_size),
FileGroupKind::TinyFiles
);
}
assert_eq!(
file(9, &[0]).group_kind(block_size),
FileGroupKind::SmallFiles
);
assert_eq!(
file(u64::from(block_size) - 1, &[0]).group_kind(block_size),
FileGroupKind::SmallFiles
);
assert_eq!(
file(u64::from(block_size), &[0]).group_kind(block_size),
FileGroupKind::BigFiles
);
}
#[test]
fn applies_ordered_changes_and_directory_tombstones() {
let mut toc = Toc::default();
toc.apply_commit(&[
TocChange::PutDirectory { path: path("docs") },
TocChange::PutFile {
path: path("docs/old.txt"),
entry: file(4, &[0]),
},
TocChange::PutFile {
path: path("docs/new.txt"),
entry: file(5, &[1]),
},
TocChange::RemoveDirectory { path: path("docs") },
TocChange::PutDirectory { path: path("docs") },
TocChange::PutFile {
path: path("docs/final.txt"),
entry: file(5, &[2]),
},
])
.unwrap();
assert_eq!(toc.len(), 2);
assert_eq!(toc.get(&path("docs")), Some(&TocEntry::Directory));
assert_eq!(
toc.get(&path("docs/final.txt")),
Some(&TocEntry::File(file(5, &[2])))
);
assert!(toc.get(&path("docs/old.txt")).is_none());
assert!(toc.get(&path("docs/new.txt")).is_none());
}
#[test]
fn directory_tombstone_removes_descendants_without_directory_entry() {
let mut toc = Toc::default();
toc.apply_commit(&[
TocChange::PutFile {
path: path("docs/file"),
entry: file(1, &[0]),
},
TocChange::RemoveDirectory { path: path("docs") },
])
.unwrap();
assert!(toc.is_empty());
}
#[test]
fn removals_of_missing_paths_are_noops_and_file_replacement_is_ordered() {
let mut toc = Toc::default();
toc.apply_commit(&[
TocChange::RemoveFile {
path: path("missing"),
},
TocChange::RemoveDirectory {
path: path("missing-dir"),
},
TocChange::PutFile {
path: path("item"),
entry: file(2, &[0]),
},
TocChange::PutFile {
path: path("item"),
entry: file(3, &[1]),
},
])
.unwrap();
assert_eq!(toc.len(), 1);
assert_eq!(toc.get(&path("item")), Some(&TocEntry::File(file(3, &[1]))));
}
#[test]
fn rejects_invalid_file_references_and_file_directory_conflicts_atomically() {
assert_eq!(FileEntry::new(0, vec![1]), Err(TocError::InvalidFileBlocks));
assert_eq!(FileEntry::new(1, vec![]), Err(TocError::InvalidFileBlocks));
assert_eq!(
FileEntry::new(2, vec![1, 1]),
Err(TocError::InvalidFileBlocks)
);
let mut toc = Toc::default();
toc.apply_commit(&[TocChange::PutFile {
path: path("parent"),
entry: file(1, &[0]),
}])
.unwrap();
let before = toc.clone();
assert_eq!(
toc.apply_commit(&[TocChange::PutFile {
path: path("parent/child"),
entry: file(1, &[1]),
}]),
Err(TocError::FileAncestor(path("parent")))
);
assert_eq!(toc, before);
let mut toc = Toc::default();
toc.apply_commit(&[
TocChange::PutDirectory {
path: path("folder"),
},
TocChange::PutFile {
path: path("folder/child"),
entry: file(1, &[0]),
},
])
.unwrap();
let before = toc.clone();
assert_eq!(
toc.apply_commit(&[TocChange::PutFile {
path: path("folder"),
entry: file(1, &[1]),
}]),
Err(TocError::FileHasDescendants(path("folder")))
);
assert_eq!(toc, before);
}
#[test]
fn commit_changes_validate_references_atomically() {
let mut toc = Toc::default();
let available_blocks = HashSet::from([3, 7]);
let changes = [
TocChange::PutFile {
path: path("valid.bin"),
entry: file(2, &[3, 7]),
},
TocChange::PutFile {
path: path("missing.bin"),
entry: file(1, &[9]),
},
];
assert_eq!(
toc.apply_commit_with_available_blocks(&changes, &available_blocks),
Err(TocError::MissingBlockReference {
path: path("missing.bin"),
block_index: 9,
})
);
assert!(toc.is_empty());
toc.apply_commit_with_available_blocks(&changes[..1], &available_blocks)
.unwrap();
assert_eq!(toc.len(), 1);
}
#[test]
fn validating_new_changes_allows_references_to_prior_commits() {
let mut toc = Toc::default();
toc.apply_commit(&[TocChange::PutFile {
path: path("existing.bin"),
entry: file(1, &[2]),
}])
.unwrap();
toc.apply_commit_with_available_blocks(
&[TocChange::PutFile {
path: path("new.bin"),
entry: file(1, &[5]),
}],
&HashSet::from([5]),
)
.unwrap();
assert_eq!(toc.len(), 2);
}
#[test]
fn archive_replay_tracks_the_actual_file_origin() {
let mut toc = Toc::default();
let entry = file(1, &[0]);
toc.apply_archive_commit(
[1, 0, 0, 0],
&[TocChange::PutFile {
path: path("first"),
entry: entry.clone(),
}],
)
.unwrap();
toc.apply_archive_commit(
[2, 0, 0, 0],
&[TocChange::PutFile {
path: path("second"),
entry: entry.clone(),
}],
)
.unwrap();
toc.apply_archive_commit(
[3, 0, 0, 0],
&[TocChange::PutFile {
path: path("alias"),
entry: entry.with_source_commit([1, 0, 0, 0]),
}],
)
.unwrap();
assert_eq!(toc.file_origin(&path("first")), Some([1, 0, 0, 0]));
assert_eq!(toc.file_origin(&path("second")), Some([2, 0, 0, 0]));
assert_eq!(toc.file_origin(&path("alias")), Some([1, 0, 0, 0]));
toc.apply_archive_commit(
[4, 0, 0, 0],
&[TocChange::RemoveFile {
path: path("first"),
}],
)
.unwrap();
assert_eq!(toc.file_origin(&path("first")), None);
}
#[test]
fn overlay_commit_id_collisions_cannot_be_reference_sources() {
let mut toc = Toc::default();
let commit = [1, 0, 0, 0];
let original = file(1, &[2]);
toc.apply_archive_commit(
commit,
&[TocChange::PutFile {
path: path("base"),
entry: original.clone(),
}],
)
.unwrap();
toc.apply_overlay_commit(
commit,
&[TocChange::PutFile {
path: path("overlay"),
entry: file(1, &[3]),
}],
)
.unwrap();
let result = toc.apply_overlay_commit(
[2, 0, 0, 0],
&[TocChange::PutFile {
path: path("alias"),
entry: original.with_source_commit(commit),
}],
);
assert!(matches!(result, Err(TocError::InvalidSourceCommit { .. })));
assert!(toc.get(&path("alias")).is_none());
}
#[test]
fn removing_a_path_with_wrong_kind_is_rejected() {
let mut toc = Toc::default();
toc.apply_commit(&[TocChange::PutDirectory {
path: path("folder"),
}])
.unwrap();
assert_eq!(
toc.apply_commit(&[TocChange::RemoveFile {
path: path("folder"),
}]),
Err(TocError::WrongEntryKind(path("folder")))
);
}
}