#[cfg(feature = "serde")]
use serde::Serialize;
use super::ondisk::{BootSector, BootSectorTail, DIR_ENTRY_SIZE};
const DIR_ENTRY_BYTES: u64 = DIR_ENTRY_SIZE as u64;
pub const MAX_CLUSTERS_FAT12: u32 = 4084;
pub const MIN_CLUSTERS_FAT16: u32 = 4087;
pub const MAX_CLUSTERS_FAT16: u32 = 65524;
pub const MIN_CLUSTERS_FAT32: u32 = 65525;
pub const MAX_CLUSTERS_FAT32: u32 = 268_435_445;
pub const MAX_BYTES_PER_CLUSTER: u32 = 32_768;
pub(crate) const FAT32_AUTO_THRESHOLD_BYTES: u64 = 512 * 1024 * 1024;
const ALIGNMENT_THRESHOLD_SECTORS: u32 = 8192;
const FS_INFO_SECTOR: u16 = 1;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub enum FatType {
Fat12,
Fat16,
Fat32,
}
crate::naming::named_choice!(FatType {
FatType::Fat12 => "fat12",
FatType::Fat16 => "fat16",
FatType::Fat32 => "fat32",
});
crate::naming::serialize_as_name!(FatType);
impl FatType {
#[must_use]
pub const fn entry_bits(self) -> u32 {
match self {
FatType::Fat12 => 12,
FatType::Fat16 => 16,
FatType::Fat32 => 32,
}
}
#[must_use]
pub const fn label(self) -> [u8; 8] {
match self {
FatType::Fat12 => *b"FAT12 ",
FatType::Fat16 => *b"FAT16 ",
FatType::Fat32 => *b"FAT32 ",
}
}
#[must_use]
pub const fn min_clusters(self) -> u32 {
match self {
FatType::Fat12 => 1,
FatType::Fat16 => MIN_CLUSTERS_FAT16,
FatType::Fat32 => MIN_CLUSTERS_FAT32,
}
}
#[must_use]
pub const fn max_clusters(self) -> u32 {
match self {
FatType::Fat12 => MAX_CLUSTERS_FAT12,
FatType::Fat16 => MAX_CLUSTERS_FAT16,
FatType::Fat32 => MAX_CLUSTERS_FAT32,
}
}
#[must_use]
pub const fn of_cluster_count(clusters: u32) -> FatType {
if clusters < MAX_CLUSTERS_FAT12 + 1 {
FatType::Fat12
} else if clusters < MIN_CLUSTERS_FAT32 {
FatType::Fat16
} else {
FatType::Fat32
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum FatTypeRequest {
#[default]
Auto,
Exactly(FatType),
UndersizedFat32,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum ClusterSize {
#[default]
Auto,
Sectors(u32),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum RootEntries {
#[default]
Auto,
Count(u32),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum ReservedSectors {
#[default]
Auto,
Count(u32),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GeometryError {
#[error("sector size {bytes_per_sector} is not 512, 1024, 2048, or 4096")]
#[non_exhaustive]
SectorSizeUnsupported {
bytes_per_sector: u32,
},
#[error("cluster size {sectors_per_cluster} is not a power of two from 1 to 128 sectors")]
#[non_exhaustive]
ClusterSizeUnsupported {
sectors_per_cluster: u32,
},
#[error("cluster of {bytes} bytes exceeds the {limit} a driver is guaranteed to handle")]
#[non_exhaustive]
ClusterTooLarge {
bytes: u64,
limit: u32,
},
#[error("{fats} file allocation tables: the count must be 1 or 2")]
#[non_exhaustive]
FatCountUnsupported {
fats: u32,
},
#[error("{reserved} reserved sectors: {minimum} is the fewest this geometry allows")]
#[non_exhaustive]
ReservedSectorsTooFew {
reserved: u32,
minimum: u32,
},
#[error(
"{reserved} reserved sectors: the boot sector records the count in sixteen bits, so \
at most {limit}"
)]
#[non_exhaustive]
ReservedSectorsTooMany {
reserved: u32,
limit: u32,
},
#[error("{root_entries} root directory entries: the count must be 1 to {limit}")]
#[non_exhaustive]
RootEntriesUnsupported {
root_entries: u32,
limit: u32,
},
#[error(
"FAT32 has no fixed root directory region, so {root_entries} entries cannot be reserved in one"
)]
#[non_exhaustive]
RootEntriesOnFat32 {
root_entries: u32,
},
#[error("volume of {sectors} sectors exceeds the {limit} a 32-bit sector count holds")]
#[non_exhaustive]
VolumeTooLarge {
sectors: u64,
limit: u64,
},
#[error(
"no FAT type fits a volume of {sectors} sectors at {sectors_per_cluster} sectors \
per cluster"
)]
#[non_exhaustive]
NoTypeFits {
sectors: u32,
sectors_per_cluster: u32,
},
#[error(
"a FAT16 of {clusters} clusters is read as FAT12 by Windows and as FAT16 by Linux; \
{low} to {high} clusters cannot be written unambiguously, so the volume must be \
large enough for {high_plus_one} or the type must be FAT12"
)]
#[non_exhaustive]
AmbiguousClusterCount {
clusters: u32,
low: u32,
high: u32,
high_plus_one: u32,
},
#[error("a {requested} of {clusters} clusters is below the {minimum} the type requires")]
#[non_exhaustive]
ClustersBelowMinimum {
requested: FatType,
clusters: u32,
minimum: u32,
},
#[error(
"a {requested} cannot address the {clusters} clusters this geometry reaches; the \
type holds at most {maximum}"
)]
#[non_exhaustive]
ClustersAboveMaximum {
requested: FatType,
clusters: u32,
maximum: u32,
},
}
impl core::fmt::Display for FatType {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Fat32Layout {
pub root_cluster: u32,
pub fs_info_sector: u16,
pub backup_boot_sector: Option<u16>,
pub backup_fs_info_sector: Option<u16>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct FatLayout {
pub fat_type: FatType,
pub bytes_per_sector: u32,
pub sectors_per_cluster: u32,
pub reserved_sectors: u32,
pub fats: u32,
pub root_entries: u32,
pub total_sectors: u32,
pub fat_sectors: u32,
pub root_dir_sectors: u32,
pub first_data_sector: u32,
pub clusters: u32,
pub fat32: Option<Fat32Layout>,
}
impl FatLayout {
#[must_use]
pub const fn bytes_per_cluster(&self) -> u32 {
self.bytes_per_sector * self.sectors_per_cluster
}
#[must_use]
pub const fn fat_start_sector(&self, index: u32) -> Option<u32> {
if index >= self.fats {
return None;
}
Some(self.reserved_sectors + index * self.fat_sectors)
}
#[must_use]
pub const fn root_dir_start_sector(&self) -> Option<u32> {
if self.root_dir_sectors == 0 {
return None;
}
Some(self.reserved_sectors + self.fats * self.fat_sectors)
}
#[must_use]
pub const fn cluster_start_sector(&self, n: u32) -> Option<u32> {
if n < 2 || n - 2 >= self.clusters {
return None;
}
Some(self.first_data_sector + (n - 2) * self.sectors_per_cluster)
}
#[must_use]
pub const fn data_sectors(&self) -> u32 {
self.clusters * self.sectors_per_cluster
}
#[must_use]
pub const fn total_bytes(&self) -> u64 {
self.total_sectors as u64 * self.bytes_per_sector as u64
}
#[must_use]
pub const fn max_table_entries(&self) -> u32 {
let bytes = self.fat_sectors as u64 * self.bytes_per_sector as u64;
let entries = match self.fat_type {
FatType::Fat12 => bytes * 2 / 3,
FatType::Fat16 => bytes / 2,
FatType::Fat32 => bytes / 4,
};
if entries > u32::MAX as u64 {
u32::MAX
} else {
entries as u32
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct PlanRequest {
pub volume_bytes: u64,
pub bytes_per_sector: u32,
pub sectors_per_cluster: ClusterSize,
pub fats: u32,
pub root_entries: RootEntries,
pub reserved_sectors: ReservedSectors,
pub fat_type: FatTypeRequest,
}
impl PlanRequest {
#[must_use]
pub const fn new(volume_bytes: u64) -> Self {
Self {
volume_bytes,
bytes_per_sector: 512,
sectors_per_cluster: ClusterSize::Auto,
fats: 2,
root_entries: RootEntries::Auto,
reserved_sectors: ReservedSectors::Auto,
fat_type: FatTypeRequest::Auto,
}
}
#[must_use]
pub const fn bytes_per_sector(mut self, bytes: u32) -> Self {
self.bytes_per_sector = bytes;
self
}
#[must_use]
pub const fn cluster_size(mut self, size: ClusterSize) -> Self {
self.sectors_per_cluster = size;
self
}
#[must_use]
pub const fn fats(mut self, fats: u32) -> Self {
self.fats = fats;
self
}
#[must_use]
pub const fn root_entries(mut self, entries: RootEntries) -> Self {
self.root_entries = entries;
self
}
#[must_use]
pub const fn reserved_sectors(mut self, reserved: ReservedSectors) -> Self {
self.reserved_sectors = reserved;
self
}
#[must_use]
pub const fn fat_type(mut self, fat_type: FatTypeRequest) -> Self {
self.fat_type = fat_type;
self
}
pub(crate) fn validate(&self) -> Result<(), GeometryError> {
if !matches!(self.bytes_per_sector, 512 | 1024 | 2048 | 4096) {
return Err(GeometryError::SectorSizeUnsupported {
bytes_per_sector: self.bytes_per_sector,
});
}
if !matches!(self.fats, 1 | 2) {
return Err(GeometryError::FatCountUnsupported { fats: self.fats });
}
if let ClusterSize::Sectors(n) = self.sectors_per_cluster {
if !n.is_power_of_two() || n > 128 {
return Err(GeometryError::ClusterSizeUnsupported {
sectors_per_cluster: n,
});
}
let bytes = u64::from(n) * u64::from(self.bytes_per_sector);
if bytes > u64::from(MAX_BYTES_PER_CLUSTER) {
return Err(GeometryError::ClusterTooLarge {
bytes,
limit: MAX_BYTES_PER_CLUSTER,
});
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
struct Candidate {
fat_sectors: u32,
clusters: u32,
}
const fn align(sectors: u32, sectors_per_cluster: u32, aligning: bool) -> u32 {
if aligning {
sectors.div_ceil(sectors_per_cluster) * sectors_per_cluster
} else {
sectors
}
}
fn table_bytes(entries: u64, bits: u32) -> u64 {
match bits {
12 => (entries * 3).div_ceil(2),
_ => entries * u64::from(bits / 8),
}
}
fn table_sectors(clusters: u32, bits: u32, bytes_per_sector: u32, spc: u32, aligning: bool) -> u32 {
let sectors = table_bytes(u64::from(clusters) + 2, bits).div_ceil(u64::from(bytes_per_sector));
align(u32::try_from(sectors).unwrap_or(u32::MAX), spc, aligning)
}
fn candidate(
space: u32,
bits: u32,
bytes_per_sector: u32,
spc: u32,
fats: u32,
aligning: bool,
) -> Option<Candidate> {
let unit = if aligning { spc } else { 1 };
let left = |units: u32| -> Option<u32> {
let tables = u64::from(fats) * u64::from(units) * u64::from(unit);
let data = u64::from(space).checked_sub(tables)?;
Some((data / u64::from(spc)) as u32)
};
let holds = |units: u32| -> bool {
match left(units) {
Some(clusters) => {
table_bytes(u64::from(clusters) + 2, bits)
<= u64::from(units) * u64::from(unit) * u64::from(bytes_per_sector)
}
None => true,
}
};
let (mut low, mut high) = (1u32, space.div_ceil(unit).max(1));
while low < high {
let mid = low + (high - low) / 2;
if holds(mid) {
high = mid;
} else {
low = mid + 1;
}
}
let clusters = left(low)?;
if clusters == 0 {
return None;
}
Some(Candidate {
fat_sectors: low * unit,
clusters,
})
}
const fn starting_cluster_size(fat32: bool, sectors: u64) -> u32 {
if !fat32 {
return 4;
}
if sectors > 32 * 1024 * 1024 * 2 {
64
} else if sectors > 16 * 1024 * 1024 * 2 {
32
} else if sectors > 8 * 1024 * 1024 * 2 {
16
} else if sectors > 260 * 1024 * 2 {
8
} else {
1
}
}
const fn backup_boot_sector(reserved: u32) -> Option<u16> {
match reserved {
0..=2 => None,
3 | 4 => Some(2),
5 | 6 => Some((reserved - 2) as u16),
_ => Some(6),
}
}
pub fn plan_layout(request: &PlanRequest) -> Result<FatLayout, GeometryError> {
let &PlanRequest {
volume_bytes,
bytes_per_sector,
sectors_per_cluster,
fats,
root_entries,
reserved_sectors,
fat_type,
} = request;
request.validate()?;
let volume_sectors = volume_bytes / u64::from(bytes_per_sector);
if volume_sectors > u64::from(u32::MAX) {
return Err(GeometryError::VolumeTooLarge {
sectors: volume_sectors,
limit: u64::from(u32::MAX),
});
}
let total_sectors = volume_sectors as u32;
let fat32_intended = match fat_type {
FatTypeRequest::Exactly(FatType::Fat32) | FatTypeRequest::UndersizedFat32 => true,
FatTypeRequest::Exactly(_) => false,
FatTypeRequest::Auto => volume_bytes >= FAT32_AUTO_THRESHOLD_BYTES,
};
let reserved = match reserved_sectors {
ReservedSectors::Auto if fat32_intended => 32,
ReservedSectors::Auto => 1,
ReservedSectors::Count(n) => n,
};
let reserved_minimum = if fat32_intended { 2 } else { 1 };
if reserved < reserved_minimum {
return Err(GeometryError::ReservedSectorsTooFew {
reserved,
minimum: reserved_minimum,
});
}
if reserved > u32::from(u16::MAX) {
return Err(GeometryError::ReservedSectorsTooMany {
reserved,
limit: u32::from(u16::MAX),
});
}
let requested_entries = match root_entries {
RootEntries::Auto => None,
RootEntries::Count(n) => Some(n),
};
if fat32_intended && let Some(n) = requested_entries.filter(|&n| n != 0) {
return Err(GeometryError::RootEntriesOnFat32 { root_entries: n });
}
let root_entries_requested = if fat32_intended {
0
} else {
let n = requested_entries.unwrap_or(512);
if n == 0 || n > u32::from(u16::MAX) {
return Err(GeometryError::RootEntriesUnsupported {
root_entries: n,
limit: u32::from(u16::MAX),
});
}
n
};
let root_dir_sectors_unaligned = (root_entries_requested * 32).div_ceil(bytes_per_sector);
let aligning = total_sectors > ALIGNMENT_THRESHOLD_SECTORS;
let (first_size, last_size) = match sectors_per_cluster {
ClusterSize::Auto => {
let ceiling = (MAX_BYTES_PER_CLUSTER / bytes_per_sector).clamp(1, 128);
(
starting_cluster_size(fat32_intended, volume_sectors).min(ceiling),
ceiling,
)
}
ClusterSize::Sectors(n) => (n, n),
};
let fat_type = match fat_type {
FatTypeRequest::Auto if fat32_intended => FatTypeRequest::Exactly(FatType::Fat32),
other => other,
};
let mut spc = first_size;
let chosen = loop {
let reserved_aligned = align(reserved, spc, aligning);
let root_aligned = align(root_dir_sectors_unaligned, spc, aligning);
let candidates =
match total_sectors
.checked_sub(reserved_aligned)
.and_then(|after_reserved| {
Some((after_reserved, after_reserved.checked_sub(root_aligned)?))
}) {
Some((beyond_reserved, beyond_root)) => [
candidate(beyond_root, 12, bytes_per_sector, spc, fats, aligning),
candidate(beyond_root, 16, bytes_per_sector, spc, fats, aligning),
candidate(beyond_reserved, 32, bytes_per_sector, spc, fats, aligning),
],
None => [None, None, None],
};
if let Some(chosen) = select(fat_type, &candidates) {
break chosen;
}
if spc >= last_size {
if let Some(c) = step_down(fat_type, &candidates) {
break (FatType::Fat12, c);
}
return Err(diagnose(fat_type, total_sectors, spc, &candidates));
}
spc *= 2;
};
let (fat_type, mut candidate) = chosen;
let reserved_aligned = align(reserved, spc, aligning);
let root_aligned = align(root_dir_sectors_unaligned, spc, aligning);
let mut total_sectors = total_sectors;
if fat_type == FatType::Fat12 && candidate.clusters > MAX_CLUSTERS_FAT12 {
candidate.clusters = MAX_CLUSTERS_FAT12;
candidate.fat_sectors =
table_sectors(MAX_CLUSTERS_FAT12, 12, bytes_per_sector, spc, aligning);
total_sectors = reserved_aligned
+ fats * candidate.fat_sectors
+ root_aligned
+ MAX_CLUSTERS_FAT12 * spc;
}
let first_data_sector = reserved_aligned + fats * candidate.fat_sectors + root_aligned;
assert_eq!(
(total_sectors - first_data_sector) / spc,
candidate.clusters,
"the planned cluster count and the count a driver derives from the planned fields \
must be the same number"
);
let root_entries = if aligning {
root_aligned * (bytes_per_sector / 32)
} else {
root_entries_requested
};
if root_entries > u32::from(u16::MAX) {
return Err(GeometryError::RootEntriesUnsupported {
root_entries,
limit: u32::from(u16::MAX),
});
}
if reserved_aligned > u32::from(u16::MAX) {
return Err(GeometryError::ReservedSectorsTooMany {
reserved: reserved_aligned,
limit: u32::from(u16::MAX),
});
}
Ok(FatLayout {
fat_type,
bytes_per_sector,
sectors_per_cluster: spc,
reserved_sectors: reserved_aligned,
fats,
root_entries,
total_sectors,
fat_sectors: candidate.fat_sectors,
root_dir_sectors: root_aligned,
first_data_sector,
clusters: candidate.clusters,
fat32: (fat_type == FatType::Fat32).then(|| {
let backup = backup_boot_sector(reserved_aligned);
Fat32Layout {
root_cluster: 2,
fs_info_sector: FS_INFO_SECTOR,
backup_boot_sector: backup,
backup_fs_info_sector: backup
.map(|b| b + FS_INFO_SECTOR)
.filter(|&b| u32::from(b) < reserved_aligned),
}
}),
})
}
fn select(
request: FatTypeRequest,
candidates: &[Option<Candidate>; 3],
) -> Option<(FatType, Candidate)> {
let fits = |kind: FatType| -> Option<Candidate> {
let c = candidates[kind as usize]?;
let low = match (request, kind) {
(FatTypeRequest::UndersizedFat32, FatType::Fat32) => 1,
_ => kind.min_clusters(),
};
(c.clusters >= low && c.clusters <= kind.max_clusters()).then_some(c)
};
match request {
FatTypeRequest::Exactly(kind) => fits(kind).map(|c| (kind, c)),
FatTypeRequest::UndersizedFat32 => fits(FatType::Fat32).map(|c| (FatType::Fat32, c)),
FatTypeRequest::Auto => {
fits(FatType::Fat12)
.map(|c| (FatType::Fat12, c))
.or_else(|| fits(FatType::Fat16).map(|c| (FatType::Fat16, c)))
}
}
}
fn step_down(request: FatTypeRequest, candidates: &[Option<Candidate>; 3]) -> Option<Candidate> {
if !matches!(
request,
FatTypeRequest::Auto | FatTypeRequest::Exactly(FatType::Fat12)
) {
return None;
}
let twelve = candidates[FatType::Fat12 as usize]?;
if twelve.clusters <= MAX_CLUSTERS_FAT12 {
return None;
}
match candidates[FatType::Fat16 as usize] {
Some(sixteen) if sixteen.clusters < MIN_CLUSTERS_FAT16 => Some(twelve),
_ => None,
}
}
fn diagnose(
request: FatTypeRequest,
sectors: u32,
spc: u32,
candidates: &[Option<Candidate>; 3],
) -> GeometryError {
let named = match request {
FatTypeRequest::Exactly(kind) => Some(kind),
FatTypeRequest::UndersizedFat32 => Some(FatType::Fat32),
FatTypeRequest::Auto => None,
};
let Some(kind) = named else {
return GeometryError::NoTypeFits {
sectors,
sectors_per_cluster: spc,
};
};
let Some(c) = candidates[kind as usize] else {
return GeometryError::NoTypeFits {
sectors,
sectors_per_cluster: spc,
};
};
if c.clusters > kind.max_clusters() {
return GeometryError::ClustersAboveMaximum {
requested: kind,
clusters: c.clusters,
maximum: kind.max_clusters(),
};
}
if kind == FatType::Fat16 && c.clusters > MAX_CLUSTERS_FAT12 && c.clusters < MIN_CLUSTERS_FAT16
{
return GeometryError::AmbiguousClusterCount {
clusters: c.clusters,
low: MAX_CLUSTERS_FAT12 + 1,
high: MIN_CLUSTERS_FAT16 - 1,
high_plus_one: MIN_CLUSTERS_FAT16,
};
}
GeometryError::ClustersBelowMinimum {
requested: kind,
clusters: c.clusters,
minimum: kind.min_clusters(),
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct BootDefect {
pub field: &'static str,
pub value: u64,
}
pub(crate) fn layout_from_boot(boot: &BootSector, available: u64) -> Result<FatLayout, BootDefect> {
let defect = |field: &'static str, value: u64| BootDefect { field, value };
let jump_ok = (boot.jump[0] == 0xEB && boot.jump[2] == 0x90) || boot.jump[0] == 0xE9;
if !jump_ok {
return Err(defect(
"BS_jmpBoot",
u64::from(u32::from_be_bytes([
0,
boot.jump[0],
boot.jump[1],
boot.jump[2],
])),
));
}
if !matches!(boot.bytes_per_sector, 512 | 1024 | 2048 | 4096) {
return Err(defect("BPB_BytsPerSec", u64::from(boot.bytes_per_sector)));
}
let spc = u32::from(boot.sectors_per_cluster);
if spc == 0 || !spc.is_power_of_two() || spc > 128 {
return Err(defect("BPB_SecPerClus", u64::from(spc)));
}
if !matches!(boot.fats, 1 | 2) {
return Err(defect("BPB_NumFATs", u64::from(boot.fats)));
}
if boot.reserved_sectors == 0 {
return Err(defect("BPB_RsvdSecCnt", 0));
}
if !super::materialize::is_media_descriptor(boot.media) {
return Err(defect("BPB_Media", u64::from(boot.media)));
}
let total_sectors = boot.total_sectors();
if total_sectors == 0 {
return Err(defect("BPB_TotSec32", 0));
}
let volume_bytes = u64::from(total_sectors) * u64::from(boot.bytes_per_sector);
if volume_bytes > available {
return Err(defect("BPB_TotSec32", volume_bytes));
}
let fat_sectors = boot.fat_sectors();
if fat_sectors == 0 {
return Err(defect("BPB_FATSz32", 0));
}
match boot.tail {
BootSectorTail::Fat1216 { .. } => {
if boot.root_entries == 0 {
return Err(defect("BPB_RootEntCnt", 0));
}
}
BootSectorTail::Fat32 { params, .. } => {
if boot.root_entries != 0 {
return Err(defect("BPB_RootEntCnt", u64::from(boot.root_entries)));
}
if params.root_cluster < 2 {
return Err(defect("BPB_RootClus", u64::from(params.root_cluster)));
}
}
}
let root_bytes = u64::from(boot.root_entries) * DIR_ENTRY_BYTES;
let root_dir_sectors =
u32::try_from(root_bytes.div_ceil(u64::from(boot.bytes_per_sector))).unwrap_or(u32::MAX);
let overhead = u32::from(boot.reserved_sectors)
.checked_add(
u32::from(boot.fats)
.checked_mul(fat_sectors)
.ok_or_else(|| defect("BPB_FATSz32", u64::from(fat_sectors)))?,
)
.and_then(|n| n.checked_add(root_dir_sectors))
.ok_or_else(|| defect("BPB_RsvdSecCnt", u64::from(boot.reserved_sectors)))?;
let data_sectors = total_sectors
.checked_sub(overhead)
.ok_or_else(|| defect("BPB_TotSec32", u64::from(total_sectors)))?;
let clusters = data_sectors / spc;
if clusters == 0 {
return Err(defect("BPB_SecPerClus", u64::from(spc)));
}
let fat_type = match boot.tail {
BootSectorTail::Fat32 { .. } => FatType::Fat32,
BootSectorTail::Fat1216 { .. } => match FatType::of_cluster_count(clusters) {
FatType::Fat32 => return Err(defect("BPB_TotSec32", u64::from(clusters))),
twelve_or_sixteen => twelve_or_sixteen,
},
};
if clusters > fat_type.max_clusters() {
return Err(defect("BPB_TotSec32", u64::from(clusters)));
}
let table_entries = u64::from(fat_sectors) * u64::from(boot.bytes_per_sector) * 8
/ u64::from(fat_type.entry_bits());
if table_entries < u64::from(clusters) + 2 {
return Err(defect("BPB_FATSz32", table_entries));
}
let fat32 = match boot.tail {
BootSectorTail::Fat1216 { .. } => None,
BootSectorTail::Fat32 { params, .. } => {
if params.root_cluster - 2 >= clusters {
return Err(defect("BPB_RootClus", u64::from(params.root_cluster)));
}
let backup_boot = (params.backup_boot_sector != 0).then_some(params.backup_boot_sector);
let backup_fs_info = backup_boot.and_then(|b| {
let at = u32::from(b) + u32::from(params.fs_info_sector);
(at < u32::from(boot.reserved_sectors)).then_some(at as u16)
});
Some(Fat32Layout {
root_cluster: params.root_cluster,
fs_info_sector: params.fs_info_sector,
backup_boot_sector: backup_boot,
backup_fs_info_sector: backup_fs_info,
})
}
};
Ok(FatLayout {
fat_type,
bytes_per_sector: u32::from(boot.bytes_per_sector),
sectors_per_cluster: spc,
reserved_sectors: u32::from(boot.reserved_sectors),
fats: u32::from(boot.fats),
root_entries: u32::from(boot.root_entries),
total_sectors,
fat_sectors,
root_dir_sectors,
first_data_sector: overhead,
clusters,
fat32,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fat::ondisk::{Fat32Params, VolumeInfo};
use crate::fat::table;
struct Edge {
what: &'static str,
total_sectors: u64,
reserved: u32,
root_entries: u32,
force: Option<FatType>,
clusters: u32,
kind: FatType,
}
const EDGES: &[Edge] = &[
Edge {
what: "one below the largest FAT12",
total_sectors: 4160,
reserved: 21,
root_entries: 512,
force: None,
clusters: 4083,
kind: FatType::Fat12,
},
Edge {
what: "the largest FAT12",
total_sectors: 4160,
reserved: 20,
root_entries: 512,
force: None,
clusters: 4084,
kind: FatType::Fat12,
},
Edge {
what: "the smallest FAT16 any formatter will write",
total_sectors: 4160,
reserved: 9,
root_entries: 512,
force: None,
clusters: 4087,
kind: FatType::Fat16,
},
Edge {
what: "one above the smallest FAT16",
total_sectors: 4160,
reserved: 8,
root_entries: 512,
force: None,
clusters: 4088,
kind: FatType::Fat16,
},
Edge {
what: "one below the largest FAT16",
total_sectors: 66080,
reserved: 13,
root_entries: 512,
force: None,
clusters: 65523,
kind: FatType::Fat16,
},
Edge {
what: "the largest FAT16",
total_sectors: 66080,
reserved: 12,
root_entries: 512,
force: None,
clusters: 65524,
kind: FatType::Fat16,
},
Edge {
what: "the smallest FAT32",
total_sectors: 66592,
reserved: 43,
root_entries: 0,
force: Some(FatType::Fat32),
clusters: 65525,
kind: FatType::Fat32,
},
Edge {
what: "one above the smallest FAT32",
total_sectors: 66592,
reserved: 42,
root_entries: 0,
force: Some(FatType::Fat32),
clusters: 65526,
kind: FatType::Fat32,
},
];
fn request_for(edge: &Edge) -> PlanRequest {
let mut r = PlanRequest::new(edge.total_sectors * 512)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(edge.reserved))
.fats(2);
if edge.root_entries != 0 {
r = r.root_entries(RootEntries::Count(edge.root_entries));
}
if let Some(kind) = edge.force {
r = r.fat_type(FatTypeRequest::Exactly(kind));
}
r
}
#[test]
fn the_planner_reaches_every_type_boundary() {
for edge in EDGES {
let layout = plan_layout(&request_for(edge))
.unwrap_or_else(|e| panic!("{}: the planner refused the row: {e}", edge.what));
assert_eq!(
layout.clusters, edge.clusters,
"{}: the cluster count is not the one these parameters reach",
edge.what
);
assert_eq!(
layout.fat_type, edge.kind,
"{}: {} clusters derives the wrong type",
edge.what, edge.clusters
);
assert_eq!(
(layout.total_sectors - layout.first_data_sector) / layout.sectors_per_cluster,
edge.clusters,
"{}: the planned count and the count the planned fields derive to disagree",
edge.what
);
assert_eq!(FatType::of_cluster_count(layout.clusters), edge.kind);
}
}
#[test]
fn every_table_holds_its_clusters_and_one_unit_less_would_not() {
let mut checked = 0u32;
for bits in [12u32, 16, 32] {
for bytes_per_sector in [512u32, 4096] {
for spc in [1u32, 2, 8] {
for fats in [1u32, 2] {
for aligning in [false, true] {
let unit = if aligning { spc } else { 1 };
for space in 1u32..6_000 {
let Some(c) =
candidate(space, bits, bytes_per_sector, spc, fats, aligning)
else {
continue;
};
let what = format!(
"{bits}-bit, {bytes_per_sector}-byte sectors, {spc} per \
cluster, {fats} tables, aligned {aligning}, {space}"
);
assert_eq!(c.fat_sectors % unit, 0, "{what}");
assert_eq!(c.clusters, (space - fats * c.fat_sectors) / spc);
let room = u64::from(c.fat_sectors) * u64::from(bytes_per_sector);
assert!(
table_bytes(u64::from(c.clusters) + 2, bits) <= room,
"{what}: the table does not hold its clusters"
);
if c.fat_sectors > unit {
let smaller = c.fat_sectors - unit;
let left = (space - fats * smaller) / spc;
let room = u64::from(smaller) * u64::from(bytes_per_sector);
assert!(
table_bytes(u64::from(left) + 2, bits) > room,
"{what}: a smaller table would have held"
);
}
checked += 1;
}
}
}
}
}
}
assert!(checked > 300_000, "only {checked} candidates were checked");
}
#[test]
fn the_thresholds_are_exclusive_below() {
assert_eq!(FatType::of_cluster_count(4084), FatType::Fat12);
assert_eq!(FatType::of_cluster_count(4085), FatType::Fat16);
assert_eq!(FatType::of_cluster_count(65524), FatType::Fat16);
assert_eq!(FatType::of_cluster_count(65525), FatType::Fat32);
}
#[test]
fn the_last_cluster_of_a_maximal_volume_is_an_ordinary_cluster() {
for kind in [FatType::Fat12, FatType::Fat16, FatType::Fat32] {
let last = kind.max_clusters() + 1;
assert!(
table::is_cluster(kind, last),
"{kind:?}: cluster {last:#x} is the highest on a maximal volume and is not an \
ordinary cluster",
);
}
assert!(!table::is_cluster(FatType::Fat32, MAX_CLUSTERS_FAT32 + 2));
assert_eq!(MAX_CLUSTERS_FAT32 + 2, table::bad_cluster(FatType::Fat32));
}
#[test]
fn the_defaults_reproduce_a_conventional_two_hundred_and_fifty_six_mebibyte_fat32() {
let layout = plan_layout(
&PlanRequest::new(256 << 20).fat_type(FatTypeRequest::Exactly(FatType::Fat32)),
)
.expect("plan");
assert_eq!(layout.bytes_per_sector, 512);
assert_eq!(layout.sectors_per_cluster, 1);
assert_eq!(layout.reserved_sectors, 32);
assert_eq!(layout.fats, 2);
assert_eq!(layout.root_entries, 0);
assert_eq!(layout.root_dir_sectors, 0);
assert_eq!(layout.fat_sectors, 4033);
assert_eq!(layout.total_sectors, 524_288);
assert_eq!(layout.clusters, 516_190);
let fat32 = layout
.fat32
.expect("a FAT32 layout carries its own placements");
assert_eq!(fat32.root_cluster, 2);
assert_eq!(fat32.fs_info_sector, 1);
assert_eq!(fat32.backup_boot_sector, Some(6));
}
#[test]
fn the_planner_steps_down_out_of_the_disputed_range() {
for reserved in [19u32, 10] {
let layout = plan_layout(
&PlanRequest::new(4160 * 512)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(reserved))
.root_entries(RootEntries::Count(512)),
)
.unwrap_or_else(|e| panic!("{reserved} reserved: the step down must succeed: {e}"));
assert_eq!(layout.fat_type, FatType::Fat12);
assert_eq!(layout.clusters, MAX_CLUSTERS_FAT12);
assert!(layout.total_sectors < 4160);
assert_eq!(
(layout.total_sectors - layout.first_data_sector) / layout.sectors_per_cluster,
MAX_CLUSTERS_FAT12
);
assert!(4160 - layout.total_sectors < 16 * layout.sectors_per_cluster);
}
}
#[test]
fn a_fat16_in_the_disputed_range_is_refused_by_name() {
let fat16_at = |reserved: u32| {
plan_layout(
&PlanRequest::new(4160 * 512)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(reserved))
.root_entries(RootEntries::Count(512))
.fat_type(FatTypeRequest::Exactly(FatType::Fat16)),
)
};
assert_eq!(fat16_at(9).expect("plan").clusters, MIN_CLUSTERS_FAT16);
for (reserved, expected) in [(11u32, 4085u32), (10, 4086)] {
match fat16_at(reserved).expect_err("a disputed FAT16 has no way out here") {
GeometryError::AmbiguousClusterCount {
clusters,
low,
high,
high_plus_one,
} => {
assert_eq!(clusters, expected);
assert_eq!(
(low, high),
(MAX_CLUSTERS_FAT12 + 1, MIN_CLUSTERS_FAT16 - 1)
);
assert_eq!(high_plus_one, MIN_CLUSTERS_FAT16);
}
other => panic!("expected the disputed range to be named, got {other}"),
}
}
}
#[test]
fn an_undersized_fat32_needs_the_acknowledgement() {
let base = PlanRequest::new(8 << 20)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(32));
let err = plan_layout(&base.fat_type(FatTypeRequest::Exactly(FatType::Fat32)))
.expect_err("a conformant FAT32 does not fit here");
assert!(matches!(
err,
GeometryError::ClustersBelowMinimum {
requested: FatType::Fat32,
minimum: MIN_CLUSTERS_FAT32,
..
}
));
let layout = plan_layout(&base.fat_type(FatTypeRequest::UndersizedFat32))
.expect("the acknowledgement produces it");
assert_eq!(layout.fat_type, FatType::Fat32);
assert!(layout.clusters < MIN_CLUSTERS_FAT32);
assert!(layout.fat32.is_some());
}
#[test]
fn there_is_no_acknowledgement_for_an_undersized_fat16() {
let err = plan_layout(
&PlanRequest::new(1 << 20)
.cluster_size(ClusterSize::Sectors(1))
.fat_type(FatTypeRequest::Exactly(FatType::Fat16)),
)
.expect_err("a FAT16 this small is unreachable");
assert!(matches!(
err,
GeometryError::ClustersBelowMinimum {
requested: FatType::Fat16,
..
}
));
}
#[test]
fn auto_grows_the_cluster_until_a_type_fits() {
let layout = plan_layout(&PlanRequest::new(1 << 30)).expect("plan");
assert_eq!(layout.fat_type, FatType::Fat32);
assert!(layout.clusters <= MAX_CLUSTERS_FAT32);
assert!(layout.sectors_per_cluster.is_power_of_two());
let err = plan_layout(
&PlanRequest::new(1 << 30)
.cluster_size(ClusterSize::Sectors(1))
.fat_type(FatTypeRequest::Exactly(FatType::Fat16)),
)
.expect_err("FAT16 cannot address a gibibyte in 512-byte clusters");
assert!(matches!(
err,
GeometryError::ClustersAboveMaximum {
requested: FatType::Fat16,
maximum: MAX_CLUSTERS_FAT16,
..
}
));
}
#[test]
fn auto_selects_fat32_from_half_a_gibibyte_up() {
assert_eq!(
plan_layout(&PlanRequest::new(FAT32_AUTO_THRESHOLD_BYTES))
.expect("plan")
.fat_type,
FatType::Fat32
);
assert_eq!(
plan_layout(&PlanRequest::new(FAT32_AUTO_THRESHOLD_BYTES - (1 << 20)))
.expect("plan")
.fat_type,
FatType::Fat16
);
}
#[test]
fn the_layout_is_consistent_at_every_sector_size_the_format_defines() {
for bytes_per_sector in [512u32, 1024, 2048, 4096] {
let layout =
plan_layout(&PlanRequest::new(512 << 20).bytes_per_sector(bytes_per_sector))
.unwrap_or_else(|e| panic!("{bytes_per_sector}-byte sectors: {e}"));
assert_eq!(layout.bytes_per_sector, bytes_per_sector);
assert_eq!(
(layout.total_sectors - layout.first_data_sector) / layout.sectors_per_cluster,
layout.clusters,
"{bytes_per_sector}-byte sectors: the planned count and the derived count \
disagree"
);
assert_eq!(FatType::of_cluster_count(layout.clusters), layout.fat_type);
let volume_sectors = (512 << 20) / u64::from(bytes_per_sector);
assert_eq!(u64::from(layout.total_sectors), volume_sectors);
}
for bad in [128u32, 256, 8192, 0, 513] {
assert!(matches!(
plan_layout(&PlanRequest::new(64 << 20).bytes_per_sector(bad)),
Err(GeometryError::SectorSizeUnsupported { .. })
));
}
}
#[test]
fn the_whole_volume_is_described() {
for sectors in [20_001u64, 66_081, 524_289] {
let layout = plan_layout(&PlanRequest::new(sectors * 512)).expect("plan");
assert_eq!(u64::from(layout.total_sectors), sectors);
}
let layout = plan_layout(&PlanRequest::new(20_001 * 512 + 511)).expect("plan");
assert_eq!(layout.total_sectors, 20_001);
}
#[test]
fn the_regions_are_cluster_aligned_above_the_threshold_and_not_below_it() {
let layout = plan_layout(
&PlanRequest::new(64 << 20)
.cluster_size(ClusterSize::Sectors(8))
.reserved_sectors(ReservedSectors::Count(3)),
)
.expect("plan");
assert!(layout.total_sectors > ALIGNMENT_THRESHOLD_SECTORS);
assert_eq!(layout.reserved_sectors % 8, 0);
assert_eq!(layout.fat_sectors % 8, 0);
assert_eq!(layout.root_dir_sectors % 8, 0);
assert_eq!(layout.first_data_sector % 8, 0);
let layout = plan_layout(
&PlanRequest::new(ALIGNMENT_THRESHOLD_SECTORS as u64 * 512)
.cluster_size(ClusterSize::Sectors(8))
.reserved_sectors(ReservedSectors::Count(3)),
)
.expect("plan");
assert_eq!(layout.reserved_sectors, 3);
}
#[test]
fn the_root_entry_count_recorded_is_the_one_the_region_holds() {
let layout = plan_layout(
&PlanRequest::new(64 << 20)
.cluster_size(ClusterSize::Sectors(8))
.root_entries(RootEntries::Count(512)),
)
.expect("plan");
assert_eq!(
(layout.root_entries * 32).div_ceil(layout.bytes_per_sector),
layout.root_dir_sectors
);
assert!(layout.root_entries >= 512);
for entries in [1u32, 16, 17, 100, 200, 224, 512, 1000] {
for bytes_per_sector in [512u32, 4096] {
for (volume, spc) in [(2u64 << 20, 1u32), (64 << 20, 1), (64 << 20, 8)] {
let layout = plan_layout(
&PlanRequest::new(volume)
.bytes_per_sector(bytes_per_sector)
.cluster_size(ClusterSize::Sectors(spc))
.root_entries(RootEntries::Count(entries))
.fat_type(FatTypeRequest::Exactly(FatType::Fat16)),
);
let Ok(layout) = layout else { continue };
let what = format!(
"{entries} entries, {bytes_per_sector}-byte sectors, {spc} \
sectors per cluster, {volume} bytes"
);
assert_eq!(
(layout.root_entries * 32).div_ceil(layout.bytes_per_sector),
layout.root_dir_sectors,
"{what}: the recorded count describes a different region than was placed"
);
assert!(
layout.root_entries >= entries,
"{what}: the recorded count is below what was asked for"
);
}
}
}
let layout = plan_layout(
&PlanRequest::new(2 << 20)
.cluster_size(ClusterSize::Sectors(1))
.root_entries(RootEntries::Count(200)),
)
.expect("plan");
assert!(layout.total_sectors <= ALIGNMENT_THRESHOLD_SECTORS);
assert_eq!(layout.root_entries, 200);
assert_eq!(layout.root_dir_sectors, 13);
}
#[test]
fn the_step_down_applies_only_where_the_volume_is_between_the_two_types() {
for volume in [64u64 << 20, 256 << 20, 511 << 20] {
let err = plan_layout(&PlanRequest::new(volume).cluster_size(ClusterSize::Sectors(1)))
.expect_err("a volume no type fits at one sector per cluster must be refused");
assert!(
matches!(err, GeometryError::NoTypeFits { .. }),
"{volume} bytes: {err}"
);
}
let mut stepped = 0;
for reserved in 1..=48u32 {
let layout = plan_layout(
&PlanRequest::new(4160 * 512)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(reserved))
.root_entries(RootEntries::Count(512)),
)
.unwrap_or_else(|e| panic!("{reserved} reserved: {e}"));
if layout.total_sectors < 4160 {
assert_eq!(layout.fat_type, FatType::Fat12, "{reserved} reserved");
assert_eq!(layout.clusters, MAX_CLUSTERS_FAT12, "{reserved} reserved");
stepped += 1;
}
}
assert!(
stepped > 0,
"no reserved count reached the range between the two types, so this fixture no \
longer exercises the step down"
);
}
#[test]
fn the_addressing_helpers_refuse_what_is_not_there() {
let layout = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
assert_eq!(layout.fat_start_sector(0), Some(layout.reserved_sectors));
assert_eq!(
layout.fat_start_sector(1),
Some(layout.reserved_sectors + layout.fat_sectors)
);
assert_eq!(layout.fat_start_sector(layout.fats), None);
assert_eq!(layout.cluster_start_sector(0), None);
assert_eq!(layout.cluster_start_sector(1), None);
assert_eq!(
layout.cluster_start_sector(2),
Some(layout.first_data_sector)
);
assert!(layout.cluster_start_sector(layout.clusters + 1).is_some());
assert_eq!(layout.cluster_start_sector(layout.clusters + 2), None);
assert!(layout.max_table_entries() >= layout.clusters + 2);
}
#[test]
fn a_fat32_layout_carries_the_fat32_placements_and_no_other_does() {
let small = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
assert_eq!(small.fat_type, FatType::Fat16);
assert!(small.fat32.is_none());
assert!(small.root_dir_start_sector().is_some());
let large = plan_layout(&PlanRequest::new(1 << 30)).expect("plan");
assert_eq!(large.fat_type, FatType::Fat32);
assert!(large.fat32.is_some());
assert_eq!(large.root_entries, 0);
assert_eq!(large.root_dir_sectors, 0);
assert!(large.root_dir_start_sector().is_none());
}
#[test]
fn the_backup_boot_sector_falls_back_as_the_reserved_region_shrinks() {
for (reserved, backup) in [
(32, Some(6)),
(8, Some(6)),
(7, Some(6)),
(6, Some(4)),
(5, Some(3)),
(4, Some(2)),
(3, Some(2)),
(2, None),
] {
assert_eq!(backup_boot_sector(reserved), backup, "{reserved} reserved");
}
}
#[test]
fn the_parameters_the_format_does_not_allow_are_named() {
let base = PlanRequest::new(64 << 20);
assert!(matches!(
plan_layout(&base.fats(0)),
Err(GeometryError::FatCountUnsupported { fats: 0 })
));
assert!(matches!(
plan_layout(&base.fats(3)),
Err(GeometryError::FatCountUnsupported { fats: 3 })
));
assert!(matches!(
plan_layout(&base.cluster_size(ClusterSize::Sectors(3))),
Err(GeometryError::ClusterSizeUnsupported { .. })
));
assert!(matches!(
plan_layout(&base.cluster_size(ClusterSize::Sectors(256))),
Err(GeometryError::ClusterSizeUnsupported { .. })
));
assert!(matches!(
plan_layout(&base.cluster_size(ClusterSize::Sectors(128))),
Err(GeometryError::ClusterTooLarge {
limit: MAX_BYTES_PER_CLUSTER,
..
})
));
assert!(matches!(
plan_layout(&base.reserved_sectors(ReservedSectors::Count(0))),
Err(GeometryError::ReservedSectorsTooFew { minimum: 1, .. })
));
assert!(matches!(
plan_layout(
&base
.fat_type(FatTypeRequest::Exactly(FatType::Fat32))
.reserved_sectors(ReservedSectors::Count(1))
),
Err(GeometryError::ReservedSectorsTooFew { minimum: 2, .. })
));
assert!(matches!(
plan_layout(
&PlanRequest::new(1 << 30).reserved_sectors(ReservedSectors::Count(70_000))
),
Err(GeometryError::ReservedSectorsTooMany {
reserved: 70_000,
..
})
));
let wide = PlanRequest::new(4 << 30).cluster_size(ClusterSize::Sectors(64));
let aligned_past =
plan_layout(&wide.reserved_sectors(ReservedSectors::Count(u32::from(u16::MAX))));
assert!(
matches!(
aligned_past,
Err(GeometryError::ReservedSectorsTooMany {
reserved: 65_536,
..
})
),
"{aligned_past:?}"
);
assert_eq!(
plan_layout(&wide.reserved_sectors(ReservedSectors::Count(65_472)))
.expect("plan")
.reserved_sectors,
65_472
);
assert!(matches!(
plan_layout(&base.root_entries(RootEntries::Count(0))),
Err(GeometryError::RootEntriesUnsupported { .. })
));
assert!(matches!(
plan_layout(&base.root_entries(RootEntries::Count(100_000))),
Err(GeometryError::RootEntriesUnsupported { .. })
));
for request in [
FatTypeRequest::Exactly(FatType::Fat32),
FatTypeRequest::UndersizedFat32,
FatTypeRequest::Auto,
] {
assert!(
matches!(
plan_layout(
&PlanRequest::new(1 << 30)
.fat_type(request)
.root_entries(RootEntries::Count(512))
),
Err(GeometryError::RootEntriesOnFat32 { root_entries: 512 })
),
"{request:?} on a volume this size reaches FAT32, so a root entry count \
must be refused rather than ignored"
);
}
}
#[test]
fn a_volume_with_no_room_for_a_data_region_is_refused() {
for bytes in [0u64, 512, 4096, 16 << 10] {
assert!(
matches!(
plan_layout(&PlanRequest::new(bytes)),
Err(GeometryError::NoTypeFits { .. })
),
"a volume of {bytes} bytes must be refused rather than planned"
);
}
let layout = plan_layout(&PlanRequest::new(32 << 10)).expect("plan");
assert_eq!(layout.fat_type, FatType::Fat12);
assert!(layout.clusters > 0);
assert_eq!(
(layout.total_sectors - layout.first_data_sector) / layout.sectors_per_cluster,
layout.clusters
);
}
#[test]
fn a_volume_past_a_thirty_two_bit_sector_count_is_refused() {
let sectors = u64::from(u32::MAX) + 1;
assert!(matches!(
plan_layout(&PlanRequest::new(sectors * 512)),
Err(GeometryError::VolumeTooLarge { .. })
));
assert!(plan_layout(&PlanRequest::new(sectors * 512).bytes_per_sector(4096)).is_ok());
}
#[test]
fn planning_is_deterministic() {
let request = PlanRequest::new(3 << 30).bytes_per_sector(1024);
assert_eq!(plan_layout(&request), plan_layout(&request));
}
#[test]
fn every_planned_volume_is_self_consistent() {
for mib in [1u64, 3, 8, 33, 64, 260, 511, 512, 1024, 4096, 16384] {
for bytes_per_sector in [512u32, 4096] {
let request = PlanRequest::new(mib << 20).bytes_per_sector(bytes_per_sector);
let Ok(layout) = plan_layout(&request) else {
continue;
};
let derived =
(layout.total_sectors - layout.first_data_sector) / layout.sectors_per_cluster;
assert_eq!(derived, layout.clusters, "{mib} MiB at {bytes_per_sector}");
assert_eq!(
FatType::of_cluster_count(layout.clusters),
layout.fat_type,
"{mib} MiB at {bytes_per_sector}"
);
assert_eq!(
layout.first_data_sector,
layout.reserved_sectors
+ layout.fats * layout.fat_sectors
+ layout.root_dir_sectors,
"{mib} MiB at {bytes_per_sector}"
);
assert!(
layout.first_data_sector + layout.data_sectors() <= layout.total_sectors,
"{mib} MiB at {bytes_per_sector}: the data region runs past the volume"
);
assert!(
layout.max_table_entries() >= layout.clusters + 2,
"{mib} MiB at {bytes_per_sector}: the table cannot index its own clusters"
);
assert!(
layout.clusters >= layout.fat_type.min_clusters()
&& layout.clusters <= layout.fat_type.max_clusters(),
"{mib} MiB at {bytes_per_sector}: {} clusters is outside {}'s range",
layout.clusters,
layout.fat_type
);
assert!(
u64::from(layout.bytes_per_cluster()) <= u64::from(MAX_BYTES_PER_CLUSTER),
"{mib} MiB at {bytes_per_sector}: the allocation unit is too large"
);
assert_layout_is_coherent(&layout, &format!("{mib} MiB at {bytes_per_sector}"));
}
}
}
fn assert_layout_is_coherent(layout: &FatLayout, what: &str) {
assert_eq!(
layout.fat32.is_some(),
layout.fat_type == FatType::Fat32,
"{what}: {} beside {:?} placements",
layout.fat_type,
layout.fat32.map(|_| "FAT32"),
);
assert_eq!(
layout.fat32.is_none(),
layout.root_entries != 0,
"{what}: {} root entries on a {} volume",
layout.root_entries,
layout.fat_type,
);
assert_eq!(
layout.root_dir_sectors == 0,
layout.fat32.is_some(),
"{what}: {} root sectors on a {} volume",
layout.root_dir_sectors,
layout.fat_type,
);
}
fn volume_info(fs_type: &[u8; 8]) -> VolumeInfo {
VolumeInfo {
drive_number: 0x80,
reserved: 0,
ext_boot_signature: 0x29,
volume_id: 0x1234_abcd,
label: VolumeInfo::NO_NAME,
fs_type: *fs_type,
}
}
fn fat1216_counting(clusters: u32, fat_sectors: u16) -> (BootSector, u64) {
let root_entries = 512u16;
let root_dir_sectors = u32::from(root_entries) * DIR_ENTRY_BYTES as u32 / 512;
let total = 1 + u32::from(fat_sectors) + root_dir_sectors + clusters;
let boot = BootSector {
jump: [0xEB, 0x3C, 0x90],
oem_name: *b"ferrosys",
bytes_per_sector: 512,
sectors_per_cluster: 1,
reserved_sectors: 1,
fats: 1,
root_entries,
total_sectors_16: 0,
media: 0xF8,
fat_sectors_16: fat_sectors,
sectors_per_track: 32,
heads: 64,
hidden_sectors: 0,
total_sectors_32: total,
tail: BootSectorTail::Fat1216 {
volume: volume_info(b"FAT16 "),
},
};
(boot, u64::from(total) * 512)
}
fn fat32_counting(clusters: u32, fat_sectors: u32) -> (BootSector, u64) {
let total = 32 + fat_sectors + clusters;
let boot = BootSector {
jump: [0xEB, 0x58, 0x90],
oem_name: *b"ferrosys",
bytes_per_sector: 512,
sectors_per_cluster: 1,
reserved_sectors: 32,
fats: 1,
root_entries: 0,
total_sectors_16: 0,
media: 0xF8,
fat_sectors_16: 0,
sectors_per_track: 32,
heads: 64,
hidden_sectors: 0,
total_sectors_32: total,
tail: BootSectorTail::Fat32 {
params: Fat32Params {
fat_sectors,
ext_flags: 0,
version: 0,
root_cluster: 2,
fs_info_sector: 1,
backup_boot_sector: 6,
},
volume: volume_info(b"FAT32 "),
},
};
(boot, u64::from(total) * 512)
}
#[test]
fn a_twelve_or_sixteen_tail_never_derives_to_fat32() {
let (boot, available) = fat1216_counting(MIN_CLUSTERS_FAT32, 512);
let defect = layout_from_boot(&boot, available).expect_err("the shape is refused");
assert_eq!(defect.value, u64::from(MIN_CLUSTERS_FAT32));
let (boot, available) = fat1216_counting(MAX_CLUSTERS_FAT16, 512);
let layout = layout_from_boot(&boot, available).expect("an ordinary FAT16 volume");
assert_eq!(layout.fat_type, FatType::Fat16);
assert_eq!(layout.clusters, MAX_CLUSTERS_FAT16);
assert_layout_is_coherent(&layout, "a recovered FAT16");
}
#[test]
fn a_count_above_what_the_type_addresses_is_refused() {
let over = MAX_CLUSTERS_FAT32 + 1;
let (boot, available) = fat32_counting(over, 2_097_152);
let defect = layout_from_boot(&boot, available).expect_err("the count is refused");
assert_eq!(defect.value, u64::from(over));
let (boot, available) = fat32_counting(MAX_CLUSTERS_FAT32, 2_097_152);
let layout = layout_from_boot(&boot, available).expect("the largest FAT32 there is");
assert_eq!(layout.fat_type, FatType::Fat32);
assert_eq!(layout.clusters, MAX_CLUSTERS_FAT32);
assert_layout_is_coherent(&layout, "a recovered FAT32");
assert!(layout.clusters + 1 < table::end_of_chain(FatType::Fat32));
assert!(layout.clusters + 1 < table::bad_cluster(FatType::Fat32));
}
#[test]
fn the_reader_holds_a_count_to_the_bound_the_planner_refuses_to_cross() {
for kind in [FatType::Fat12, FatType::Fat16, FatType::Fat32] {
let err = plan_layout(
&PlanRequest::new(u64::from(kind.max_clusters()) * 512 * 2)
.cluster_size(ClusterSize::Sectors(1))
.fat_type(FatTypeRequest::Exactly(kind)),
)
.expect_err("a volume past what the type addresses");
assert!(
matches!(err, GeometryError::ClustersAboveMaximum { requested, maximum, .. }
if requested == kind && maximum == kind.max_clusters()),
"{kind}: {err}"
);
}
}
}