Fix format_volume panic in debug build for small FAT12 volumes

Backport of 50b8dec36ab664b02d7532422a164e47144eecac
This commit is contained in:
Rafał Harabień 2023-01-17 00:44:08 +01:00
parent 75bb9d1293
commit 243ed69e54
2 changed files with 9 additions and 3 deletions

View File

@ -4,7 +4,8 @@ Changelog
0.3.6 (not released yet) 0.3.6 (not released yet)
------------------------ ------------------------
Bug fixes: Bug fixes:
* Create directory entry with `VOLUME_ID` attribute when formatting if volume label was set in `FormatVolumeOptions`. * Create directory entry with `VOLUME_ID` attribute when formatting if volume label was set in `FormatVolumeOptions`
* Fix `format_volume` function panicking in debug build for FAT12 volumes with size below 1 MB
0.3.5 (2021-01-23) 0.3.5 (2021-01-23)
------------------------ ------------------------

View File

@ -449,8 +449,12 @@ fn determine_bytes_per_cluster(total_bytes: u64, bytes_per_sector: u16, fat_type
}, },
}; };
const MAX_CLUSTER_SIZE: u32 = 32 * KB as u32; const MAX_CLUSTER_SIZE: u32 = 32 * KB as u32;
debug_assert!(bytes_per_cluster.is_power_of_two()); let bytes_per_cluster_clamped = cmp::min(
cmp::min(cmp::max(bytes_per_cluster, bytes_per_sector as u32), MAX_CLUSTER_SIZE) cmp::max(bytes_per_cluster, u32::from(bytes_per_sector)),
MAX_CLUSTER_SIZE,
);
debug_assert!(bytes_per_cluster_clamped.is_power_of_two());
bytes_per_cluster_clamped
} }
fn determine_sectors_per_fat( fn determine_sectors_per_fat(
@ -727,6 +731,7 @@ mod tests {
#[test] #[test]
fn test_determine_bytes_per_cluster_fat12() { fn test_determine_bytes_per_cluster_fat12() {
assert_eq!(determine_bytes_per_cluster(128 * KB, 512, Some(FatType::Fat12)), 512);
assert_eq!(determine_bytes_per_cluster(1 * MB + 0, 512, Some(FatType::Fat12)), 512); assert_eq!(determine_bytes_per_cluster(1 * MB + 0, 512, Some(FatType::Fat12)), 512);
assert_eq!(determine_bytes_per_cluster(1 * MB + 1, 512, Some(FatType::Fat12)), 1024); assert_eq!(determine_bytes_per_cluster(1 * MB + 1, 512, Some(FatType::Fat12)), 1024);
assert_eq!(determine_bytes_per_cluster(1 * MB, 4096, Some(FatType::Fat12)), 4096); assert_eq!(determine_bytes_per_cluster(1 * MB, 4096, Some(FatType::Fat12)), 4096);