correctly update file size after write

This commit is contained in:
Moritz Gmeiner 2025-08-01 22:42:13 +02:00
commit 2ed107478e
11 changed files with 451 additions and 272 deletions

View file

@ -1,7 +1,7 @@
use std::io::{Read, Write};
use crate::FatFs;
use crate::subslice::{SubSlice, SubSliceMut};
use crate::{FatFs, FatType};
pub struct ClusterChainReader<'a> {
fat_fs: &'a FatFs,
@ -12,7 +12,7 @@ pub struct ClusterChainReader<'a> {
}
impl<'a> ClusterChainReader<'a> {
pub fn new(fat_fs: &'a FatFs, first_cluster: u32) -> ClusterChainReader<'a> {
pub fn new(fat_fs: &'a FatFs, first_cluster: u32) -> Self {
let next_cluster = fat_fs.next_cluster(first_cluster).unwrap_or(None);
let sub_slice = fat_fs.cluster_as_subslice(first_cluster);
@ -24,6 +24,28 @@ impl<'a> ClusterChainReader<'a> {
}
}
pub fn root_dir_reader(fat_fs: &'a FatFs) -> Self {
match fat_fs.fat_type() {
FatType::Fat12 | FatType::Fat16 => {
// fixed root dir, so no need to chain
// get a single SubSlice for it and next_cluster is None
let sub_slice = fat_fs.root_dir_as_subslice();
ClusterChainReader {
fat_fs,
sub_slice,
next_cluster: None,
}
}
FatType::Fat32 => {
// FAT is directory_like, so get a real chain reader
Self::new(fat_fs, fat_fs.bpb.root_cluster().unwrap())
}
}
}
fn move_to_next_cluster(&mut self) -> bool {
let Some(next_cluster) = self.next_cluster else {
return false;
@ -55,6 +77,10 @@ impl<'a> ClusterChainReader<'a> {
n
}
pub fn current_offset(&self) -> u64 {
self.sub_slice.offset()
}
}
impl Read for ClusterChainReader<'_> {
@ -78,7 +104,7 @@ pub struct ClusterChainWriter<'a> {
}
impl<'a> ClusterChainWriter<'a> {
pub fn new(fat_fs: &'a FatFs, first_cluster: u32) -> ClusterChainWriter<'a> {
pub fn new(fat_fs: &'a FatFs, first_cluster: u32) -> Self {
let next_cluster = fat_fs.next_cluster(first_cluster).unwrap_or(None);
let sub_slice = fat_fs.cluster_as_subslice_mut(first_cluster);
@ -90,6 +116,28 @@ impl<'a> ClusterChainWriter<'a> {
}
}
pub fn root_dir_writer(fat_fs: &'a FatFs) -> Self {
match fat_fs.fat_type() {
FatType::Fat12 | FatType::Fat16 => {
// fixed root dir, so no need to chain
// get a single SubSliceMut for it and next_cluster is None
let sub_slice = fat_fs.root_dir_as_subslice_mut();
ClusterChainWriter {
fat_fs,
sub_slice,
next_cluster: None,
}
}
FatType::Fat32 => {
// FAT is directory_like, so get a real chain writer
Self::new(fat_fs, fat_fs.bpb.root_cluster().unwrap())
}
}
}
fn move_to_next_cluster(&mut self) -> bool {
// TODO: should allocate a new cluster here!
let Some(next_cluster) = self.next_cluster else {
@ -122,6 +170,10 @@ impl<'a> ClusterChainWriter<'a> {
n
}
pub fn current_offset(&self) -> u64 {
self.sub_slice.offset()
}
}
impl Write for ClusterChainWriter<'_> {