use super::ondisk::{
BOOT_REGION_SECTORS, FILE_SYSTEM_MAJOR_REVISION, MAX_CLUSTER_SHIFT, MainBootSector,
RECOMMENDED_UPCASE_BYTES,
};
#[cfg(feature = "serde")]
use serde::Serialize;
pub const FIRST_CLUSTER: u32 = 2;
pub const MAX_CLUSTER_COUNT: u32 = 0xFFFF_FFF5;
pub const MIN_VOLUME_BYTES: u64 = 1 << 20;
#[must_use]
pub(crate) const fn min_volume_sectors(bytes_per_sector: u64) -> u64 {
MIN_VOLUME_BYTES / bytes_per_sector
}
pub const MAX_BYTES_PER_CLUSTER: u32 = 1 << MAX_CLUSTER_SHIFT;
pub const DEFAULT_BOUNDARY_ALIGN: u32 = 1 << 20;
const RESERVED_SECTORS: u64 = 2 * BOOT_REGION_SECTORS;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum ClusterSize {
#[default]
Auto,
Bytes(u32),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum BoundaryAlign {
#[default]
Auto,
Bytes(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 {bytes_per_cluster} bytes is not a power of two at least as large as \
the {bytes_per_sector}-byte sector"
)]
#[non_exhaustive]
ClusterSizeUnsupported {
bytes_per_cluster: u32,
bytes_per_sector: u32,
},
#[error("cluster size {bytes_per_cluster} bytes exceeds the {limit}-byte maximum")]
#[non_exhaustive]
ClusterTooLarge {
bytes_per_cluster: u32,
limit: u32,
},
#[error(
"boundary alignment {bytes} is not a power of two at least as large as the \
{bytes_per_sector}-byte sector"
)]
#[non_exhaustive]
BoundaryAlignUnsupported {
bytes: u32,
bytes_per_sector: u32,
},
#[error("a volume of {sectors} sectors is below the {minimum}-sector minimum")]
#[non_exhaustive]
VolumeTooSmall {
sectors: u64,
minimum: u64,
},
#[error(
"the allocation table and the alignment leave no cluster heap: the heap would begin \
at byte {heap_at} of a {volume_bytes}-byte volume"
)]
#[non_exhaustive]
NoClusterHeap {
heap_at: u64,
volume_bytes: u64,
},
#[error("{clusters} clusters exceeds the {limit} a cluster number can address")]
#[non_exhaustive]
TooManyClusters {
clusters: u64,
limit: u32,
},
#[error(
"a heap of {clusters} clusters cannot hold the allocation bitmap, the up-case table \
and the root directory, which need {needed}"
)]
#[non_exhaustive]
HeapTooSmall {
clusters: u32,
needed: u32,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct ExfatLayout {
pub bytes_per_sector: u32,
pub bytes_per_cluster: u32,
pub volume_length: u64,
pub fat_offset: u32,
pub fat_length: u32,
pub cluster_heap_offset: u32,
pub cluster_count: u32,
pub first_cluster_of_root: u32,
pub bitmap_cluster: u32,
pub bitmap_bytes: u64,
pub upcase_cluster: u32,
pub upcase_bytes: u64,
}
impl ExfatLayout {
#[must_use]
pub const fn sectors_per_cluster(&self) -> u32 {
self.bytes_per_cluster / self.bytes_per_sector
}
#[must_use]
pub const fn bytes_per_sector_shift(&self) -> u8 {
self.bytes_per_sector.trailing_zeros() as u8
}
#[must_use]
pub const fn sectors_per_cluster_shift(&self) -> u8 {
self.sectors_per_cluster().trailing_zeros() as u8
}
#[must_use]
pub const fn total_bytes(&self) -> u64 {
self.volume_length * self.bytes_per_sector as u64
}
#[must_use]
pub const fn boot_region_sector(&self, which: u32) -> Option<u64> {
match which {
0 => Some(0),
1 => Some(BOOT_REGION_SECTORS),
_ => None,
}
}
#[must_use]
pub const fn cluster_start_sector(&self, n: u32) -> Option<u64> {
if n < FIRST_CLUSTER || n - FIRST_CLUSTER >= self.cluster_count {
return None;
}
Some(
self.cluster_heap_offset as u64
+ (n - FIRST_CLUSTER) as u64 * self.sectors_per_cluster() as u64,
)
}
#[must_use]
pub const fn cluster_start_byte(&self, n: u32) -> Option<u64> {
match self.cluster_start_sector(n) {
Some(sector) => Some(sector * self.bytes_per_sector as u64),
None => None,
}
}
#[must_use]
pub const fn fat_entry_byte(&self, n: u32) -> Option<u64> {
if n as u64 >= FIRST_CLUSTER as u64 + self.cluster_count as u64 {
return None;
}
Some(self.fat_offset as u64 * self.bytes_per_sector as u64 + n as u64 * 4)
}
#[must_use]
pub const fn clusters_for(&self, bytes: u64) -> u64 {
bytes.div_ceil(self.bytes_per_cluster as u64)
}
#[must_use]
pub const fn heap_bytes(&self) -> u64 {
self.cluster_count as u64 * self.bytes_per_cluster as u64
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct PlanRequest {
pub volume_bytes: u64,
pub bytes_per_sector: u32,
pub cluster_size: ClusterSize,
pub boundary_align: BoundaryAlign,
}
impl PlanRequest {
#[must_use]
pub const fn new(volume_bytes: u64) -> Self {
Self {
volume_bytes,
bytes_per_sector: 512,
cluster_size: ClusterSize::Auto,
boundary_align: BoundaryAlign::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.cluster_size = size;
self
}
#[must_use]
pub const fn boundary_align(mut self, align: BoundaryAlign) -> Self {
self.boundary_align = align;
self
}
}
#[must_use]
pub const fn conventional_cluster_size(volume_bytes: u64) -> u32 {
if volume_bytes < 7 << 20 {
512
} else if volume_bytes <= 256 << 20 {
4 << 10
} else if volume_bytes <= 32 << 30 {
32 << 10
} else {
128 << 10
}
}
pub fn plan_layout(request: &PlanRequest) -> Result<ExfatLayout, GeometryError> {
let bytes_per_sector = request.bytes_per_sector;
if !matches!(bytes_per_sector, 512 | 1024 | 2048 | 4096) {
return Err(GeometryError::SectorSizeUnsupported { bytes_per_sector });
}
let sector = u64::from(bytes_per_sector);
let volume_length = request.volume_bytes / sector;
let minimum = min_volume_sectors(sector);
if volume_length < minimum {
return Err(GeometryError::VolumeTooSmall {
sectors: volume_length,
minimum,
});
}
let volume_bytes = volume_length * sector;
let bytes_per_cluster = match request.cluster_size {
ClusterSize::Auto => conventional_cluster_size(volume_bytes),
ClusterSize::Bytes(bytes) => bytes,
};
if !bytes_per_cluster.is_power_of_two() || bytes_per_cluster < bytes_per_sector {
return Err(GeometryError::ClusterSizeUnsupported {
bytes_per_cluster,
bytes_per_sector,
});
}
if bytes_per_cluster > MAX_BYTES_PER_CLUSTER {
return Err(GeometryError::ClusterTooLarge {
bytes_per_cluster,
limit: MAX_BYTES_PER_CLUSTER,
});
}
let cluster = u64::from(bytes_per_cluster);
let align = match request.boundary_align {
BoundaryAlign::Auto => DEFAULT_BOUNDARY_ALIGN,
BoundaryAlign::Bytes(bytes) => bytes,
};
if !align.is_power_of_two() || align < bytes_per_sector {
return Err(GeometryError::BoundaryAlignUnsupported {
bytes: align,
bytes_per_sector,
});
}
let align = u64::from(align);
let fat_at = round_up(RESERVED_SECTORS * sector, align);
let Some(for_table_and_heap) = volume_bytes.checked_sub(fat_at + TABLE_TAIL) else {
return Err(GeometryError::NoClusterHeap {
heap_at: fat_at,
volume_bytes,
});
};
let max_clusters = for_table_and_heap / (cluster + 4) + 1;
let fat_bytes = round_up((max_clusters + 2) * 4, sector);
let fat_length =
u32::try_from(fat_bytes / sector).map_err(|_| GeometryError::TooManyClusters {
clusters: max_clusters,
limit: MAX_CLUSTER_COUNT,
})?;
let heap_at = round_up(fat_at + fat_bytes, align);
if heap_at >= volume_bytes {
return Err(GeometryError::NoClusterHeap {
heap_at,
volume_bytes,
});
}
let clusters = (volume_bytes - heap_at) / cluster;
if clusters > u64::from(MAX_CLUSTER_COUNT) {
return Err(GeometryError::TooManyClusters {
clusters,
limit: MAX_CLUSTER_COUNT,
});
}
let cluster_count = clusters as u32;
let bitmap_bytes = u64::from(cluster_count).div_ceil(8);
let bitmap_clusters = bitmap_bytes.div_ceil(cluster);
let upcase_bytes = RECOMMENDED_UPCASE_BYTES;
let upcase_clusters = upcase_bytes.div_ceil(cluster);
let residents = bitmap_clusters + upcase_clusters + 1;
if residents > u64::from(cluster_count) {
return Err(GeometryError::HeapTooSmall {
clusters: cluster_count,
needed: residents.min(u64::from(u32::MAX)) as u32,
});
}
let bitmap_cluster = FIRST_CLUSTER;
let upcase_cluster = bitmap_cluster + bitmap_clusters as u32;
let first_cluster_of_root = upcase_cluster + upcase_clusters as u32;
Ok(ExfatLayout {
bytes_per_sector,
bytes_per_cluster,
volume_length,
fat_offset: sectors_of(fat_at, sector),
fat_length,
cluster_heap_offset: sectors_of(heap_at, sector),
cluster_count,
first_cluster_of_root,
bitmap_cluster,
bitmap_bytes,
upcase_cluster,
upcase_bytes,
})
}
const TABLE_TAIL: u64 = 4 * 2 + 1;
const fn round_up(value: u64, to: u64) -> u64 {
value.div_ceil(to) * to
}
const fn sectors_of(bytes: u64, sector: u64) -> u32 {
let sectors = bytes / sector;
if sectors > u32::MAX as u64 {
u32::MAX
} else {
sectors as u32
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BootDefect {
#[error("a volume of revision {major}.{minor} is not one this reads; the format defines 1")]
#[non_exhaustive]
FileSystemRevision {
major: u8,
minor: u8,
},
#[error("sector size shift {shift} is outside the 9 to 12 the format defines")]
#[non_exhaustive]
SectorShift {
shift: u8,
},
#[error(
"sector shift {sector_shift} and cluster shift {cluster_shift} sum past the \
{limit} the format allows"
)]
#[non_exhaustive]
ClusterShift {
sector_shift: u8,
cluster_shift: u8,
limit: u8,
},
#[error("a volume of {sectors} sectors does not fit: {why}")]
#[non_exhaustive]
VolumeLength {
sectors: u64,
why: &'static str,
},
#[error("{region} does not fit within the volume: {why}")]
#[non_exhaustive]
RegionOutsideVolume {
region: &'static str,
why: &'static str,
},
#[error(
"an allocation table of {table_bytes} bytes cannot hold entries for {cluster_count} \
clusters and the two reserved numbers"
)]
#[non_exhaustive]
TableTooShort {
table_bytes: u64,
cluster_count: u32,
},
#[error("the root directory begins at cluster {cluster}, which the volume does not have")]
#[non_exhaustive]
RootOutsideHeap {
cluster: u32,
},
}
pub(crate) fn layout_from_boot(
boot: &MainBootSector,
available: u64,
) -> Result<ExfatLayout, BootDefect> {
if boot.major_revision() != FILE_SYSTEM_MAJOR_REVISION {
return Err(BootDefect::FileSystemRevision {
major: boot.major_revision(),
minor: boot.minor_revision(),
});
}
let Some(bytes_per_sector) = boot.bytes_per_sector() else {
return Err(BootDefect::SectorShift {
shift: boot.bytes_per_sector_shift,
});
};
let Some(bytes_per_cluster) = boot.bytes_per_cluster() else {
return Err(BootDefect::ClusterShift {
sector_shift: boot.bytes_per_sector_shift,
cluster_shift: boot.sectors_per_cluster_shift,
limit: MAX_CLUSTER_SHIFT,
});
};
let sector = u64::from(bytes_per_sector);
let volume_length = boot.volume_length;
if volume_length < min_volume_sectors(sector) {
return Err(BootDefect::VolumeLength {
sectors: volume_length,
why: "fewer sectors than two boot regions and a filesystem need",
});
}
let Some(volume_bytes) = volume_length.checked_mul(sector) else {
return Err(BootDefect::VolumeLength {
sectors: volume_length,
why: "the length in bytes does not fit in 64 bits",
});
};
if volume_bytes > available {
return Err(BootDefect::VolumeLength {
sectors: volume_length,
why: "the source does not hold that many",
});
}
let fat_at = u64::from(boot.fat_offset) * sector;
let fat_bytes = u64::from(boot.fat_length) * sector;
if fat_at < RESERVED_SECTORS * sector {
return Err(BootDefect::RegionOutsideVolume {
region: "the allocation table",
why: "it begins inside the boot regions",
});
}
let heap_at = u64::from(boot.cluster_heap_offset) * sector;
let Some(fat_end) = fat_at.checked_add(fat_bytes) else {
return Err(BootDefect::RegionOutsideVolume {
region: "the allocation table",
why: "its end does not fit in 64 bits",
});
};
if fat_end > heap_at {
return Err(BootDefect::RegionOutsideVolume {
region: "the allocation table",
why: "it runs into the cluster heap",
});
}
if heap_at >= volume_bytes {
return Err(BootDefect::RegionOutsideVolume {
region: "the cluster heap",
why: "it begins at or past the end of the volume",
});
}
let cluster_count = boot.cluster_count;
if cluster_count > MAX_CLUSTER_COUNT {
return Err(BootDefect::RegionOutsideVolume {
region: "the cluster heap",
why: "it claims more clusters than a cluster number addresses",
});
}
let heap_bytes = u64::from(cluster_count) * u64::from(bytes_per_cluster);
if heap_bytes > volume_bytes - heap_at {
return Err(BootDefect::RegionOutsideVolume {
region: "the cluster heap",
why: "its clusters run past the end of the volume",
});
}
if fat_bytes / 4 < u64::from(cluster_count) + u64::from(FIRST_CLUSTER) {
return Err(BootDefect::TableTooShort {
table_bytes: fat_bytes,
cluster_count,
});
}
let root = boot.first_cluster_of_root;
if root < FIRST_CLUSTER || u64::from(root - FIRST_CLUSTER) >= u64::from(cluster_count) {
return Err(BootDefect::RootOutsideHeap { cluster: root });
}
Ok(ExfatLayout {
bytes_per_sector,
bytes_per_cluster,
volume_length,
fat_offset: boot.fat_offset,
fat_length: boot.fat_length,
cluster_heap_offset: boot.cluster_heap_offset,
cluster_count,
first_cluster_of_root: root,
bitmap_cluster: FIRST_CLUSTER,
bitmap_bytes: u64::from(cluster_count).div_ceil(8),
upcase_cluster: FIRST_CLUSTER,
upcase_bytes: RECOMMENDED_UPCASE_BYTES,
})
}
#[cfg(test)]
mod tests {
use super::*;
struct Row {
what: &'static str,
volume_bytes: u64,
bytes_per_sector: u32,
cluster_size: ClusterSize,
fat_offset: u32,
fat_length: u32,
cluster_heap_offset: u32,
cluster_count: u32,
first_cluster_of_root: u32,
bitmap_bytes: u64,
upcase_cluster: u32,
}
impl Row {
fn request(&self) -> PlanRequest {
PlanRequest::new(self.volume_bytes)
.bytes_per_sector(self.bytes_per_sector)
.cluster_size(self.cluster_size)
}
}
const BASELINE: &[Row] = &[
Row {
what: "the lowest cluster band, where the up-case table spans twelve clusters",
volume_bytes: 4 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Auto,
fat_offset: 2048,
fat_length: 48,
cluster_heap_offset: 4096,
cluster_count: 4096,
first_cluster_of_root: 15,
bitmap_bytes: 512,
upcase_cluster: 3,
},
Row {
what: "the lowest band again, where the bitmap needs a second cluster",
volume_bytes: 6 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Auto,
fat_offset: 2048,
fat_length: 80,
cluster_heap_offset: 4096,
cluster_count: 8192,
first_cluster_of_root: 16,
bitmap_bytes: 1024,
upcase_cluster: 4,
},
Row {
what: "the smallest volume, at whatever cluster the baseline picks",
volume_bytes: 32 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Auto,
fat_offset: 2048,
fat_length: 62,
cluster_heap_offset: 4096,
cluster_count: 7680,
first_cluster_of_root: 5,
bitmap_bytes: 960,
upcase_cluster: 3,
},
Row {
what: "four-kilobyte clusters, where the up-case table spans two of them",
volume_bytes: 64 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Bytes(4 << 10),
fat_offset: 2048,
fat_length: 126,
cluster_heap_offset: 4096,
cluster_count: 15872,
first_cluster_of_root: 5,
bitmap_bytes: 1984,
upcase_cluster: 3,
},
Row {
what: "thirty-two-kilobyte clusters, where it fits in one",
volume_bytes: 512 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Bytes(32 << 10),
fat_offset: 2048,
fat_length: 128,
cluster_heap_offset: 4096,
cluster_count: 16320,
first_cluster_of_root: 4,
bitmap_bytes: 2040,
upcase_cluster: 3,
},
Row {
what: "a sector size that is not five hundred and twelve",
volume_bytes: 64 << 20,
bytes_per_sector: 4096,
cluster_size: ClusterSize::Auto,
fat_offset: 256,
fat_length: 16,
cluster_heap_offset: 512,
cluster_count: 15872,
first_cluster_of_root: 5,
bitmap_bytes: 1984,
upcase_cluster: 3,
},
Row {
what: "a million clusters, so the allocation bitmap spans many of them",
volume_bytes: 512 << 20,
bytes_per_sector: 512,
cluster_size: ClusterSize::Bytes(512),
fat_offset: 2048,
fat_length: 8113,
cluster_heap_offset: 10240,
cluster_count: 1_038_336,
first_cluster_of_root: 268,
bitmap_bytes: 129_792,
upcase_cluster: 256,
},
Row {
what: "a volume whose byte offsets pass four gigabytes",
volume_bytes: 8 << 30,
bytes_per_sector: 512,
cluster_size: ClusterSize::Bytes(128 << 10),
fat_offset: 2048,
fat_length: 512,
cluster_heap_offset: 4096,
cluster_count: 65520,
first_cluster_of_root: 4,
bitmap_bytes: 8190,
upcase_cluster: 3,
},
];
#[test]
fn the_planner_derives_the_geometry_the_baseline_derives() {
for row in BASELINE {
let what = row.what;
let layout = plan_layout(&row.request()).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(layout.fat_offset, row.fat_offset, "{what}: FatOffset");
assert_eq!(layout.fat_length, row.fat_length, "{what}: FatLength");
assert_eq!(
layout.cluster_heap_offset, row.cluster_heap_offset,
"{what}: ClusterHeapOffset"
);
assert_eq!(
layout.cluster_count, row.cluster_count,
"{what}: ClusterCount"
);
assert_eq!(
layout.first_cluster_of_root, row.first_cluster_of_root,
"{what}: root cluster"
);
assert_eq!(
layout.bitmap_bytes, row.bitmap_bytes,
"{what}: bitmap bytes"
);
assert_eq!(
layout.upcase_cluster, row.upcase_cluster,
"{what}: up-case cluster"
);
assert_eq!(
layout.volume_length * u64::from(row.bytes_per_sector),
row.volume_bytes,
"{what}: length"
);
}
}
#[test]
fn every_planned_layout_agrees_with_itself() {
for bytes in [
8u64 << 20,
32 << 20,
100 << 20,
512 << 20,
3 << 30,
64 << 30,
] {
for sector in [512u32, 1024, 2048, 4096] {
for cluster in [
ClusterSize::Auto,
ClusterSize::Bytes(4 << 10),
ClusterSize::Bytes(64 << 10),
ClusterSize::Bytes(1 << 20),
] {
let request = PlanRequest::new(bytes)
.bytes_per_sector(sector)
.cluster_size(cluster);
let Ok(layout) = plan_layout(&request) else {
continue;
};
let what = format!("{bytes} bytes, {sector}-byte sectors, {cluster:?}");
let sector = u64::from(sector);
let fat_at = u64::from(layout.fat_offset) * sector;
let fat_end = fat_at + u64::from(layout.fat_length) * sector;
let heap_at = u64::from(layout.cluster_heap_offset) * sector;
assert!(
fat_at >= RESERVED_SECTORS * sector,
"{what}: table over boot"
);
assert!(fat_end <= heap_at, "{what}: table over heap");
let heap_end = heap_at
+ u64::from(layout.cluster_count) * u64::from(layout.bytes_per_cluster);
assert!(heap_end <= layout.total_bytes(), "{what}: heap over volume");
assert!(
u64::from(layout.fat_length) * sector / 4
>= u64::from(layout.cluster_count) + u64::from(FIRST_CLUSTER),
"{what}: table too short for its clusters"
);
assert_eq!(
layout.bitmap_bytes,
u64::from(layout.cluster_count).div_ceil(8),
"{what}: bitmap is one bit per cluster"
);
assert_eq!(layout.bitmap_cluster, FIRST_CLUSTER, "{what}");
assert_eq!(
layout.upcase_cluster,
layout.bitmap_cluster + layout.clusters_for(layout.bitmap_bytes) as u32,
"{what}: up-case table behind the bitmap"
);
assert_eq!(
layout.first_cluster_of_root,
layout.upcase_cluster + layout.clusters_for(layout.upcase_bytes) as u32,
"{what}: root behind the up-case table"
);
assert!(
layout
.cluster_start_sector(layout.first_cluster_of_root)
.is_some(),
"{what}: root inside the heap"
);
}
}
}
}
#[test]
fn a_planned_layout_is_one_a_boot_sector_round_trips() {
for row in BASELINE {
let what = row.what;
let planned = plan_layout(&row.request()).expect("plan");
let boot = boot_for(&planned);
let recovered =
layout_from_boot(&boot, row.volume_bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(
recovered.bytes_per_sector, planned.bytes_per_sector,
"{what}"
);
assert_eq!(
recovered.bytes_per_cluster, planned.bytes_per_cluster,
"{what}"
);
assert_eq!(recovered.volume_length, planned.volume_length, "{what}");
assert_eq!(recovered.fat_offset, planned.fat_offset, "{what}");
assert_eq!(recovered.fat_length, planned.fat_length, "{what}");
assert_eq!(
recovered.cluster_heap_offset, planned.cluster_heap_offset,
"{what}"
);
assert_eq!(recovered.cluster_count, planned.cluster_count, "{what}");
assert_eq!(
recovered.first_cluster_of_root, planned.first_cluster_of_root,
"{what}"
);
assert_eq!(recovered.bitmap_bytes, planned.bitmap_bytes, "{what}");
}
}
fn boot_for(layout: &ExfatLayout) -> MainBootSector {
MainBootSector {
jump_boot: MainBootSector::JUMP_BOOT,
file_system_name: super::super::ondisk::FILE_SYSTEM_NAME,
partition_offset: 0,
volume_length: layout.volume_length,
fat_offset: layout.fat_offset,
fat_length: layout.fat_length,
cluster_heap_offset: layout.cluster_heap_offset,
cluster_count: layout.cluster_count,
first_cluster_of_root: layout.first_cluster_of_root,
volume_serial: 0x1234_5678,
file_system_revision: super::super::ondisk::FILE_SYSTEM_REVISION,
volume_flags: 0,
bytes_per_sector_shift: layout.bytes_per_sector_shift(),
sectors_per_cluster_shift: layout.sectors_per_cluster_shift(),
number_of_fats: 1,
drive_select: 0x80,
percent_in_use: 0,
boot_code: [0; 390],
}
}
#[test]
fn the_conventional_cluster_size_is_keyed_on_the_volume_alone() {
for (bytes, want) in [
(1u64 << 20, 512u32),
((7 << 20) - 1, 512),
(7 << 20, 4 << 10),
(256 << 20, 4 << 10),
((256 << 20) + 1, 32 << 10),
(32 << 30, 32 << 10),
((32 << 30) + 1, 128 << 10),
(1 << 40, 128 << 10),
] {
assert_eq!(conventional_cluster_size(bytes), want, "{bytes} bytes");
}
}
#[test]
fn an_input_the_format_does_not_define_is_refused_by_name() {
let ok = PlanRequest::new(64 << 20);
assert!(plan_layout(&ok).is_ok());
assert!(matches!(
plan_layout(&ok.bytes_per_sector(768)),
Err(GeometryError::SectorSizeUnsupported {
bytes_per_sector: 768
})
));
assert!(matches!(
plan_layout(
&ok.bytes_per_sector(4096)
.cluster_size(ClusterSize::Bytes(512))
),
Err(GeometryError::ClusterSizeUnsupported { .. })
));
assert!(matches!(
plan_layout(&ok.cluster_size(ClusterSize::Bytes(3072))),
Err(GeometryError::ClusterSizeUnsupported { .. })
));
assert!(matches!(
plan_layout(&ok.cluster_size(ClusterSize::Bytes(64 << 20))),
Err(GeometryError::ClusterTooLarge {
limit: MAX_BYTES_PER_CLUSTER,
..
})
));
assert!(matches!(
plan_layout(&ok.boundary_align(BoundaryAlign::Bytes(3 << 20))),
Err(GeometryError::BoundaryAlignUnsupported { .. })
));
}
#[test]
fn a_volume_that_cannot_hold_a_filesystem_is_refused_rather_than_planned() {
assert!(matches!(
plan_layout(&PlanRequest::new(MIN_VOLUME_BYTES - 512)),
Err(GeometryError::VolumeTooSmall { .. })
));
assert!(matches!(
plan_layout(&PlanRequest::new(4 << 20).boundary_align(BoundaryAlign::Bytes(8 << 20))),
Err(GeometryError::NoClusterHeap { .. })
));
let cramped =
plan_layout(&PlanRequest::new(4 << 20).cluster_size(ClusterSize::Bytes(1 << 20)));
assert!(
matches!(
cramped,
Err(GeometryError::HeapTooSmall {
clusters: 2,
needed: 3
})
),
"expected a heap too small for its residents, got {cramped:?}"
);
assert!(
plan_layout(&PlanRequest::new(5 << 20).cluster_size(ClusterSize::Bytes(1 << 20)))
.is_ok()
);
}
#[test]
fn the_alignment_is_a_byte_quantity_and_not_a_sector_count() {
let at_512 = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
let at_4096 =
plan_layout(&PlanRequest::new(64 << 20).bytes_per_sector(4096)).expect("plan");
assert_eq!(
u64::from(at_512.fat_offset) * 512,
u64::from(at_4096.fat_offset) * 4096
);
assert_eq!(
u64::from(at_512.fat_offset) * 512,
u64::from(DEFAULT_BOUNDARY_ALIGN)
);
let packed =
plan_layout(&PlanRequest::new(64 << 20).boundary_align(BoundaryAlign::Bytes(64 << 10)))
.expect("plan");
assert_eq!(u64::from(packed.fat_offset) * 512, 64 << 10);
assert_eq!(u64::from(packed.cluster_heap_offset) * 512 % (64 << 10), 0);
assert!(
packed.cluster_count > at_512.cluster_count,
"a tighter alignment leaves more room for clusters"
);
}
#[test]
fn a_volume_size_that_is_not_whole_sectors_is_planned_as_the_sectors_it_has() {
let whole = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
let ragged = plan_layout(&PlanRequest::new((64 << 20) + 511)).expect("plan");
assert_eq!(ragged.volume_length, whole.volume_length);
assert_eq!(ragged.total_bytes(), 64 << 20);
}
#[test]
fn a_boot_sector_that_does_not_agree_with_itself_is_refused_by_name() {
let planned = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
let good = boot_for(&planned);
let available = planned.total_bytes();
assert!(layout_from_boot(&good, available).is_ok());
let mut sector_shift = good;
sector_shift.bytes_per_sector_shift = 13;
assert!(matches!(
layout_from_boot(§or_shift, available),
Err(BootDefect::SectorShift { shift: 13 })
));
let mut cluster_shift = good;
cluster_shift.sectors_per_cluster_shift = 20;
assert!(matches!(
layout_from_boot(&cluster_shift, available),
Err(BootDefect::ClusterShift { .. })
));
let mut long = good;
long.volume_length = good.volume_length * 2;
assert!(matches!(
layout_from_boot(&long, available),
Err(BootDefect::VolumeLength { .. })
));
let mut short = good;
short.volume_length = 4;
assert!(matches!(
layout_from_boot(&short, available),
Err(BootDefect::VolumeLength { .. })
));
let mut table_in_boot = good;
table_in_boot.fat_offset = 4;
assert!(matches!(
layout_from_boot(&table_in_boot, available),
Err(BootDefect::RegionOutsideVolume { .. })
));
let mut table_over_heap = good;
table_over_heap.fat_length = good.cluster_heap_offset;
assert!(matches!(
layout_from_boot(&table_over_heap, available),
Err(BootDefect::RegionOutsideVolume { .. })
));
let mut heap_past_end = good;
heap_past_end.cluster_heap_offset = u32::try_from(good.volume_length).expect("fits");
assert!(matches!(
layout_from_boot(&heap_past_end, available),
Err(BootDefect::RegionOutsideVolume { .. })
));
let mut too_many = good;
too_many.cluster_count = good.cluster_count * 4;
assert!(matches!(
layout_from_boot(&too_many, available),
Err(BootDefect::RegionOutsideVolume { .. })
));
let mut short_table = good;
short_table.fat_length = u32::try_from(
(u64::from(good.cluster_count) + u64::from(FIRST_CLUSTER) - 1) * 4
/ u64::from(planned.bytes_per_sector),
)
.expect("fits");
assert!(matches!(
layout_from_boot(&short_table, available),
Err(BootDefect::TableTooShort { .. })
));
for cluster in [0, 1, good.cluster_count + FIRST_CLUSTER] {
let mut root = good;
root.first_cluster_of_root = cluster;
assert!(
matches!(
layout_from_boot(&root, available),
Err(BootDefect::RootOutsideHeap { .. })
),
"a root at cluster {cluster} is outside the heap"
);
}
}
#[test]
fn the_addressing_helpers_refuse_a_cluster_the_volume_does_not_have() {
let layout = plan_layout(&PlanRequest::new(64 << 20)).expect("plan");
let last = FIRST_CLUSTER + layout.cluster_count - 1;
assert_eq!(
layout.cluster_start_byte(FIRST_CLUSTER),
Some(u64::from(layout.cluster_heap_offset) * u64::from(layout.bytes_per_sector))
);
assert!(layout.cluster_start_sector(last).is_some());
assert_eq!(layout.cluster_start_sector(last + 1), None);
assert_eq!(layout.cluster_start_sector(1), None);
assert_eq!(layout.cluster_start_sector(0), None);
assert_eq!(
layout.fat_entry_byte(0),
Some(u64::from(layout.fat_offset) * u64::from(layout.bytes_per_sector))
);
assert!(layout.fat_entry_byte(last).is_some());
assert_eq!(layout.fat_entry_byte(last + 1), None);
assert_eq!(layout.boot_region_sector(0), Some(0));
assert_eq!(layout.boot_region_sector(1), Some(BOOT_REGION_SECTORS));
assert_eq!(layout.boot_region_sector(2), None);
}
}