use std::collections::{BTreeMap, HashMap};
use crate::fidelity::{Direction, FidelityReport, LossPolicy, Property, WRITE_BITS};
use crate::path::canonical_key;
use crate::source::{
ClassifyError, Darwin, EntryKind, FileContent, LinkEnd, LinkStep, Metadata, PathFault,
SourceEntry, classify_paths, follow_hard_link,
};
use crate::time::{DosTimestamp, Timestamp};
use super::geometry::{ExfatLayout, FIRST_CLUSTER};
use super::name::{NameError, PlacedName, place};
use super::ondisk::{DIR_ENTRY_SIZE, FileAttributes, UpcaseTable};
pub const MAX_DIRECTORY_BYTES: u64 = 256 << 20;
pub const MAX_DIRECTORY_ENTRIES: u64 = MAX_DIRECTORY_BYTES / DIR_ENTRY_SIZE as u64;
pub(crate) const ROOT_LEADING_SLOTS: u32 = 4;
pub(crate) const ROOT_DIR: usize = 0;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum TimeField {
Modification,
Access,
Birth,
}
impl TimeField {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
TimeField::Modification => "modification time",
TimeField::Access => "access time",
TimeField::Birth => "birth time",
}
}
}
impl core::fmt::Display for TimeField {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModelError {
#[error("{}: {source}", crate::escape::printable(.path))]
#[non_exhaustive]
Name {
path: Vec<u8>,
#[source]
source: NameError,
},
#[error("path {} has a `..` component", crate::escape::printable(.path))]
#[non_exhaustive]
InvalidComponent {
path: Vec<u8>,
},
#[error("path {} is used by more than one entry", crate::escape::printable(.path))]
#[non_exhaustive]
Duplicate {
path: Vec<u8>,
},
#[error(
"{} and {} fold to one name through this volume's up-case table, which is what every \
exFAT lookup compares through",
crate::escape::printable(.path),
crate::escape::printable(.other)
)]
#[non_exhaustive]
Indistinguishable {
path: Vec<u8>,
other: Vec<u8>,
},
#[error("path {} has no parent directory", crate::escape::printable(.path))]
#[non_exhaustive]
ParentMissing {
path: Vec<u8>,
},
#[error("path {} has a parent that is not a directory", crate::escape::printable(.path))]
#[non_exhaustive]
ParentNotDir {
path: Vec<u8>,
},
#[error("entry {} names the root but is not a directory", crate::escape::printable(.path))]
#[non_exhaustive]
RootNotDirectory {
path: Vec<u8>,
},
#[error(
"hard link {} targets {}, which does not exist",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
HardlinkTargetMissing {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"hard link {} targets the directory {}",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
HardlinkTargetIsDirectory {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"hard link {} names a chain of links that returns to itself",
crate::escape::printable(.path)
)]
#[non_exhaustive]
HardlinkCycle {
path: Vec<u8>,
},
#[error(
"{}: a {field} of {secs} seconds past the epoch is outside the {min} to {max} an exFAT \
directory entry represents",
crate::escape::printable(.path)
)]
#[non_exhaustive]
TimeOutOfRange {
path: Vec<u8>,
field: TimeField,
secs: i64,
min: i64,
max: i64,
},
#[error(
"{}: an exFAT volume cannot carry the {} of this entry",
crate::escape::printable(.path),
.property.as_str()
)]
#[non_exhaustive]
LossNotAccepted {
path: Vec<u8>,
property: Property,
},
#[error(
"the directory {} needs {needed} bytes of entries and the format holds {limit} in one",
crate::escape::printable(.path)
)]
#[non_exhaustive]
DirectoryTooLarge {
path: Vec<u8>,
needed: u64,
limit: u64,
},
#[error("the tree needs {needed} clusters and the volume has {available}")]
#[non_exhaustive]
VolumeFull {
needed: u64,
available: u32,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) struct ClusterRun {
pub first: u32,
pub count: u32,
}
impl ClusterRun {
pub(crate) const fn is_empty(self) -> bool {
self.count == 0
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) struct EntryTimes {
pub create: DosTimestamp,
pub modify: DosTimestamp,
pub access: DosTimestamp,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Node {
Dir(usize),
File {
content: usize,
size: u64,
run: ClusterRun,
},
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct ModelEntry {
pub name: PlacedName,
pub attributes: FileAttributes,
pub times: EntryTimes,
pub node: Node,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct ModelDir {
pub entries: Vec<ModelEntry>,
pub run: ClusterRun,
pub path: Vec<u8>,
}
impl ModelDir {
fn bytes(&self, index: usize) -> u64 {
let leading = if index == ROOT_DIR {
u64::from(ROOT_LEADING_SLOTS)
} else {
0
};
let slots = leading
+ self
.entries
.iter()
.map(|e| u64::from(e.name.slots()))
.sum::<u64>();
slots * DIR_ENTRY_SIZE as u64
}
}
#[derive(Debug)]
pub(crate) struct ExfatModel {
pub dirs: Vec<ModelDir>,
pub contents: Vec<FileContent>,
pub fidelity: FidelityReport,
pub used_clusters: u32,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct ModelConfig<'a> {
pub loss: LossPolicy,
pub upcase: &'a UpcaseTable,
}
pub(crate) fn build_model(
entries: Vec<SourceEntry>,
layout: &ExfatLayout,
config: &ModelConfig<'_>,
) -> Result<ExfatModel, ModelError> {
let mut placed = place_tree(entries, config)?;
let used_clusters = placed.allocate(layout)?;
Ok(placed.finish(used_clusters))
}
pub(crate) fn place_tree(
entries: Vec<SourceEntry>,
config: &ModelConfig<'_>,
) -> Result<PlacedTree, ModelError> {
Builder::new(config).place_all(entries)
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum Class {
Dir,
File {
content: usize,
size: u64,
},
Link(Vec<u8>),
Unrepresentable,
}
struct Builder<'a> {
config: &'a ModelConfig<'a>,
dirs: Vec<ModelDir>,
contents: Vec<FileContent>,
fidelity: FidelityReport,
classes: BTreeMap<Vec<u8>, Class>,
dir_of: HashMap<Vec<u8>, usize>,
folded: Vec<HashMap<Vec<u16>, Vec<u8>>>,
}
impl<'a> Builder<'a> {
fn new(config: &'a ModelConfig<'a>) -> Self {
let root = ModelDir {
entries: Vec::new(),
run: ClusterRun::default(),
path: b"/".to_vec(),
};
Self {
config,
dirs: vec![root],
contents: Vec::new(),
fidelity: FidelityReport::new(),
classes: BTreeMap::new(),
dir_of: HashMap::from([(Vec::new(), 0usize)]),
folded: vec![HashMap::new()],
}
}
fn place_all(mut self, mut entries: Vec<SourceEntry>) -> Result<PlacedTree, ModelError> {
entries.sort_by_key(|entry| canonical_key(&entry.path));
self.classify(&entries)?;
for entry in entries {
self.place(entry)?;
}
Ok(PlacedTree {
dirs: self.dirs,
contents: self.contents,
fidelity: self.fidelity,
})
}
fn classify(&mut self, entries: &[SourceEntry]) -> Result<(), ModelError> {
let mut next_content = 0usize;
self.classes = classify_paths(
entries,
|entry, _| {
Ok(match &entry.kind {
EntryKind::Directory => Class::Dir,
EntryKind::File(content) => {
let size = content.len();
let content = next_content;
next_content += 1;
Class::File { content, size }
}
EntryKind::HardLink { target } => Class::Link(canonical_key(target)),
_ => Class::Unrepresentable,
})
},
|class| *class == Class::Dir,
)
.map_err(|e| match e {
ClassifyError::Class(e) => e,
ClassifyError::Path(PathFault::Traversal, path) => {
ModelError::InvalidComponent { path }
}
ClassifyError::Path(PathFault::Duplicate, path) => ModelError::Duplicate { path },
ClassifyError::Path(PathFault::RootNotDirectory, path) => {
ModelError::RootNotDirectory { path }
}
})?;
Ok(())
}
fn place(&mut self, entry: SourceEntry) -> Result<(), ModelError> {
let SourceEntry {
path,
kind,
meta,
xattrs,
darwin,
} = entry;
let key = canonical_key(&path);
if key.is_empty() {
return Ok(());
}
let split = key.iter().rposition(|&b| b == b'/');
let (parent_key, name) = match split {
Some(at) => (key[..at].to_vec(), key[at + 1..].to_vec()),
None => (Vec::new(), key.clone()),
};
let parent = match self.dir_of.get(&parent_key) {
Some(&index) => index,
None if self.classes.contains_key(&parent_key) => {
return Err(ModelError::ParentNotDir { path });
}
None => return Err(ModelError::ParentMissing { path }),
};
let Some(node) = self.node_for(kind, &key, &path)? else {
return Ok(());
};
let placed = self.name_in(parent, &name, &path)?;
let times = self.times_for(&meta, &path)?;
let is_dir = matches!(node, Node::Dir(_));
self.record_losses(&meta, &xattrs, darwin.as_ref(), is_dir, &path)?;
let mut attributes = if is_dir {
FileAttributes::DIRECTORY
} else {
FileAttributes::ARCHIVE
};
if meta.mode & WRITE_BITS == 0 {
attributes |= FileAttributes::READ_ONLY;
}
self.dirs[parent].entries.push(ModelEntry {
name: placed,
attributes,
times,
node,
});
Ok(())
}
fn node_for(
&mut self,
kind: EntryKind,
key: &[u8],
path: &[u8],
) -> Result<Option<Node>, ModelError> {
match kind {
EntryKind::Directory => {
let index = self.dirs.len();
self.dirs.push(ModelDir {
entries: Vec::new(),
run: ClusterRun::default(),
path: path.to_vec(),
});
self.folded.push(HashMap::new());
self.dir_of.insert(key.to_vec(), index);
Ok(Some(Node::Dir(index)))
}
EntryKind::File(content) => {
let Some(Class::File { content: at, size }) = self.classes.get(key).cloned() else {
unreachable!("a file was classified as something else")
};
assert_eq!(at, self.contents.len(), "the two passes fell out of step");
self.contents.push(content);
Ok(Some(Node::File {
content: at,
size,
run: ClusterRun::default(),
}))
}
EntryKind::HardLink { target } => match self.resolve_link(&target, path)? {
Some((content, size)) => {
self.lose(Property::Kind, path)?;
Ok(Some(Node::File {
content,
size,
run: ClusterRun::default(),
}))
}
None => {
self.lose(Property::Kind, path)?;
Ok(None)
}
},
_ => {
self.lose(Property::Kind, path)?;
Ok(None)
}
}
}
fn resolve_link(&self, target: &[u8], path: &[u8]) -> Result<Option<(usize, u64)>, ModelError> {
match follow_hard_link(target, self.classes.len(), |key| {
match self.classes.get(key) {
Some(Class::File { content, size }) => LinkStep::File((*content, *size)),
Some(Class::Dir) => LinkStep::Directory,
Some(Class::Unrepresentable) => LinkStep::Unrepresentable,
Some(Class::Link(next)) => LinkStep::Link(next.clone()),
None => LinkStep::Missing,
}
}) {
LinkEnd::File(found) => Ok(Some(found)),
LinkEnd::Unrepresentable => Ok(None),
LinkEnd::Directory => Err(ModelError::HardlinkTargetIsDirectory {
path: path.to_vec(),
target: target.to_vec(),
}),
LinkEnd::Missing => Err(ModelError::HardlinkTargetMissing {
path: path.to_vec(),
target: target.to_vec(),
}),
LinkEnd::Cycle => Err(ModelError::HardlinkCycle {
path: path.to_vec(),
}),
}
}
fn name_in(
&mut self,
parent: usize,
name: &[u8],
path: &[u8],
) -> Result<PlacedName, ModelError> {
let (placed, folded) =
place(name, self.config.upcase).map_err(|source| ModelError::Name {
path: path.to_vec(),
source,
})?;
if let Some(other) = self.folded[parent].get(&folded) {
return Err(ModelError::Indistinguishable {
path: path.to_vec(),
other: other.clone(),
});
}
self.folded[parent].insert(folded, path.to_vec());
Ok(placed)
}
fn times_for(&mut self, meta: &Metadata, path: &[u8]) -> Result<EntryTimes, ModelError> {
let modify = self.encode(meta.mtime, TimeField::Modification, path)?;
let mut access = self.encode(meta.atime, TimeField::Access, path)?;
let create = match meta.btime {
Some(btime) => self.encode(btime, TimeField::Birth, path)?,
None => modify,
};
access.tenth = 0;
let modify_precise = meta.mtime.nanos.is_multiple_of(10_000_000);
let birth_precise = meta
.btime
.is_none_or(|btime| btime.nanos.is_multiple_of(10_000_000));
let access_precise = meta.atime.secs % 2 == 0 && meta.atime.nanos == 0;
if !modify_precise || !birth_precise || !access_precise {
self.fidelity
.record(Direction::Dropped, path, Property::TimePrecision);
}
Ok(EntryTimes {
create,
modify,
access,
})
}
fn encode(
&self,
time: Timestamp,
field: TimeField,
path: &[u8],
) -> Result<DosTimestamp, ModelError> {
DosTimestamp::encode(time).ok_or_else(|| ModelError::TimeOutOfRange {
path: path.to_vec(),
field,
secs: time.secs,
min: DosTimestamp::SECS_MIN,
max: DosTimestamp::SECS_MAX,
})
}
fn record_losses(
&mut self,
meta: &Metadata,
xattrs: &[crate::xattr::Xattr],
darwin: Option<&Darwin>,
is_dir: bool,
path: &[u8],
) -> Result<(), ModelError> {
self.config
.loss
.record_losses(&mut self.fidelity, meta, xattrs, darwin, is_dir, path)
.map_err(|property| ModelError::LossNotAccepted {
path: path.to_vec(),
property,
})
}
fn lose(&mut self, property: Property, path: &[u8]) -> Result<(), ModelError> {
if !self.config.loss.accepts(property) {
return Err(ModelError::LossNotAccepted {
path: path.to_vec(),
property,
});
}
self.fidelity.record(Direction::Dropped, path, property);
Ok(())
}
}
#[derive(Debug)]
pub(crate) struct PlacedTree {
dirs: Vec<ModelDir>,
contents: Vec<FileContent>,
fidelity: FidelityReport,
}
impl PlacedTree {
pub(crate) fn allocate(&mut self, layout: &ExfatLayout) -> Result<u32, ModelError> {
self.check_directory_capacity()?;
self.allocate_clusters(layout)
}
pub(crate) fn content_sectors(&self, bytes_per_sector: u64) -> u64 {
let mut total = 0u64;
for (index, dir) in self.dirs.iter().enumerate() {
total = total.saturating_add(dir.bytes(index).div_ceil(bytes_per_sector));
for entry in &dir.entries {
if let Node::File { size, .. } = entry.node {
total = total.saturating_add(size.div_ceil(bytes_per_sector));
}
}
}
total
}
pub(crate) fn finish(self, used_clusters: u32) -> ExfatModel {
ExfatModel {
dirs: self.dirs,
contents: self.contents,
fidelity: self.fidelity,
used_clusters,
}
}
fn check_directory_capacity(&self) -> Result<(), ModelError> {
for (index, dir) in self.dirs.iter().enumerate() {
let needed = dir.bytes(index);
if needed > MAX_DIRECTORY_BYTES {
return Err(ModelError::DirectoryTooLarge {
path: dir.path.clone(),
needed,
limit: MAX_DIRECTORY_BYTES,
});
}
}
Ok(())
}
fn allocate_clusters(&mut self, layout: &ExfatLayout) -> Result<u32, ModelError> {
let per_cluster = u64::from(layout.bytes_per_cluster);
let available = layout.cluster_count;
let mut next = u64::from(layout.first_cluster_of_root);
let mut take = |count: u64| -> Result<ClusterRun, ModelError> {
let first = next;
next += count;
if next > u64::from(available) + u64::from(FIRST_CLUSTER) {
return Err(ModelError::VolumeFull {
needed: next - u64::from(FIRST_CLUSTER),
available,
});
}
Ok(ClusterRun {
first: if count == 0 { 0 } else { first as u32 },
count: count as u32,
})
};
for index in 0..self.dirs.len() {
let bytes = self.dirs[index].bytes(index);
self.dirs[index].run = take(bytes.div_ceil(per_cluster).max(1))?;
for at in 0..self.dirs[index].entries.len() {
if let Node::File { size, .. } = self.dirs[index].entries[at].node {
let run = take(size.div_ceil(per_cluster))?;
if let Node::File { run: slot, .. } = &mut self.dirs[index].entries[at].node {
*slot = run;
}
}
}
}
Ok((next - u64::from(FIRST_CLUSTER)) as u32)
}
}
impl ExfatModel {
pub(crate) fn entry_target(&self, node: Node, bytes_per_cluster: u32) -> (ClusterRun, u64) {
match node {
Node::Dir(index) => {
let run = self.dirs[index].run;
(run, u64::from(run.count) * u64::from(bytes_per_cluster))
}
Node::File { size, run, .. } => (run, size),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exfat::geometry::{PlanRequest, plan_layout};
use crate::fidelity::{AcceptedLoss, Synthesis};
use crate::source::{Source, TreeBuilder};
const TIME: Timestamp = Timestamp {
secs: 1_426_325_212,
nanos: 0,
};
fn layout() -> ExfatLayout {
plan_layout(&PlanRequest::new(32 << 20)).expect("a geometry")
}
fn upcase() -> UpcaseTable {
UpcaseTable::recommended()
}
fn config<'a>(upcase: &'a UpcaseTable) -> ModelConfig<'a> {
ModelConfig {
loss: LossPolicy {
accepted: AcceptedLoss::NONE,
synthesis: Synthesis::new(),
},
upcase,
}
}
fn model(source: impl Source) -> Result<ExfatModel, ModelError> {
let upcase = upcase();
build_model(source.into_entries(), &layout(), &config(&upcase))
}
#[test]
fn a_tree_becomes_directories_and_files_in_sorted_order() {
let m = model(
TreeBuilder::new()
.file(b"/zebra.txt".to_vec(), b"z", Metadata::new(0o644, TIME))
.directory(b"/dir".to_vec(), Metadata::new(0o755, TIME))
.file(b"/dir/apple.txt".to_vec(), b"a", Metadata::new(0o644, TIME))
.file(b"/alpha.txt".to_vec(), b"al", Metadata::new(0o644, TIME)),
)
.expect("a tree the format holds");
assert_eq!(m.dirs.len(), 2);
let names: Vec<String> = m.dirs[ROOT_DIR]
.entries
.iter()
.map(|e| String::from_utf16(&e.name.units).expect("well-formed"))
.collect();
assert_eq!(names, ["alpha.txt", "dir", "zebra.txt"]);
assert!(m.fidelity.is_faithful(), "nothing was lost");
assert_eq!(m.dirs[ROOT_DIR].run.first, layout().first_cluster_of_root);
assert!(m.dirs[1].run.count >= 1);
}
#[test]
fn allocation_is_contiguous_and_begins_where_the_format_left_off() {
let m = model(
TreeBuilder::new()
.file(b"/a".to_vec(), vec![0u8; 9_000], Metadata::new(0o644, TIME))
.file(b"/b".to_vec(), vec![0u8; 1], Metadata::new(0o644, TIME)),
)
.expect("a tree the format holds");
let layout = layout();
let mut expected = layout.first_cluster_of_root;
assert_eq!(m.dirs[ROOT_DIR].run.first, expected);
expected += m.dirs[ROOT_DIR].run.count;
for entry in &m.dirs[ROOT_DIR].entries {
let Node::File { run, .. } = entry.node else {
unreachable!("both entries are files")
};
assert_eq!(run.first, expected);
expected += run.count;
}
assert_eq!(m.used_clusters + FIRST_CLUSTER, expected);
assert_eq!(
m.dirs[ROOT_DIR].entries[0].node,
Node::File {
content: 0,
size: 9_000,
run: ClusterRun {
first: layout.first_cluster_of_root + 1,
count: 3
}
}
);
}
#[test]
fn an_empty_file_owns_no_cluster() {
let m = model(TreeBuilder::new().file(b"/empty".to_vec(), b"", Metadata::new(0o644, TIME)))
.expect("a tree the format holds");
let Node::File { run, size, .. } = m.dirs[ROOT_DIR].entries[0].node else {
unreachable!("a file")
};
assert_eq!(size, 0);
assert!(run.is_empty());
assert_eq!(run.first, 0, "the format says so with a zero");
}
#[test]
fn two_names_the_volumes_folding_makes_one_are_refused_with_both_paths_named() {
let err = model(
TreeBuilder::new()
.file(b"/README".to_vec(), b"a", Metadata::new(0o644, TIME))
.file(b"/readme".to_vec(), b"b", Metadata::new(0o644, TIME)),
)
.expect_err("a directory that cannot hold both");
assert!(matches!(err, ModelError::Indistinguishable { .. }), "{err}");
let message = err.to_string();
assert!(
message.contains("README") && message.contains("readme"),
"{message}"
);
assert!(
model(
TreeBuilder::new()
.directory(b"/d".to_vec(), Metadata::new(0o755, TIME))
.file(b"/README".to_vec(), b"a", Metadata::new(0o644, TIME))
.file(b"/d/readme".to_vec(), b"b", Metadata::new(0o644, TIME)),
)
.is_ok()
);
}
#[test]
fn the_folding_is_the_volumes_own_rather_than_the_hosts() {
let identity = UpcaseTable::new(&[crate::exfat::ondisk::UPCASE_IDENTITY_RUN, 0]);
let source = TreeBuilder::new()
.file(b"/README".to_vec(), b"a", Metadata::new(0o644, TIME))
.file(b"/readme".to_vec(), b"b", Metadata::new(0o644, TIME));
assert!(
build_model(source.into_entries(), &layout(), &config(&identity)).is_ok(),
"a volume that folds nothing distinguishes them"
);
}
#[test]
fn a_property_the_format_cannot_carry_refuses_until_it_is_accepted() {
let source = TreeBuilder::new().file(
b"/owned".to_vec(),
b"x",
Metadata {
uid: 1000,
gid: 1000,
..Metadata::new(0o644, TIME)
},
);
let err = model(source.clone()).expect_err("ownership has nowhere to go");
assert!(matches!(
err,
ModelError::LossNotAccepted {
property: Property::Ownership,
..
}
));
let upcase = upcase();
let m = build_model(
source.into_entries(),
&layout(),
&ModelConfig {
loss: LossPolicy {
accepted: AcceptedLoss::NONE.and(Property::Ownership),
..config(&upcase).loss
},
..config(&upcase)
},
)
.expect("accepted");
assert!(!m.fidelity.is_faithful());
assert_eq!(m.fidelity.count(Direction::Dropped, Property::Ownership), 1);
}
#[test]
fn a_conventionally_moded_root_owned_tree_loses_nothing() {
let m = model(
TreeBuilder::new()
.directory(b"/etc".to_vec(), Metadata::new(0o755, TIME))
.file(
b"/etc/hostname".to_vec(),
b"host\n",
Metadata::new(0o644, TIME),
),
)
.expect("a tree the format holds");
assert!(m.fidelity.is_faithful());
assert!(m.fidelity.records().is_empty());
}
#[test]
fn a_read_only_file_keeps_its_mode_through_the_one_bit_the_format_has() {
let m = model(TreeBuilder::new().file(b"/ro".to_vec(), b"x", Metadata::new(0o444, TIME)))
.expect("a tree the format holds");
assert!(
m.dirs[ROOT_DIR].entries[0]
.attributes
.contains(FileAttributes::READ_ONLY)
);
assert!(
m.fidelity.is_faithful(),
"the write bits a driver clears are the mode that was asked for"
);
}
#[test]
fn the_precision_a_time_loses_is_recorded_and_never_refuses() {
let odd = Timestamp {
secs: TIME.secs + 1,
nanos: 0,
};
assert_eq!(odd.secs % 2, 1);
let m = model(TreeBuilder::new().file(b"/f".to_vec(), b"x", Metadata::new(0o644, odd)))
.expect("recorded, not refused");
assert_eq!(
m.fidelity
.count(Direction::Dropped, Property::TimePrecision),
1
);
let entry = &m.dirs[ROOT_DIR].entries[0];
assert_eq!(
entry.times.modify.tenth, 100,
"the odd second rides in the hundredths"
);
assert_eq!(
entry.times.access.tenth, 0,
"the access field has no such byte"
);
assert_eq!(
entry.times.create, entry.times.modify,
"a creation time is derived"
);
let m = model(TreeBuilder::new().file(b"/f".to_vec(), b"x", Metadata::new(0o644, TIME)))
.expect("a tree the format holds");
assert!(m.fidelity.is_faithful());
let hundredth = Timestamp {
secs: TIME.secs,
nanos: 370_000_000,
};
let m = model(TreeBuilder::new().file(
b"/f".to_vec(),
b"x",
Metadata {
atime: TIME,
..Metadata::new(0o644, hundredth)
},
))
.expect("a tree the format holds");
assert!(m.fidelity.is_faithful());
assert_eq!(m.dirs[ROOT_DIR].entries[0].times.modify.tenth, 37);
}
#[test]
fn a_birth_time_is_held_to_the_exfat_creation_field() {
let born = Timestamp {
secs: TIME.secs + 1,
nanos: 230_000_000,
};
let file = |meta: Metadata| TreeBuilder::new().file(b"/f".to_vec(), b"x", meta);
let m = model(file(Metadata::new(0o644, TIME).with_birth_time(born))).expect("held");
assert!(m.fidelity.is_faithful());
let times = m.dirs[ROOT_DIR].entries[0].times;
assert_eq!(times.create, DosTimestamp::encode(born).expect("in range"));
assert_eq!(times.create.tenth, 123, "the odd second and the fraction");
assert_eq!(times.modify, DosTimestamp::encode(TIME).expect("in range"));
let finer = Timestamp { nanos: 1, ..born };
let m = model(file(Metadata::new(0o644, TIME).with_birth_time(finer))).expect("held");
assert_eq!(
m.fidelity
.count(Direction::Dropped, Property::TimePrecision),
1
);
let err = model(file(
Metadata::new(0o644, TIME).with_birth_time(Timestamp::from_secs(0)),
))
.expect_err("outside the range");
assert!(
matches!(
err,
ModelError::TimeOutOfRange {
field: TimeField::Birth,
..
}
),
"{err:?}"
);
}
#[test]
fn an_instant_outside_the_range_is_refused_by_field_rather_than_wrapped() {
for (meta, field) in [
(
Metadata::new(0o644, Timestamp::from_secs(0)),
TimeField::Modification,
),
(
Metadata {
atime: Timestamp::from_secs(DosTimestamp::SECS_MAX + 1),
..Metadata::new(0o644, TIME)
},
TimeField::Access,
),
] {
let err = model(TreeBuilder::new().file(b"/f".to_vec(), b"x", meta))
.expect_err("outside the range");
assert!(
matches!(err, ModelError::TimeOutOfRange { field: f, .. } if f == field),
"{err}"
);
}
}
#[test]
fn a_hard_link_is_written_as_a_second_copy_and_says_so() {
let upcase = upcase();
let m = build_model(
TreeBuilder::new()
.file(b"/a".to_vec(), b"contents", Metadata::new(0o644, TIME))
.hardlink(b"/b".to_vec(), b"/a".to_vec(), Metadata::new(0o644, TIME))
.into_entries(),
&layout(),
&ModelConfig {
loss: LossPolicy {
accepted: AcceptedLoss::NONE.and(Property::Kind),
..config(&upcase).loss
},
..config(&upcase)
},
)
.expect("accepted");
let runs: Vec<_> = m.dirs[ROOT_DIR]
.entries
.iter()
.map(|e| match e.node {
Node::File { content, run, .. } => (content, run),
Node::Dir(_) => unreachable!("both are files"),
})
.collect();
assert_eq!(runs[0].0, runs[1].0, "one content");
assert_ne!(runs[0].1.first, runs[1].1.first, "two allocations");
assert_eq!(m.fidelity.count(Direction::Dropped, Property::Kind), 1);
}
#[test]
fn a_shape_no_filesystem_has_is_refused_by_name() {
let dup = TreeBuilder::new()
.file(b"/a".to_vec(), b"x", Metadata::new(0o644, TIME))
.file(b"//a".to_vec(), b"y", Metadata::new(0o644, TIME));
assert!(matches!(
model(dup).expect_err("one path twice"),
ModelError::Duplicate { .. }
));
let orphan = TreeBuilder::new().file(b"/d/f".to_vec(), b"x", Metadata::new(0o644, TIME));
assert!(matches!(
model(orphan).expect_err("no parent"),
ModelError::ParentMissing { .. }
));
let under_file = TreeBuilder::new()
.file(b"/f".to_vec(), b"x", Metadata::new(0o644, TIME))
.file(b"/f/g".to_vec(), b"y", Metadata::new(0o644, TIME));
assert!(matches!(
model(under_file).expect_err("a file is not a directory"),
ModelError::ParentNotDir { .. }
));
let ascending = TreeBuilder::new()
.directory(b"/d".to_vec(), Metadata::new(0o755, TIME))
.file(b"/d/../f".to_vec(), b"x", Metadata::new(0o644, TIME));
assert!(matches!(
model(ascending).expect_err("a path is not a traversal"),
ModelError::InvalidComponent { .. }
));
let root_file = TreeBuilder::new().file(b"/".to_vec(), b"x", Metadata::new(0o644, TIME));
assert!(matches!(
model(root_file).expect_err("the root is a directory"),
ModelError::RootNotDirectory { .. }
));
}
#[test]
fn a_tree_larger_than_the_volume_is_refused_before_anything_is_written() {
let mut source = TreeBuilder::new();
for n in 0..40u32 {
source = source.file(
format!("/f{n}").into_bytes(),
vec![0u8; 1 << 20],
Metadata::new(0o644, TIME),
);
}
assert!(matches!(
model(source).expect_err("forty megabytes into thirty-two"),
ModelError::VolumeFull { .. }
));
}
#[test]
fn the_root_carries_the_four_entries_a_format_writes_ahead_of_the_tree() {
let empty = model(TreeBuilder::new()).expect("an empty tree");
assert!(empty.dirs[ROOT_DIR].entries.is_empty());
assert_eq!(
empty.dirs[ROOT_DIR].run.count, 1,
"an empty root is one cluster"
);
let one = model(TreeBuilder::new().file(b"/f".to_vec(), b"x", Metadata::new(0o644, TIME)))
.expect("a tree the format holds");
assert_eq!(
one.dirs[ROOT_DIR].bytes(ROOT_DIR),
u64::from(ROOT_LEADING_SLOTS + 3) * DIR_ENTRY_SIZE as u64
);
}
#[test]
fn a_directory_larger_than_the_format_holds_is_refused_by_path() {
let mut placed = Builder::new(&config(&upcase()))
.place_all(
TreeBuilder::new()
.directory(b"/d".to_vec(), Metadata::new(0o755, TIME))
.into_entries(),
)
.expect("a tree");
placed.dirs[1].entries = std::iter::repeat_with(|| ModelEntry {
name: PlacedName {
units: vec![u16::from(b'a'); 255],
hash: 0,
},
attributes: FileAttributes::ARCHIVE,
times: EntryTimes::default(),
node: Node::File {
content: 0,
size: 0,
run: ClusterRun::default(),
},
})
.take((MAX_DIRECTORY_ENTRIES / 19) as usize + 1)
.collect();
let err = placed
.allocate(&layout())
.expect_err("too large a directory");
assert!(
matches!(err, ModelError::DirectoryTooLarge { limit, .. } if limit == MAX_DIRECTORY_BYTES),
"{err}"
);
assert!(err.to_string().contains("/d"), "{err}");
}
#[test]
fn two_models_of_one_tree_are_the_same_model() {
let forward = model(
TreeBuilder::new()
.directory(b"/d".to_vec(), Metadata::new(0o755, TIME))
.file(b"/d/a".to_vec(), b"a", Metadata::new(0o644, TIME))
.file(b"/z".to_vec(), b"z", Metadata::new(0o644, TIME)),
)
.expect("a tree");
let shuffled = model(
TreeBuilder::new()
.file(b"/z".to_vec(), b"z", Metadata::new(0o644, TIME))
.file(b"/d/a".to_vec(), b"a", Metadata::new(0o644, TIME))
.directory(b"/d".to_vec(), Metadata::new(0o755, TIME)),
)
.expect("a tree");
assert_eq!(forward.dirs, shuffled.dirs);
assert_eq!(forward.used_clusters, shuffled.used_clusters);
}
}