use std::io::{Seek, Write};
use std::num::NonZeroU16;
use crate::fidelity::{AcceptedLoss, FidelityReport, LossPolicy, Property, Synthesis};
use crate::io::ByteSink;
use crate::sizing::Slack;
use crate::source::Source;
use crate::time::{DosTimestamp, Timestamp};
use super::geometry::{FatLayout, FatType, GeometryError, PlanRequest, plan_layout};
use super::model::{EntryTimes, FatModel, ModelConfig, ModelError, Node, build_model, place_tree};
use super::ondisk::{
Attributes, BootSector, BootSectorTail, DIR_ENTRY_SIZE, DirEntry, EXTENDED_BOOT_SIGNATURE,
Fat32Params, FsInfo, ParseError, VolumeInfo,
};
use super::table;
pub const DEFAULT_OEM_NAME: [u8; 8] = *b"ferrosys";
pub const MEDIA_FIXED: u8 = 0xF8;
pub const MEDIA_REMOVABLE: u8 = 0xF0;
pub(super) const fn is_media_descriptor(media: u8) -> bool {
media == MEDIA_REMOVABLE || media >= MEDIA_FIXED
}
const DRIVE_FIXED: u8 = 0x80;
const DRIVE_REMOVABLE: u8 = 0x00;
const BOOT_CODE_OFFSET_FAT1216: usize = 62;
const BOOT_CODE_OFFSET_FAT32: usize = 90;
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct VolumeLabel([u8; VolumeLabel::LEN]);
impl VolumeLabel {
pub const LEN: usize = 11;
pub const NO_NAME: Self = Self(*b"NO NAME ");
pub fn new(name: &str) -> Result<Self, LabelError> {
Self::from_bytes(name.as_bytes())
}
pub fn from_bytes(name: &[u8]) -> Result<Self, LabelError> {
if name.is_empty() {
return Err(LabelError::Empty);
}
if name.len() > Self::LEN {
return Err(LabelError::TooLong {
bytes: name.len(),
limit: Self::LEN,
});
}
let mut label = [b' '; Self::LEN];
for (at, &byte) in name.iter().enumerate() {
let byte = byte.to_ascii_uppercase();
if !byte_is_allowed(byte, at) {
return Err(LabelError::InvalidByte { byte, at });
}
label[at] = byte;
}
Ok(Self(label))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; Self::LEN] {
&self.0
}
}
fn byte_is_allowed(byte: u8, at: usize) -> bool {
const RESERVED: &[u8] = b"\"*+,./:;<=>?[\\]|";
if byte < 0x20 || RESERVED.contains(&byte) || (at == 0 && byte == b' ') {
return false;
}
!(at == 0 && byte == super::ondisk::NAME_DELETED)
}
impl core::fmt::Debug for VolumeLabel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match core::str::from_utf8(&self.0) {
Ok(text) => write!(f, "VolumeLabel({:?})", text.trim_end()),
Err(_) => write!(f, "VolumeLabel({:02x?})", self.0),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LabelError {
#[error("volume label of {bytes} bytes exceeds the {limit} the format holds")]
#[non_exhaustive]
TooLong {
bytes: usize,
limit: usize,
},
#[error("a volume label of no bytes is no label: leave the label unset")]
Empty,
#[error("byte {byte:#04x} at position {at} is not one a volume label may contain")]
#[non_exhaustive]
InvalidByte {
byte: u8,
at: usize,
},
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct BootCode {
bytes: [u8; BootCode::MAX_BYTES],
len: u16,
}
impl BootCode {
pub const MAX_BYTES: usize = 448;
pub const MAX_BYTES_FAT32: usize = 420;
pub const NONE: Self = Self {
bytes: [0; Self::MAX_BYTES],
len: 0,
};
pub fn new(code: &[u8]) -> Result<Self, FormatError> {
if code.len() > Self::MAX_BYTES {
return Err(FormatError::BootCodeTooLong {
bytes: code.len(),
limit: Self::MAX_BYTES,
});
}
let mut bytes = [0u8; Self::MAX_BYTES];
bytes[..code.len()].copy_from_slice(code);
Ok(Self {
bytes,
len: code.len() as u16,
})
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len as usize]
}
#[must_use]
pub const fn capacity(fat_type: FatType) -> usize {
match fat_type {
FatType::Fat32 => Self::MAX_BYTES_FAT32,
_ => Self::MAX_BYTES,
}
}
}
impl Default for BootCode {
fn default() -> Self {
Self::NONE
}
}
impl core::fmt::Debug for BootCode {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "BootCode({} bytes)", self.len)
}
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct FormatOptions {
pub volume_id: u32,
pub time: Timestamp,
pub label: Option<VolumeLabel>,
pub oem_name: [u8; 8],
pub media: u8,
pub hidden_sectors: u32,
pub disk_geometry: DiskGeometry,
pub boot_code: BootCode,
pub plan: PlanRequest,
pub accepted_loss: AcceptedLoss,
pub synthesis: Synthesis,
}
impl FormatOptions {
#[must_use]
pub const fn new(volume_id: u32, time: Timestamp) -> Self {
Self {
volume_id,
time,
label: None,
oem_name: DEFAULT_OEM_NAME,
media: MEDIA_FIXED,
hidden_sectors: 0,
disk_geometry: DiskGeometry::Auto,
boot_code: BootCode::NONE,
plan: PlanRequest::new(0),
accepted_loss: AcceptedLoss::NONE,
synthesis: Synthesis::new(),
}
}
#[must_use]
pub const fn label(mut self, label: VolumeLabel) -> Self {
self.label = Some(label);
self
}
#[must_use]
pub const fn accept_loss(mut self, property: Property) -> Self {
self.accepted_loss = self.accepted_loss.and(property);
self
}
#[must_use]
pub const fn accept_all_loss(mut self) -> Self {
self.accepted_loss = AcceptedLoss::ALL;
self
}
#[must_use]
pub const fn synthesis(mut self, synthesis: Synthesis) -> Self {
self.synthesis = synthesis;
self
}
pub(crate) const fn model_config(&self) -> ModelConfig {
ModelConfig {
loss: LossPolicy {
accepted: self.accepted_loss,
synthesis: self.synthesis,
},
has_label: self.label.is_some(),
}
}
#[must_use]
pub const fn plan(mut self, plan: PlanRequest) -> Self {
self.plan = plan;
self
}
#[must_use]
pub const fn boot_code(mut self, boot_code: BootCode) -> Self {
self.boot_code = boot_code;
self
}
#[must_use]
pub const fn disk_geometry(mut self, disk_geometry: DiskGeometry) -> Self {
self.disk_geometry = disk_geometry;
self
}
const fn drive_number(&self) -> u8 {
if self.media == MEDIA_FIXED {
DRIVE_FIXED
} else {
DRIVE_REMOVABLE
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FormatError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Geometry(#[from] GeometryError),
#[error(transparent)]
Model(#[from] ModelError),
#[error(transparent)]
Parse(#[from] ParseError),
#[error("boot code of {bytes} bytes exceeds the {limit} the boot sector holds")]
#[non_exhaustive]
BootCodeTooLong {
bytes: usize,
limit: usize,
},
#[error(
"a format time of {secs} seconds past the epoch is outside the {min} to {max} a FAT \
directory entry represents"
)]
#[non_exhaustive]
TimeOutOfRange {
secs: i64,
min: i64,
max: i64,
},
#[error("directory {index} serializes to {bytes} bytes and was planned {capacity}")]
#[non_exhaustive]
DirectoryOverflowsItsClusters {
index: usize,
bytes: u64,
capacity: u64,
},
#[error(
"a media descriptor of {media:#04x} is not a value a FAT volume's parameter block \
carries"
)]
#[non_exhaustive]
MediaDescriptorUndefined {
media: u8,
},
#[error("slack of {hundredths} hundredths of a percent is past the limit of {limit}")]
#[non_exhaustive]
SlackShareTooLarge {
hundredths: u16,
limit: u16,
},
#[error("no volume up to {ceiling} bytes holds the tree with the room asked for")]
#[non_exhaustive]
DoesNotFit {
ceiling: u64,
},
#[error("an image of {bytes} bytes cannot be held in memory on this machine")]
#[non_exhaustive]
ImageTooLargeInMemory {
bytes: u64,
},
}
pub struct Image {
bytes: Vec<u8>,
layout: FatLayout,
fidelity: FidelityReport,
}
impl Image {
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
#[must_use]
pub fn layout(&self) -> &FatLayout {
&self.layout
}
#[must_use]
pub fn fidelity(&self) -> &FidelityReport {
&self.fidelity
}
pub fn write_to(&self, mut w: impl Write) -> std::io::Result<()> {
w.write_all(&self.bytes)
}
}
pub struct FormatPlan {
layout: FatLayout,
volume_bytes: u64,
options: FormatOptions,
model: FatModel,
}
impl FormatPlan {
pub fn new(
source: impl Source,
volume_bytes: u64,
options: FormatOptions,
) -> Result<Self, FormatError> {
let layout = plan(volume_bytes, &options)?;
let model = build_model(source.into_entries(), &layout, &options.model_config())?;
Ok(Self {
layout,
volume_bytes,
options,
model,
})
}
pub fn fit(
source: impl Source,
options: FormatOptions,
slack: Slack,
) -> Result<Self, FormatError> {
let mut tree = place_tree(source.into_entries(), &options.model_config())?;
let fitted = crate::fat::fit::search(&mut tree, &options, slack)?;
let volume_bytes =
u64::from(fitted.layout.total_sectors) * u64::from(fitted.layout.bytes_per_sector);
Ok(Self {
layout: fitted.layout,
volume_bytes,
options,
model: tree.finish(fitted.used_clusters, fitted.next_free),
})
}
#[must_use]
pub const fn free_clusters(&self) -> u32 {
self.layout.clusters - self.model.used_clusters
}
#[must_use]
pub fn layout(&self) -> &FatLayout {
&self.layout
}
#[must_use]
pub const fn volume_bytes(&self) -> u64 {
self.volume_bytes
}
#[must_use]
pub fn fidelity(&self) -> &FidelityReport {
&self.model.fidelity
}
pub fn write_to(&self, sink: impl Write + Seek) -> Result<FatLayout, FormatError> {
write_volume(
&self.layout,
self.volume_bytes,
&self.options,
&self.model,
sink,
)?;
Ok(self.layout)
}
}
pub fn format(
source: impl Source,
volume_bytes: u64,
options: FormatOptions,
) -> Result<Image, FormatError> {
let plan = FormatPlan::new(source, volume_bytes, options)?;
let bytes = plan.volume_bytes.max(plan.layout.total_bytes());
let buffer =
crate::io::image_buffer(bytes).ok_or(FormatError::ImageTooLargeInMemory { bytes })?;
let mut sink = std::io::Cursor::new(buffer);
let layout = plan.write_to(&mut sink)?;
Ok(Image {
bytes: sink.into_inner(),
layout,
fidelity: plan.model.fidelity,
})
}
pub fn format_to(
source: impl Source,
volume_bytes: u64,
options: FormatOptions,
sink: impl Write + Seek,
) -> Result<FormatPlan, FormatError> {
let plan = FormatPlan::new(source, volume_bytes, options)?;
plan.write_to(sink)?;
Ok(plan)
}
fn plan(volume_bytes: u64, options: &FormatOptions) -> Result<FatLayout, FormatError> {
if !is_media_descriptor(options.media) {
return Err(FormatError::MediaDescriptorUndefined {
media: options.media,
});
}
let mut request = options.plan;
request.volume_bytes = volume_bytes;
let layout = plan_layout(&request)?;
let capacity = BootCode::capacity(layout.fat_type);
let code = options.boot_code.as_bytes().len();
if code > capacity {
return Err(FormatError::BootCodeTooLong {
bytes: code,
limit: capacity,
});
}
if DosTimestamp::encode(options.time).is_none() {
return Err(FormatError::TimeOutOfRange {
secs: options.time.secs,
min: DosTimestamp::SECS_MIN,
max: DosTimestamp::SECS_MAX,
});
}
Ok(layout)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum DiskGeometry {
#[default]
Auto,
Exactly {
sectors_per_track: NonZeroU16,
heads: NonZeroU16,
},
}
impl DiskGeometry {
const fn resolve(self, total_sectors: u32) -> (u16, u16) {
match self {
DiskGeometry::Auto => chs(total_sectors),
DiskGeometry::Exactly {
sectors_per_track,
heads,
} => (sectors_per_track.get(), heads.get()),
}
}
}
const CHS_SMALL_MEDIA_SECTORS: u32 = 524_288;
const fn chs(total_sectors: u32) -> (u16, u16) {
if total_sectors <= CHS_SMALL_MEDIA_SECTORS {
let heads: u16 = if total_sectors <= 32_768 {
2
} else if total_sectors <= 65_536 {
4
} else if total_sectors <= 262_144 {
8
} else {
16
};
let sectors_per_track: u16 = if total_sectors <= 4096 { 16 } else { 32 };
return (sectors_per_track, heads);
}
const PER_HEAD: u32 = 63 * 1024;
let heads: u16 = if total_sectors <= 16 * PER_HEAD {
16
} else if total_sectors <= 32 * PER_HEAD {
32
} else if total_sectors <= 64 * PER_HEAD {
64
} else if total_sectors <= 128 * PER_HEAD {
128
} else {
255
};
(63, heads)
}
const TABLE_BATCH: u32 = 4096;
fn write_volume(
layout: &FatLayout,
volume_bytes: u64,
options: &FormatOptions,
model: &FatModel,
sink: impl Write + Seek,
) -> Result<(), FormatError> {
let mut sink = ByteSink::new(sink);
let sector_bytes = layout.bytes_per_sector as usize;
let at = |sector: u32| u64::from(sector) * u64::from(layout.bytes_per_sector);
let mut boot = vec![0u8; sector_bytes];
boot_sector(layout, options).write_to(&mut boot)?;
let code = options.boot_code.as_bytes();
let code_offset = match layout.fat_type {
FatType::Fat32 => BOOT_CODE_OFFSET_FAT32,
_ => BOOT_CODE_OFFSET_FAT1216,
};
boot[code_offset..code_offset + code.len()].copy_from_slice(code);
sink.write_at(0, &boot)?;
if let Some(fat32) = layout.fat32 {
let mut info = vec![0u8; sector_bytes];
FsInfo {
free_clusters: Some(layout.clusters - model.used_clusters),
next_free_cluster: (model.next_free < layout.clusters + 2).then_some(model.next_free),
}
.write_to(&mut info)?;
sink.write_at(at(u32::from(fat32.fs_info_sector)), &info)?;
if let Some(backup) = fat32.backup_boot_sector {
sink.write_at(at(u32::from(backup)), &boot)?;
if let Some(backup_info) = fat32.backup_fs_info_sector {
sink.write_at(at(u32::from(backup_info)), &info)?;
}
}
}
write_tables(layout, options, model, &mut sink)?;
write_tree(layout, options, model, &mut sink)?;
sink.extend_to(volume_bytes.max(layout.total_bytes()))?;
Ok(())
}
fn write_tables<W: Write + Seek>(
layout: &FatLayout,
options: &FormatOptions,
model: &FatModel,
sink: &mut ByteSink<W>,
) -> Result<(), FormatError> {
let kind = layout.fat_type;
let span = table::entry_span(kind);
let ends = model.chain_ends();
for start in (0..model.next_free.max(2)).step_by(TABLE_BATCH as usize) {
let end = (start + TABLE_BATCH).min(model.next_free.max(2));
let base = table::entry_offset(kind, start);
let len = table::entry_offset(kind, end - 1 - start) + span;
assert!(
base + len <= u64::from(layout.fat_sectors) * u64::from(layout.bytes_per_sector),
"a table batch ending at {} runs past a table of {} sectors",
base + len,
layout.fat_sectors
);
let mut batch = vec![0u8; len as usize];
for cluster in start..end {
let value = match cluster {
0 => table::media_entry(kind, options.media),
1 => table::tail_entry(kind),
_ if ends.binary_search(&cluster).is_ok() => table::end_of_chain(kind),
_ => cluster + 1,
};
let wrote = table::write_entry(kind, &mut batch, cluster - start, value);
assert!(wrote, "entry {cluster} did not fit the batch sized for it");
}
for copy in 0..layout.fats {
let table_start = layout
.fat_start_sector(copy)
.expect("every copy below the table count has a start sector");
sink.write_at(at_sector(layout, table_start) + base, &batch)?;
}
}
Ok(())
}
fn write_tree<W: Write + Seek>(
layout: &FatLayout,
options: &FormatOptions,
model: &FatModel,
sink: &mut ByteSink<W>,
) -> Result<(), FormatError> {
for (index, dir) in model.dirs.iter().enumerate() {
let bytes = directory_bytes(model, options, index)?;
if !bytes.is_empty() {
let (start, capacity) = match (index, layout.fat32) {
(0, None) => (
layout
.root_dir_start_sector()
.expect("a volume that is not FAT32 has a root directory region"),
u64::from(layout.root_entries) * DIR_ENTRY_SIZE as u64,
),
_ => (
layout
.cluster_start_sector(dir.run.first)
.expect("a planned directory cluster is one the volume has"),
u64::from(dir.run.count) * u64::from(layout.bytes_per_cluster()),
),
};
if bytes.len() as u64 > capacity {
return Err(FormatError::DirectoryOverflowsItsClusters {
index,
bytes: bytes.len() as u64,
capacity,
});
}
sink.write_at(at_sector(layout, start), &bytes)?;
}
for entry in &dir.entries {
let Node::File { content, size, run } = entry.node else {
continue;
};
if run.is_empty() {
continue;
}
let content = &model.contents[content];
assert_eq!(
content.len(),
u64::from(size),
"a file's contents are not the length its entry records"
);
let start = layout
.cluster_start_sector(run.first)
.expect("a planned file cluster is one the volume has");
let at = at_sector(layout, start);
content.for_each_window(|offset, bytes| sink.write_at(at + offset, bytes))?;
}
}
Ok(())
}
fn at_sector(layout: &FatLayout, sector: u32) -> u64 {
u64::from(sector) * u64::from(layout.bytes_per_sector)
}
fn directory_bytes(
model: &FatModel,
options: &FormatOptions,
index: usize,
) -> Result<Vec<u8>, FormatError> {
let dir = &model.dirs[index];
let mut out = Vec::new();
if index == 0 {
if let Some(label) = options.label {
push_entry(&mut out, &label_entry(label, options.time))?;
}
} else {
let parent = dir.parent.expect("only the root has no parent");
let parent_cluster = if parent == 0 {
0
} else {
model.dirs[parent].run.first
};
push_entry(
&mut out,
&dot_entry(b". ", dir.run.first, dir.times),
)?;
push_entry(
&mut out,
&dot_entry(b".. ", parent_cluster, dir.times),
)?;
}
for entry in &dir.entries {
for lfn in entry.name.lfn_entries() {
let at = out.len();
out.resize(at + DIR_ENTRY_SIZE, 0);
lfn.write_to(&mut out[at..])?;
}
let (cluster, size) = model.entry_target(entry.node);
push_entry(
&mut out,
&DirEntry {
name: entry.name.short,
attributes: entry.attributes,
case_flags: 0,
create_time_tenth: entry.times.create.tenth,
create_time: entry.times.create.time,
create_date: entry.times.create.date,
access_date: entry.times.access_date,
first_cluster_hi: (cluster >> 16) as u16,
write_time: entry.times.write.time,
write_date: entry.times.write.date,
first_cluster_lo: cluster as u16,
size,
},
)?;
}
Ok(out)
}
fn push_entry(out: &mut Vec<u8>, entry: &DirEntry) -> Result<(), FormatError> {
let at = out.len();
out.resize(at + DIR_ENTRY_SIZE, 0);
entry.write_to(&mut out[at..])?;
Ok(())
}
fn dot_entry(name: &[u8; 11], cluster: u32, times: EntryTimes) -> DirEntry {
DirEntry {
name: *name,
attributes: Attributes::DIRECTORY,
case_flags: 0,
create_time_tenth: times.create.tenth,
create_time: times.create.time,
create_date: times.create.date,
access_date: times.access_date,
first_cluster_hi: (cluster >> 16) as u16,
write_time: times.write.time,
write_date: times.write.date,
first_cluster_lo: cluster as u16,
size: 0,
}
}
fn boot_sector(layout: &FatLayout, options: &FormatOptions) -> BootSector {
assert!(
u16::try_from(layout.bytes_per_sector).is_ok()
&& u8::try_from(layout.sectors_per_cluster).is_ok()
&& u16::try_from(layout.reserved_sectors).is_ok()
&& u8::try_from(layout.fats).is_ok()
&& u16::try_from(layout.root_entries).is_ok()
&& (layout.fat32.is_some() || u16::try_from(layout.fat_sectors).is_ok()),
"a planned field does not fit the boot sector field that records it: {layout:?}"
);
let (sectors_per_track, heads) = options.disk_geometry.resolve(layout.total_sectors);
let volume = VolumeInfo {
drive_number: options.drive_number(),
reserved: 0,
ext_boot_signature: EXTENDED_BOOT_SIGNATURE,
volume_id: options.volume_id,
label: *options.label.unwrap_or(VolumeLabel::NO_NAME).as_bytes(),
fs_type: layout.fat_type.label(),
};
let (total_16, total_32) = match u16::try_from(layout.total_sectors) {
Ok(small) => (small, 0),
Err(_) => (0, layout.total_sectors),
};
let (fat_sectors_16, tail) = match layout.fat32 {
Some(fat32) => (
0,
BootSectorTail::Fat32 {
params: Fat32Params {
fat_sectors: layout.fat_sectors,
ext_flags: 0,
version: 0,
root_cluster: fat32.root_cluster,
fs_info_sector: fat32.fs_info_sector,
backup_boot_sector: fat32.backup_boot_sector.unwrap_or(0),
},
volume,
},
),
None => (
layout.fat_sectors as u16,
BootSectorTail::Fat1216 { volume },
),
};
BootSector {
jump: [
0xEB,
match layout.fat_type {
FatType::Fat32 => (BOOT_CODE_OFFSET_FAT32 - 2) as u8,
_ => (BOOT_CODE_OFFSET_FAT1216 - 2) as u8,
},
0x90,
],
oem_name: options.oem_name,
bytes_per_sector: layout.bytes_per_sector as u16,
sectors_per_cluster: layout.sectors_per_cluster as u8,
reserved_sectors: layout.reserved_sectors as u16,
fats: layout.fats as u8,
root_entries: layout.root_entries as u16,
total_sectors_16: total_16,
media: options.media,
fat_sectors_16,
sectors_per_track,
heads,
hidden_sectors: options.hidden_sectors,
total_sectors_32: total_32,
tail,
}
}
fn label_entry(label: VolumeLabel, time: Timestamp) -> DirEntry {
let stamp = DosTimestamp::encode(time).unwrap_or_default();
DirEntry {
name: *label.as_bytes(),
attributes: Attributes::VOLUME_ID,
case_flags: 0,
create_time_tenth: stamp.tenth,
create_time: stamp.time,
create_date: stamp.date,
access_date: stamp.date,
first_cluster_hi: 0,
write_time: stamp.time,
write_date: stamp.date,
first_cluster_lo: 0,
size: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fat::ondisk::{BOOT_SIGNATURE, LfnEntry};
use crate::fat::{ClusterSize, FatTypeRequest, ReservedSectors};
use crate::source::TreeBuilder;
const TIME: Timestamp = Timestamp::from_secs(1_426_325_212);
fn options() -> FormatOptions {
FormatOptions::new(0x1234_abcd, TIME)
}
fn image(mib: u64, request: FatTypeRequest) -> Image {
let opts = options().plan(PlanRequest::new(0).fat_type(request));
format(TreeBuilder::new(), mib << 20, opts).expect("format")
}
#[test]
fn a_formatted_volume_is_exactly_the_size_it_was_asked_for() {
for mib in [1u64, 8, 64, 512] {
let image = image(mib, FatTypeRequest::Auto);
assert_eq!(
image.as_bytes().len() as u64,
mib << 20,
"{mib} MiB: the image is not the size of the volume"
);
assert_eq!(image.layout().total_bytes(), mib << 20);
}
}
#[test]
fn a_shortened_filesystem_still_fills_the_destination_it_was_given() {
let asked = 2_120_704u64;
let opts = options().plan(PlanRequest::new(0).cluster_size(ClusterSize::Sectors(1)));
let plan = FormatPlan::new(TreeBuilder::new(), asked, opts).expect("plan");
assert_eq!(plan.volume_bytes(), asked);
assert!(
plan.layout().total_bytes() < asked,
"the fixture is not in the step-down range: {} bytes",
plan.layout().total_bytes()
);
let image = format(TreeBuilder::new(), asked, opts).expect("format");
assert_eq!(image.as_bytes().len() as u64, asked);
let mut sink = std::io::Cursor::new(Vec::new());
format_to(TreeBuilder::new(), asked, opts, &mut sink).expect("format_to");
let streamed = sink.into_inner();
assert_eq!(streamed.len() as u64, asked);
assert_eq!(streamed, image.as_bytes());
let boot = BootSector::read_from(image.as_bytes()).expect("read the boot sector");
let described = u64::from(boot.total_sectors()) * u64::from(boot.bytes_per_sector);
assert_eq!(described, plan.layout().total_bytes());
assert!(
image.as_bytes()[described as usize..]
.iter()
.all(|b| *b == 0)
);
let mut r = crate::fat::Reader::open(std::io::Cursor::new(image.as_bytes()))
.expect("a strict open");
assert_eq!(r.layout(), plan.layout());
assert!(r.scan().is_clean());
}
#[test]
fn the_boot_sector_reads_back_as_the_layout_it_describes() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let image = image(mib, request);
let layout = *image.layout();
let boot = BootSector::read_from(image.as_bytes()).expect("read the boot sector");
let what = layout.fat_type;
assert_eq!(u32::from(boot.bytes_per_sector), layout.bytes_per_sector);
assert_eq!(
u32::from(boot.sectors_per_cluster),
layout.sectors_per_cluster
);
assert_eq!(u32::from(boot.reserved_sectors), layout.reserved_sectors);
assert_eq!(u32::from(boot.fats), layout.fats);
assert_eq!(u32::from(boot.root_entries), layout.root_entries);
assert_eq!(boot.total_sectors(), layout.total_sectors, "{what}");
assert_eq!(boot.fat_sectors(), layout.fat_sectors, "{what}");
assert_eq!(boot.media, MEDIA_FIXED);
let root_sectors =
(u32::from(boot.root_entries) * 32).div_ceil(layout.bytes_per_sector);
let data = boot.total_sectors()
- (u32::from(boot.reserved_sectors)
+ u32::from(boot.fats) * boot.fat_sectors()
+ root_sectors);
assert_eq!(
data / u32::from(boot.sectors_per_cluster),
layout.clusters,
"{what}: the written fields derive a different cluster count than was planned"
);
assert_eq!(FatType::of_cluster_count(layout.clusters), what, "{what}");
assert_eq!(
u16::from_le_bytes([image.as_bytes()[510], image.as_bytes()[511]]),
BOOT_SIGNATURE
);
}
}
#[test]
fn a_zero_16_bit_table_size_marks_exactly_the_fat32_volumes() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let image = image(mib, request);
let boot = BootSector::read_from(image.as_bytes()).expect("read");
let is_fat32 = image.layout().fat_type == FatType::Fat32;
assert_eq!(boot.fat_sectors_16 == 0, is_fat32);
assert_eq!(matches!(boot.tail, BootSectorTail::Fat32 { .. }), is_fat32);
assert_eq!(boot.root_entries == 0, is_fat32);
}
}
#[test]
fn every_table_copy_carries_the_entries_the_format_reserves() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let image = image(mib, request);
let layout = *image.layout();
let kind = layout.fat_type;
for copy in 0..layout.fats {
let start = layout.fat_start_sector(copy).expect("a copy that exists") as usize
* layout.bytes_per_sector as usize;
let table = &image.as_bytes()[start..start + layout.bytes_per_sector as usize];
assert_eq!(
table::read_entry(kind, table, 0),
Some(table::media_entry(kind, MEDIA_FIXED)),
"{kind} copy {copy}: the media entry"
);
assert_eq!(
table::read_entry(kind, table, 1),
Some(table::tail_entry(kind)),
"{kind} copy {copy}: the reserved entry"
);
match layout.fat32 {
Some(fat32) => {
assert_eq!(
table::read_entry(kind, table, fat32.root_cluster),
Some(table::end_of_chain(kind))
);
assert_eq!(
table::read_entry(kind, table, fat32.root_cluster + 1),
Some(table::FREE)
);
}
None => assert_eq!(table::read_entry(kind, table, 2), Some(table::FREE)),
}
}
let copies: Vec<&[u8]> = (0..layout.fats)
.map(|c| {
let start = layout.fat_start_sector(c).unwrap() as usize
* layout.bytes_per_sector as usize;
let len = layout.fat_sectors as usize * layout.bytes_per_sector as usize;
&image.as_bytes()[start..start + len]
})
.collect();
assert!(copies.windows(2).all(|w| w[0] == w[1]), "{kind}");
}
}
#[test]
fn a_label_reaches_both_places_that_record_it() {
let label = VolumeLabel::new("ferrosys").expect("a valid label");
let opts = options()
.label(label)
.plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat32)));
let image = format(TreeBuilder::new(), 512 << 20, opts).expect("format");
let layout = *image.layout();
let boot = BootSector::read_from(image.as_bytes()).expect("read");
let BootSectorTail::Fat32 { volume, .. } = boot.tail else {
panic!("a FAT32 volume must carry the FAT32 tail")
};
assert_eq!(&volume.label, label.as_bytes());
assert_eq!(volume.volume_id, 0x1234_abcd);
let root = layout
.cluster_start_sector(layout.fat32.unwrap().root_cluster)
.unwrap() as usize
* layout.bytes_per_sector as usize;
let entry = DirEntry::read_from(&image.as_bytes()[root..]).expect("read");
assert_eq!(&entry.name, label.as_bytes());
assert!(entry.attributes.contains(Attributes::VOLUME_ID));
assert_eq!(entry.first_cluster_lo, 0);
assert_eq!(entry.first_cluster_hi, 0);
assert_eq!(entry.size, 0);
assert_eq!(image.as_bytes()[root + DIR_ENTRY_SIZE], 0);
}
#[test]
fn an_unnamed_volume_carries_the_placeholder_and_no_entry() {
let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
let boot = BootSector::read_from(image.as_bytes()).expect("read");
let BootSectorTail::Fat1216 { volume } = boot.tail else {
panic!("a FAT16 volume must carry the smaller tail")
};
assert_eq!(volume.label, *VolumeLabel::NO_NAME.as_bytes());
let root = image.layout().root_dir_start_sector().unwrap() as usize
* image.layout().bytes_per_sector as usize;
assert_eq!(image.as_bytes()[root], 0);
}
#[test]
fn a_fat32_volume_carries_its_information_sector_and_both_backups() {
let image = image(512, FatTypeRequest::Exactly(FatType::Fat32));
let layout = *image.layout();
let fat32 = layout.fat32.expect("a FAT32 layout");
let sector = layout.bytes_per_sector as usize;
let at = |n: u16| n as usize * sector;
let info = FsInfo::read_from(&image.as_bytes()[at(fat32.fs_info_sector)..]).expect("read");
assert_eq!(info.free_clusters, Some(layout.clusters - 1));
assert_eq!(info.next_free_cluster, Some(fat32.root_cluster + 1));
let backup = fat32.backup_boot_sector.expect("room for a backup");
assert_eq!(
&image.as_bytes()[at(backup)..at(backup) + BootSector::SIZE],
&image.as_bytes()[..BootSector::SIZE],
"the backup boot sector is not a copy of the primary"
);
let backup_info = fat32.backup_fs_info_sector.expect("room for a backup");
assert_eq!(
&image.as_bytes()[at(backup_info)..at(backup_info) + FsInfo::SIZE],
&image.as_bytes()[at(fat32.fs_info_sector)..at(fat32.fs_info_sector) + FsInfo::SIZE],
);
assert!(u32::from(backup) < layout.reserved_sectors);
assert!(u32::from(backup_info) < layout.reserved_sectors);
}
#[test]
fn a_reserved_region_with_no_room_for_a_backup_information_sector_writes_none() {
let opts = options().plan(
PlanRequest::new(0)
.fat_type(FatTypeRequest::Exactly(FatType::Fat32))
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(7)),
);
let image = format(TreeBuilder::new(), 64 << 20, opts).expect("format");
let layout = *image.layout();
let fat32 = layout.fat32.expect("a FAT32 layout");
assert_eq!(layout.reserved_sectors, 7);
assert_eq!(fat32.backup_boot_sector, Some(6));
assert_eq!(fat32.backup_fs_info_sector, None);
let head = layout.fat_start_sector(0).unwrap() as usize * layout.bytes_per_sector as usize;
assert_eq!(head, 7 * layout.bytes_per_sector as usize);
let table = &image.as_bytes()[head..head + layout.bytes_per_sector as usize];
assert_eq!(
table::read_entry(FatType::Fat32, table, 0),
Some(table::media_entry(FatType::Fat32, MEDIA_FIXED))
);
}
#[test]
fn the_streamed_image_is_the_in_memory_image() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let opts = options()
.label(VolumeLabel::new("STREAMED").unwrap())
.plan(PlanRequest::new(0).fat_type(request));
let whole = format(TreeBuilder::new(), mib << 20, opts).expect("format");
let mut streamed = std::io::Cursor::new(Vec::new());
let plan =
format_to(TreeBuilder::new(), mib << 20, opts, &mut streamed).expect("format_to");
assert_eq!(plan.layout(), whole.layout());
assert_eq!(streamed.into_inner(), whole.as_bytes());
}
}
#[test]
fn only_the_sectors_the_filesystem_occupies_are_written() {
let image = image(512, FatTypeRequest::Exactly(FatType::Fat32));
let layout = *image.layout();
let sector = layout.bytes_per_sector as usize;
let after_root = (layout.cluster_start_sector(3).unwrap() as usize) * sector;
assert!(
image.as_bytes()[after_root..].iter().all(|&b| b == 0),
"the data region past the root cluster is not empty"
);
}
#[test]
fn the_boot_code_is_laid_where_the_jump_points() {
for (mib, request, offset) in [
(64u64, FatTypeRequest::Exactly(FatType::Fat16), 62usize),
(512, FatTypeRequest::Exactly(FatType::Fat32), 90),
] {
let code: Vec<u8> = (0..64u8).collect();
let opts = options()
.boot_code(BootCode::new(&code).expect("a valid length"))
.plan(PlanRequest::new(0).fat_type(request));
let image = format(TreeBuilder::new(), mib << 20, opts).expect("format");
let bytes = image.as_bytes();
assert_eq!(bytes[0], 0xEB);
assert_eq!(usize::from(bytes[1]) + 2, offset, "the jump's target");
assert_eq!(bytes[2], 0x90);
assert_eq!(&bytes[offset..offset + code.len()], &code[..]);
assert_ne!(bytes[offset - 1], code[0]);
}
}
#[test]
fn boot_code_too_long_for_the_type_is_refused_rather_than_truncated() {
let code = vec![0x90u8; BootCode::MAX_BYTES];
let fits = BootCode::new(&code).expect("the largest region's worth");
assert!(
format(
TreeBuilder::new(),
64 << 20,
options()
.boot_code(fits)
.plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat16)))
)
.is_ok()
);
assert!(matches!(
format(
TreeBuilder::new(),
512 << 20,
options()
.boot_code(fits)
.plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat32)))
),
Err(FormatError::BootCodeTooLong { limit, .. }) if limit == BootCode::MAX_BYTES_FAT32
));
assert!(matches!(
BootCode::new(&vec![0u8; BootCode::MAX_BYTES + 1]),
Err(FormatError::BootCodeTooLong { .. })
));
}
#[test]
fn a_time_the_format_cannot_hold_is_refused_before_anything_is_written() {
let mut opts = options().label(VolumeLabel::new("EARLY").unwrap());
opts.time = Timestamp::from_secs(0);
assert!(matches!(
format(TreeBuilder::new(), 64 << 20, opts),
Err(FormatError::TimeOutOfRange { secs: 0, .. })
));
let mut unlabelled = options();
unlabelled.time = Timestamp::from_secs(0);
assert!(matches!(
format(TreeBuilder::new(), 64 << 20, unlabelled),
Err(FormatError::TimeOutOfRange { secs: 0, .. })
));
let mut late = options();
late.time = Timestamp::from_secs(7_258_118_400); assert!(matches!(
format(TreeBuilder::new(), 64 << 20, late),
Err(FormatError::TimeOutOfRange { .. })
));
}
#[test]
fn the_size_a_format_is_asked_for_wins_over_the_one_in_the_request() {
let opts = options().plan(PlanRequest::new(999 << 20));
let image = format(TreeBuilder::new(), 64 << 20, opts).expect("format");
assert_eq!(image.as_bytes().len() as u64, 64 << 20);
}
#[test]
fn the_media_descriptor_reaches_the_boot_sector_the_tables_and_the_drive_number() {
let defined = (0xF8u8..=0xFF)
.map(|m| {
(
m,
if m == MEDIA_FIXED {
DRIVE_FIXED
} else {
DRIVE_REMOVABLE
},
)
})
.chain([(MEDIA_REMOVABLE, DRIVE_REMOVABLE)]);
for (media, drive) in defined {
let mut opts = options();
opts.media = media;
let image = format(TreeBuilder::new(), 64 << 20, opts).expect("format");
let boot = BootSector::read_from(image.as_bytes()).expect("read");
assert_eq!(boot.media, media);
let BootSectorTail::Fat1216 { volume } = boot.tail else {
panic!("a FAT16 volume")
};
assert_eq!(volume.drive_number, drive);
let layout = image.layout();
let head =
layout.fat_start_sector(0).unwrap() as usize * layout.bytes_per_sector as usize;
assert_eq!(
table::read_entry(layout.fat_type, &image.as_bytes()[head..], 0),
Some(table::media_entry(layout.fat_type, media))
);
}
}
#[test]
fn a_media_descriptor_the_format_does_not_define_is_refused() {
for media in [0x00u8, 0x42, 0xEF, 0xF1, 0xF7] {
let mut opts = options();
opts.media = media;
let err = format(TreeBuilder::new(), 64 << 20, opts)
.err()
.expect("an undefined media descriptor is refused");
assert!(
matches!(err, FormatError::MediaDescriptorUndefined { media: m } if m == media),
"media {media:#04x}: {err}",
);
let mut opts = options();
opts.media = media;
let mut sink = std::io::Cursor::new(Vec::new());
assert!(format_to(TreeBuilder::new(), 64 << 20, opts, &mut sink).is_err());
assert!(sink.into_inner().is_empty());
}
}
#[test]
fn the_legacy_geometry_follows_the_published_recommendation() {
assert_eq!(chs(4096), (16, 2));
assert_eq!(chs(4097), (32, 2));
assert_eq!(chs(32_768), (32, 2));
assert_eq!(chs(32_769), (32, 4));
assert_eq!(chs(65_536), (32, 4));
assert_eq!(chs(65_537), (32, 8));
assert_eq!(chs(262_144), (32, 8));
assert_eq!(chs(262_145), (32, 16));
assert_eq!(chs(524_288), (32, 16));
assert_eq!(chs(524_289), (63, 16));
assert_eq!(chs(16 * 63 * 1024), (63, 16));
assert_eq!(chs(16 * 63 * 1024 + 1), (63, 32));
assert_eq!(chs(32 * 63 * 1024), (63, 32));
assert_eq!(chs(32 * 63 * 1024 + 1), (63, 64));
assert_eq!(chs(64 * 63 * 1024), (63, 64));
assert_eq!(chs(64 * 63 * 1024 + 1), (63, 128));
assert_eq!(chs(128 * 63 * 1024), (63, 128));
assert_eq!(chs(128 * 63 * 1024 + 1), (63, 255));
assert_eq!(chs(u32::MAX), (63, 255));
}
fn entries_at(image: &Image, offset: usize) -> Vec<DirEntry> {
let mut out = Vec::new();
let mut at = offset;
while image.as_bytes()[at] != 0 {
out.push(DirEntry::read_from(&image.as_bytes()[at..]).expect("read"));
at += DIR_ENTRY_SIZE;
}
out
}
fn files_at(image: &Image, offset: usize) -> Vec<DirEntry> {
entries_at(image, offset)
.into_iter()
.filter(|e| !e.attributes.is_long_name())
.collect()
}
fn first_cluster(entry: &DirEntry) -> u32 {
u32::from(entry.first_cluster_lo) | u32::from(entry.first_cluster_hi) << 16
}
fn cluster_at(layout: &FatLayout, n: u32) -> usize {
layout
.cluster_start_sector(n)
.expect("a cluster the volume has") as usize
* layout.bytes_per_sector as usize
}
fn tree() -> TreeBuilder {
let meta = crate::source::Metadata::new(0o644, TIME);
let dir = crate::source::Metadata::new(0o755, TIME);
TreeBuilder::new()
.directory(b"/EFI".to_vec(), dir)
.directory(b"/EFI/BOOT".to_vec(), dir)
.file(b"/EFI/BOOT/BOOTX64.EFI".to_vec(), b"MZ payload", meta)
.file(b"/readme.txt".to_vec(), b"a long name\n", meta)
}
#[test]
fn a_tree_reaches_the_image_with_its_names_clusters_and_lengths() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let opts = options().plan(PlanRequest::new(0).fat_type(request));
let image = format(tree(), mib << 20, opts).expect("format");
let layout = *image.layout();
let what = layout.fat_type;
let root = match layout.fat32 {
Some(f) => cluster_at(&layout, f.root_cluster),
None => {
layout.root_dir_start_sector().unwrap() as usize
* layout.bytes_per_sector as usize
}
};
let entries = entries_at(&image, root);
assert_eq!(entries.len(), 3, "{what}: EFI, then two entries for readme");
assert_eq!(&entries[0].name, b"EFI ");
assert!(entries[0].attributes.contains(Attributes::DIRECTORY));
assert_eq!(entries[0].size, 0, "{what}: a directory records no length");
assert!(entries[1].attributes.is_long_name());
assert_eq!(&entries[2].name, b"README TXT");
assert_eq!(entries[2].size, 12);
let lfn = LfnEntry::read_from(&image.as_bytes()[root + DIR_ENTRY_SIZE..])
.expect("a long-name entry");
assert_eq!(
lfn.checksum,
crate::fat::ondisk::lfn_checksum(&entries[2].name),
"{what}: the long name is not tied to its short entry"
);
let units: Vec<u16> = lfn
.name
.iter()
.copied()
.take_while(|&u| u != 0 && u != 0xFFFF)
.collect();
assert_eq!(String::from_utf16(&units).expect("utf16"), "readme.txt");
let boot = layout
.cluster_start_sector(u32::from(entries[0].first_cluster_lo))
.expect("EFI's cluster");
let efi = files_at(&image, boot as usize * layout.bytes_per_sector as usize);
assert_eq!(&efi[0].name, b". ", "{what}");
assert_eq!(&efi[1].name, b".. ", "{what}");
assert_eq!(efi[1].first_cluster_lo, 0, "{what}");
assert_eq!(efi[1].first_cluster_hi, 0, "{what}");
assert_eq!(&efi[2].name, b"BOOT ", "{what}");
let boot_dir = files_at(&image, cluster_at(&layout, first_cluster(&efi[2])));
assert_eq!(
first_cluster(&boot_dir[1]),
first_cluster(&efi[0]),
"{what}: `..` does not name the directory that holds this one"
);
let payload = &boot_dir[2];
assert_eq!(&payload.name, b"BOOTX64 EFI", "{what}");
assert_eq!(payload.size, 10, "{what}");
let at = cluster_at(&layout, first_cluster(payload));
assert_eq!(&image.as_bytes()[at..at + 10], b"MZ payload", "{what}");
}
}
#[test]
fn every_chain_the_tree_needs_is_in_every_copy_of_the_table() {
let bytes = 4096usize;
let meta = crate::source::Metadata::new(0o644, TIME);
let source = TreeBuilder::new()
.file(b"/big".to_vec(), vec![9u8; bytes * 3], meta)
.file(b"/small".to_vec(), b"x", meta);
let opts =
options().plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat16)));
let image = format(source, 64 << 20, opts).expect("format");
let layout = *image.layout();
let kind = layout.fat_type;
let per_cluster = layout.bytes_per_cluster() as usize;
let want = (bytes * 3).div_ceil(per_cluster) as u32;
for copy in 0..layout.fats {
let start =
layout.fat_start_sector(copy).unwrap() as usize * layout.bytes_per_sector as usize;
let table = &image.as_bytes()[start..];
for n in 2..2 + want - 1 {
assert_eq!(
table::read_entry(kind, table, n),
Some(n + 1),
"{kind} copy {copy}: cluster {n} does not point at its successor"
);
}
let last = 2 + want - 1;
assert!(table::is_end_of_chain(
kind,
table::read_entry(kind, table, last).expect("an entry the table holds")
));
assert!(table::is_end_of_chain(
kind,
table::read_entry(kind, table, last + 1).expect("an entry")
));
assert_eq!(table::read_entry(kind, table, last + 2), Some(table::FREE));
}
}
#[test]
fn a_twelve_bit_table_packs_a_tree_across_its_shared_nibbles() {
let meta = crate::source::Metadata::new(0o644, TIME);
let mut source = TreeBuilder::new();
for i in 0..60 {
source = source.file(format!("/F{i}").into_bytes(), b"x", meta);
}
let opts = options().plan(
PlanRequest::new(0)
.fat_type(FatTypeRequest::Exactly(FatType::Fat12))
.cluster_size(ClusterSize::Sectors(1)),
);
let image = format(source, 2 << 20, opts).expect("format");
let layout = *image.layout();
let start = layout.fat_start_sector(0).unwrap() as usize * layout.bytes_per_sector as usize;
let table = &image.as_bytes()[start..];
for n in 2..62 {
let entry = table::read_entry(FatType::Fat12, table, n).expect("an entry");
assert!(
table::is_end_of_chain(FatType::Fat12, entry),
"cluster {n} reads back as {entry:#05x} rather than an end of chain"
);
}
assert_eq!(
table::read_entry(FatType::Fat12, table, 62),
Some(table::FREE)
);
}
#[test]
fn a_full_volume_records_no_next_free_hint_rather_than_one_past_the_end() {
let options = options()
.accept_all_loss()
.plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat32)));
let source = || {
let meta = crate::source::Metadata::new(0o644, TIME);
let mut b = TreeBuilder::new();
for i in 0..8 {
b = b.file(format!("/bulk{i}").into_bytes(), vec![0xAB; 5 << 20], meta);
}
b
};
let plan = FormatPlan::fit(source(), options, crate::Slack::None).expect("fit");
assert_eq!(plan.free_clusters(), 0, "no slack leaves a full volume");
let mut image = std::io::Cursor::new(vec![0u8; plan.volume_bytes() as usize]);
plan.write_to(&mut image).expect("write");
let mut r =
crate::fat::Reader::open(std::io::Cursor::new(image.into_inner())).expect("open");
let report = r.scan();
assert!(
report.is_clean(),
"a volume this crate wrote is clean by its own scanner: {:#?}",
report.anomalies()
);
}
#[test]
fn the_information_sector_counts_what_the_tree_took() {
let meta = crate::source::Metadata::new(0o644, TIME);
let source = TreeBuilder::new()
.directory(b"/d".to_vec(), crate::source::Metadata::new(0o755, TIME))
.file(b"/d/f".to_vec(), b"x", meta);
let opts =
options().plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat32)));
let image = format(source, 512 << 20, opts).expect("format");
let layout = *image.layout();
let fat32 = layout.fat32.expect("a FAT32 layout");
let at = fat32.fs_info_sector as usize * layout.bytes_per_sector as usize;
let info = FsInfo::read_from(&image.as_bytes()[at..]).expect("read");
assert_eq!(info.free_clusters, Some(layout.clusters - 3));
assert_eq!(info.next_free_cluster, Some(5));
}
#[test]
fn a_populated_format_is_reproducible_and_streams_the_same_bytes() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let opts = options()
.label(VolumeLabel::new("TREE").unwrap())
.plan(PlanRequest::new(0).fat_type(request));
let whole = format(tree(), mib << 20, opts).expect("format");
assert_eq!(
whole.as_bytes(),
format(tree(), mib << 20, opts).expect("format").as_bytes(),
"two formats of one tree differ"
);
let mut streamed = std::io::Cursor::new(Vec::new());
let plan = format_to(tree(), mib << 20, opts, &mut streamed).expect("format_to");
assert_eq!(plan.layout(), whole.layout());
assert_eq!(streamed.into_inner(), whole.as_bytes());
}
}
#[test]
fn a_loss_the_caller_has_not_accepted_stops_the_format_before_the_destination_is_touched() {
let source = TreeBuilder::new().file(
b"/setuid".to_vec(),
b"x",
crate::source::Metadata::new(0o4755, TIME),
);
let mut sink = std::io::Cursor::new(Vec::new());
assert!(matches!(
format_to(source.clone(), 64 << 20, options(), &mut sink),
Err(FormatError::Model(_))
));
assert!(sink.into_inner().is_empty());
let opts = options().accept_all_loss();
let image = format(source, 64 << 20, opts).expect("format");
assert!(!image.fidelity().is_faithful());
assert_eq!(
image
.fidelity()
.count(crate::fidelity::Direction::Dropped, Property::SpecialBits),
1
);
}
#[test]
fn a_hard_link_is_written_as_a_second_copy_of_its_file() {
let meta = crate::source::Metadata::new(0o644, TIME);
let source = TreeBuilder::new()
.file(b"/one".to_vec(), b"shared bytes", meta)
.hardlink(b"/two".to_vec(), b"/one".to_vec(), meta);
let opts = options().accept_loss(Property::Kind);
let image = format(source, 64 << 20, opts).expect("format");
let layout = *image.layout();
let root =
layout.root_dir_start_sector().unwrap() as usize * layout.bytes_per_sector as usize;
let entries = files_at(&image, root);
assert_eq!(entries.len(), 2);
assert_ne!(first_cluster(&entries[0]), first_cluster(&entries[1]));
for entry in &entries {
assert_eq!(entry.size, 12);
let at = cluster_at(&layout, first_cluster(entry));
assert_eq!(&image.as_bytes()[at..at + 12], b"shared bytes");
}
}
#[test]
fn a_labelled_root_counts_the_label_among_the_entries_it_reserves_room_for() {
let meta = crate::source::Metadata::new(0o644, TIME);
let mut source = TreeBuilder::new();
for i in 0..16 {
source = source.file(format!("/F{i}").into_bytes(), b"payload", meta);
}
let opts = options().label(VolumeLabel::new("FULL").unwrap()).plan(
PlanRequest::new(0)
.fat_type(FatTypeRequest::Exactly(FatType::Fat32))
.cluster_size(ClusterSize::Sectors(1)),
);
let image = format(source, 512 << 20, opts).expect("format");
let layout = *image.layout();
assert_eq!(
layout.bytes_per_cluster(),
512,
"sixteen entries to a cluster"
);
let fat32 = layout.fat32.expect("a FAT32 layout");
let root = fat32.root_cluster;
let head = layout.fat_start_sector(0).unwrap() as usize * layout.bytes_per_sector as usize;
let table = &image.as_bytes()[head..];
assert_eq!(
table::read_entry(FatType::Fat32, table, root),
Some(root + 1),
"seventeen entries were placed in a root of one cluster"
);
assert!(table::is_end_of_chain(
FatType::Fat32,
table::read_entry(FatType::Fat32, table, root + 1).expect("an entry")
));
let at = cluster_at(&layout, root);
assert_eq!(
files_at(&image, at).len(),
17,
"the label and sixteen files"
);
}
#[test]
fn an_empty_source_writes_exactly_what_an_empty_volume_is() {
for (mib, request) in [
(2u64, FatTypeRequest::Exactly(FatType::Fat12)),
(64, FatTypeRequest::Exactly(FatType::Fat16)),
(512, FatTypeRequest::Exactly(FatType::Fat32)),
] {
let opts = options()
.label(VolumeLabel::new("EMPTY").unwrap())
.plan(PlanRequest::new(0).fat_type(request));
let image = format(TreeBuilder::new(), mib << 20, opts).expect("format");
let layout = *image.layout();
let root = match layout.fat32 {
Some(f) => cluster_at(&layout, f.root_cluster),
None => {
layout.root_dir_start_sector().unwrap() as usize
* layout.bytes_per_sector as usize
}
};
let entries = entries_at(&image, root);
assert_eq!(entries.len(), 1, "{}", layout.fat_type);
assert!(entries[0].attributes.contains(Attributes::VOLUME_ID));
}
}
#[test]
fn a_label_is_folded_up_padded_and_held_to_what_a_directory_entry_holds() {
assert_eq!(VolumeLabel::new("esp").unwrap().as_bytes(), b"ESP ");
assert_eq!(
VolumeLabel::new("ELEVEN CHRS").unwrap().as_bytes(),
b"ELEVEN CHRS"
);
assert!(matches!(
VolumeLabel::new("TWELVE CHARS"),
Err(LabelError::TooLong { bytes: 12, .. })
));
for bad in ["A.B", "A/B", "A:B", "A*B", "A?B", "A\"B", "A|B", "A<B"] {
assert!(
matches!(VolumeLabel::new(bad), Err(LabelError::InvalidByte { .. })),
"{bad} was accepted"
);
}
assert!(matches!(
VolumeLabel::from_bytes(&[0xE5, b'A']),
Err(LabelError::InvalidByte { at: 0, .. })
));
assert!(VolumeLabel::from_bytes(&[b'A', 0xE5]).is_ok());
assert!(matches!(
VolumeLabel::new(" AB"),
Err(LabelError::InvalidByte { byte: b' ', at: 0 })
));
assert_eq!(VolumeLabel::new("A B").unwrap().as_bytes(), b"A B ");
assert_eq!(VolumeLabel::new(""), Err(LabelError::Empty));
}
#[test]
fn the_label_entry_stamps_every_time_the_entry_has() {
let mut opts = options().label(VolumeLabel::new("STAMPED").unwrap());
opts.time = Timestamp::from_secs(1_426_325_213);
let image = format(TreeBuilder::new(), 64 << 20, opts).expect("format");
let layout = *image.layout();
let root =
layout.root_dir_start_sector().unwrap() as usize * layout.bytes_per_sector as usize;
let entry = DirEntry::read_from(&image.as_bytes()[root..]).expect("read");
let expected = DosTimestamp::encode(opts.time).expect("in range");
assert_eq!(entry.create_date, expected.date);
assert_eq!(entry.create_time, expected.time);
assert_eq!(entry.create_time_tenth, 100);
assert_eq!(entry.write_date, expected.date);
assert_eq!(entry.write_time, expected.time);
assert_eq!(entry.access_date, expected.date);
let mut even = opts;
even.time = TIME;
let image = format(TreeBuilder::new(), 64 << 20, even).expect("format");
let entry = DirEntry::read_from(&image.as_bytes()[root..]).expect("read");
assert_eq!(entry.create_time_tenth, 0);
assert_eq!(entry.create_time, expected.time);
}
}