1use aligned::Aligned;
2
3#[cfg(feature = "alloc")]
4use alloc::{string::String, vec, vec::Vec};
5
6use super::fat::END_OF_CHAIN;
7use crate::timestamp::{EncodedTimestamp, Timestamp};
8
9use super::{
10 BlockDevice,
11 allocation::{AllocatedRun, SearchPolicy, StoredChain},
12 bisync,
13 directory_entry::{
14 DirSetWriter,
15 DirectoryEntryChain,
16 FileAttributes,
17 FileDirEntry,
18 GeneralSecondaryFlags,
19 Location,
20 RawDirEntry,
21 StreamExtensionDirEntry, },
23 error::ExFatError,
24 file_system::{ExFatResult, FileSystem},
25 utils::split_path,
26};
27
28#[derive(Copy, Clone, Debug, Default)]
29pub struct OpenOptions {
30 pub read: bool,
31 pub write: bool,
32 pub append: bool,
33 pub truncate: bool,
34 pub create: bool,
35 pub create_new: bool,
36}
37
38pub(crate) const NO_CLUSTER_ID: u32 = 0;
39pub(crate) const DEFAULT_TOUCHED_SECTORS: usize = 6;
40
41impl OpenOptions {
42 pub const fn new() -> Self {
43 Self {
44 read: false,
45 write: false,
46 append: false,
47 truncate: false,
48 create: false,
49 create_new: false,
50 }
51 }
52
53 pub const fn read(mut self, read: bool) -> Self {
57 self.read = read;
58 self
59 }
60
61 pub const fn write(mut self, write: bool) -> Self {
65 self.write = write;
66 self
67 }
68
69 pub const fn append(mut self, append: bool) -> Self {
75 self.append = append;
76 self
77 }
78
79 pub const fn truncate(mut self, truncate: bool) -> Self {
84 self.truncate = truncate;
85 self
86 }
87
88 pub const fn create(mut self, create: bool) -> Self {
93 self.create = create;
94 self
95 }
96
97 pub const fn create_new(mut self, create_new: bool) -> Self {
102 self.create_new = create_new;
103 self
104 }
105}
106
107#[derive(Debug, Clone)]
108pub(crate) struct FileDetails {
109 pub first_cluster: u32,
110 pub data_length: u64,
111 pub valid_data_length: u64, pub attributes: FileAttributes,
113 pub location: Location,
114 pub flags: GeneralSecondaryFlags,
115 pub secondary_count: u8,
116 pub created: EncodedTimestamp,
117 pub modified: EncodedTimestamp,
118 pub accessed: EncodedTimestamp,
119}
120
121#[cfg(feature = "defmt")]
122impl defmt::Format for FileDetails {
123 fn format(&self, f: defmt::Formatter) {
124 defmt::write!(
125 f,
126 "FileDetails {{ first_cluster: {=u32}, data_length: {=u64}, valid_data_length: {=u64}, attributes: {}, location: {}, flags: {}, secondary_count: {=u8} }}",
127 self.first_cluster,
128 self.data_length,
129 self.valid_data_length,
130 self.attributes,
131 self.location,
132 self.flags,
133 self.secondary_count,
134 );
135 }
136}
137
138#[derive(Debug)]
139pub struct Metadata {
140 pub(crate) details: FileDetails,
141}
142
143#[allow(async_fn_in_trait)]
144pub(crate) trait Touched {
145 fn insert(&mut self, touched: TouchedSector);
146
147 #[bisync]
148 async fn flush<D, const SIZE: usize, const N: usize>(
149 &mut self,
150 fs: &mut FileSystem<D, SIZE, N>,
151 ) -> ExFatResult<(), D, SIZE>
152 where
153 D: BlockDevice<SIZE>;
154
155 fn sort(&mut self);
156}
157
158#[derive(Debug)]
159pub(crate) struct FileDirty<const N: usize = DEFAULT_TOUCHED_SECTORS> {
160 sectors: heapless::Vec<TouchedSector, N>,
161 overflowed: bool,
162 is_dir_entry_dirty: bool,
163}
164
165impl FileDirty {
166 pub fn new() -> Self {
167 Self {
168 sectors: heapless::Vec::new(),
169 overflowed: false,
170 is_dir_entry_dirty: false,
171 }
172 }
173}
174
175#[derive(Debug, Default, PartialEq, Eq)]
176pub(crate) enum TouchedKind {
177 Data,
178 Fat,
179 Bitmap,
180 Dir,
181 #[default]
182 None,
183}
184
185impl TouchedKind {
186 fn rank(&self) -> u8 {
187 match self {
188 Self::Data => 0,
189 Self::Bitmap => 1,
190 Self::Fat => 2,
191 Self::Dir => 3,
192 Self::None => 4,
193 }
194 }
195}
196
197#[derive(Debug, Default)]
198pub(crate) struct TouchedSector {
199 kind: TouchedKind,
200 sector: u32,
201}
202
203impl TouchedSector {
204 pub fn new(kind: TouchedKind, sector: u32) -> Self {
205 Self { kind, sector }
206 }
207}
208
209impl<const NUM_SECTORS: usize> Touched for FileDirty<NUM_SECTORS> {
210 fn insert(&mut self, touched: TouchedSector) {
211 if self
212 .sectors
213 .iter()
214 .find(|x| x.sector == touched.sector)
215 .is_none()
216 && self.sectors.push(touched).is_err()
217 {
218 self.overflowed = true;
219 }
220 }
221
222 #[bisync]
223 async fn flush<D, const SIZE: usize, const N: usize>(
224 &mut self,
225 fs: &mut FileSystem<D, SIZE, N>,
226 ) -> ExFatResult<(), D, SIZE>
227 where
228 D: BlockDevice<SIZE>,
229 {
230 if self.overflowed {
231 fs.fat.flush(&mut fs.dev).await?;
232 fs.allocator.flush(&mut fs.dev).await?;
233 fs.data_blocks.flush(&mut fs.dev).await?;
234 } else {
235 self.sort();
237 for item in &self.sectors {
238 match item.kind {
239 TouchedKind::Bitmap => {
240 fs.allocator.flush_sector(&mut fs.dev, item.sector).await?
241 }
242 TouchedKind::Fat => fs.fat.flush_sector(&mut fs.dev, item.sector).await?,
243 TouchedKind::Data | TouchedKind::Dir => {
244 fs.data_blocks
245 .flush_sector(&mut fs.dev, item.sector)
246 .await?
247 }
248 TouchedKind::None => {
249 }
251 }
252 }
253 }
254
255 self.sectors.clear();
256 self.overflowed = false;
257 self.is_dir_entry_dirty = false;
258 Ok(())
259 }
260
261 fn sort(&mut self) {
262 self.sectors
263 .sort_unstable_by_key(|x| (x.kind.rank(), x.sector));
264 }
265}
266
267impl Metadata {
268 pub fn len(&self) -> u64 {
270 self.details.data_length
271 }
272
273 pub fn is_empty(&self) -> bool {
275 self.details.data_length == 0
276 }
277
278 pub fn is_dir(&self) -> bool {
280 self.details.attributes.contains(FileAttributes::Directory)
281 }
282
283 pub fn is_file(&self) -> bool {
285 self.details.attributes.contains(FileAttributes::Archive)
286 }
287
288 pub fn created(&self) -> Timestamp {
290 Timestamp::decode(self.details.created)
291 }
292
293 pub fn accessed(&self) -> Timestamp {
295 Timestamp::decode(self.details.accessed)
296 }
297
298 pub fn modified(&self) -> Timestamp {
300 Timestamp::decode(self.details.modified)
301 }
302}
303
304pub struct File {
305 pub(crate) details: FileDetails,
306 current_cluster: u32,
307 remaining_bytes_in_cluster: u32,
308 cursor: u64,
309 open_options: OpenOptions,
310 chain: StoredChain,
311 touched: FileDirty<DEFAULT_TOUCHED_SECTORS>,
312}
313
314impl File {
315 pub(crate) fn new(
316 file_details: &FileDetails,
317 cluster_id: u32,
318 cluster_length: u32,
319 open_options: OpenOptions,
320 chain: StoredChain,
321 ) -> Self {
322 let cursor = if open_options.append {
323 file_details.valid_data_length
324 } else {
325 0
326 };
327
328 let remaining_bytes_in_cluster = match &chain {
329 StoredChain::Empty => 0,
330 _ => cluster_length - (cursor % cluster_length as u64) as u32,
331 };
332
333 Self {
334 details: file_details.clone(),
335 current_cluster: cluster_id,
336 remaining_bytes_in_cluster,
337 cursor,
338 open_options,
339 chain,
340 touched: FileDirty::new(),
341 }
342 }
343
344 pub fn metadata(&self) -> Metadata {
346 Metadata {
347 details: self.details.clone(),
348 }
349 }
350
351 #[bisync]
352 pub async fn flush<D, const SIZE: usize, const N: usize>(
353 &mut self,
354 fs: &mut FileSystem<D, SIZE, N>,
355 ) -> ExFatResult<(), D, SIZE>
356 where
357 D: BlockDevice<SIZE>,
358 {
359 if self.touched.is_dir_entry_dirty {
361 let mut chain = DirectoryEntryChain::new_from_file_details(&self.details, &fs.fs);
362 let mut counter = 0;
363 let mut dir_set_writer = DirSetWriter::new(self.details.location);
364 let mut file_dir: Option<RawDirEntry> = None;
365
366 while let Some((dir_entry, _location)) = chain.next(fs).await? {
367 match counter {
368 0 => {
369 let mut file_dir_entry = FileDirEntry::from(dir_entry);
371 let timestamp = fs.get_current_timestamp();
372 file_dir_entry.last_modified_timestamp = timestamp.packed;
373 file_dir_entry.last_modified_10ms_increment = timestamp.increment_10ms;
374 file_dir_entry.last_modified_utc_offset = timestamp.utc_offset;
375 file_dir_entry.last_accessed_timestamp = timestamp.packed;
376 file_dir_entry.last_accessed_utc_offset = timestamp.utc_offset;
377 let raw = file_dir_entry.serialize();
378 dir_set_writer
379 .add(fs, &mut self.touched, &raw, true)
380 .await?;
381 file_dir = Some(raw);
382 }
383 1 => {
384 let mut stream_ext: StreamExtensionDirEntry = dir_entry.into();
386 stream_ext.first_cluster = match &self.chain {
387 StoredChain::Empty => NO_CLUSTER_ID,
388 StoredChain::Contiguous {
389 first,
390 cluster_count: _cluster_count,
391 } => *first,
392 StoredChain::Fat {
393 first,
394 last: _last,
395 cluster_count: _cluster_count,
396 } => *first,
397 };
398 stream_ext.data_length = self.details.data_length;
399 stream_ext.valid_data_length = self.details.valid_data_length;
400 stream_ext.general_secondary_flags = self.details.flags;
401
402 dir_set_writer
403 .add(fs, &mut self.touched, &stream_ext.serialize(), false)
404 .await?;
405 }
406 _ => {
407 dir_set_writer.add_no_write::<SIZE>(dir_entry, false);
409 }
410 }
411 counter += 1;
412 }
413
414 if let Some(file_dir) = file_dir {
415 dir_set_writer
417 .finish(fs, &mut self.touched, &file_dir)
418 .await?;
419 }
420 }
421
422 self.touched.flush(fs).await?;
423
424 Ok(())
425 }
426
427 #[bisync]
428 pub async fn close<D, const SIZE: usize, const N: usize>(
429 mut self,
430 fs: &mut FileSystem<D, SIZE, N>,
431 ) -> ExFatResult<(), D, SIZE>
432 where
433 D: BlockDevice<SIZE>,
434 {
435 self.flush(fs).await?;
436 Ok(())
437 }
438
439 #[bisync]
443 pub async fn read<D, const SIZE: usize, const N: usize>(
444 &mut self,
445 fs: &mut FileSystem<D, SIZE, N>,
446 buf: &mut [u8],
447 ) -> ExFatResult<Option<usize>, D, SIZE>
448 where
449 D: BlockDevice<SIZE>,
450 {
451 fs.mount().await?;
452 if !self.open_options.read {
453 return Err(ExFatError::ReadNotEnabled);
454 }
455
456 if self.eof() {
458 return Ok(None);
459 }
460
461 if buf.is_empty() {
463 return Ok(Some(0));
464 }
465
466 let mut bytes_read = 0;
467
468 loop {
469 let file_remainder = self.details.data_length.saturating_sub(self.cursor);
470 let valid_remainder = self.details.valid_data_length.saturating_sub(self.cursor);
471
472 self.next_cluster_if_required(fs).await?;
473 let cluster_id = self.current_cluster;
474 let cluster_offset = self.get_cluster_offset(fs);
475 let start_sector_id = fs.fs.get_heap_sector_id::<D, SIZE>(cluster_id)?;
476 let sector_id = start_sector_id + cluster_offset / SIZE as u32;
477 let sector_offset = cluster_offset as usize % SIZE;
478 let remainder_in_sector = SIZE - sector_offset;
479
480 let mut chunk_bytes = (remainder_in_sector as u64)
482 .min(file_remainder)
483 .min((buf.len() - bytes_read) as u64) as usize;
484
485 if valid_remainder > 0 {
486 chunk_bytes = chunk_bytes.min(valid_remainder as usize);
487 let slot = fs.data_blocks.read(sector_id, &mut fs.dev).await?;
489 buf[bytes_read..bytes_read + chunk_bytes]
490 .copy_from_slice(&slot.as_slice()[sector_offset..sector_offset + chunk_bytes]);
491 } else {
492 buf[bytes_read..bytes_read + chunk_bytes].fill(0);
495 }
496
497 self.move_file_cursor(chunk_bytes);
498 bytes_read += chunk_bytes;
499
500 if bytes_read == buf.len() || self.eof() {
501 return Ok(Some(bytes_read));
502 }
503 }
504 }
505
506 #[cfg(feature = "alloc")]
517 #[bisync]
518 pub async fn read_to_end<D, const SIZE: usize, const N: usize>(
519 &mut self,
520 fs: &mut FileSystem<D, SIZE, N>,
521 buf: &mut Vec<u8>,
522 ) -> ExFatResult<usize, D, SIZE>
523 where
524 D: BlockDevice<SIZE>,
525 {
526 fs.mount().await?;
527
528 let len = self.details.data_length.saturating_sub(self.cursor) as usize;
529 let start = buf.len();
530 buf.resize(start + len, 0);
531 let filled = self.read_to_end_inner(fs, &mut buf[start..]).await?;
532 buf.truncate(start + filled); Ok(filled)
534 }
535
536 #[cfg(feature = "alloc")]
538 #[bisync]
539 pub async fn read_to_string<D, const SIZE: usize, const N: usize>(
540 &mut self,
541 fs: &mut FileSystem<D, SIZE, N>,
542 ) -> ExFatResult<String, D, SIZE>
543 where
544 D: BlockDevice<SIZE>,
545 {
546 fs.mount().await?;
547
548 let len = self.details.valid_data_length.saturating_sub(self.cursor) as usize;
551 let mut buf = vec![0u8; len];
552 let filled = self.read_to_end_inner(fs, &mut buf).await?;
553 let decoded = core::str::from_utf8(&buf[..filled])
554 .map_err(|_| ExFatError::Utf8Error)?
555 .into();
556 Ok(decoded)
557 }
558
559 #[bisync]
560 #[cfg(feature = "alloc")]
561 async fn read_to_end_inner<D, const SIZE: usize, const N: usize>(
562 &mut self,
563 fs: &mut FileSystem<D, SIZE, N>,
564 buf: &mut [u8],
565 ) -> ExFatResult<usize, D, SIZE>
566 where
567 D: BlockDevice<SIZE>,
568 {
569 if !self.open_options.read {
570 return Err(ExFatError::ReadNotEnabled);
571 }
572
573 let mut filled = 0;
574 while filled < buf.len() {
575 match self.read(fs, &mut buf[filled..]).await? {
576 Some(n) if n > 0 => filled += n,
577 _ => break, }
579 }
580
581 Ok(filled)
582 }
583
584 fn should_convert_to_fat_chain(&self, run: &AllocatedRun) -> bool {
585 match &self.chain {
586 StoredChain::Empty => false,
587 StoredChain::Contiguous {
588 first,
589 cluster_count: len,
590 } => {
591 let no_fat_chain = self
592 .details
593 .flags
594 .contains(GeneralSecondaryFlags::NoFatChain);
595
596 no_fat_chain && (first + len) != run.first_cluster
597 }
598 StoredChain::Fat {
599 first: _first,
600 last: _last,
601 cluster_count: _len,
602 } => false,
603 }
604 }
605
606 #[bisync]
607 async fn update_chain<D, const SIZE: usize, const N: usize>(
608 &mut self,
609 fs: &mut FileSystem<D, SIZE, N>,
610 run: &AllocatedRun,
611 ) -> ExFatResult<(), D, SIZE>
612 where
613 D: BlockDevice<SIZE>,
614 {
615 if self.should_convert_to_fat_chain(run) {
616 self.convert_file_to_fat_chain_if_required(fs).await?;
617 }
618
619 let has_fat_chain = !self
620 .details
621 .flags
622 .contains(GeneralSecondaryFlags::NoFatChain);
623
624 if has_fat_chain {
625 let mut prev_cluster = match &self.chain {
627 StoredChain::Empty => None,
628 StoredChain::Contiguous {
629 first,
630 cluster_count,
631 } => Some(first + cluster_count - 1),
632 StoredChain::Fat { last, .. } => Some(*last),
633 };
634
635 for next_cluster in run.first_cluster..run.first_cluster + run.cluster_count {
636 if let Some(prev_cluster) = prev_cluster {
637 fs.fat
638 .set(&mut fs.dev, &mut self.touched, prev_cluster, next_cluster)
639 .await?;
640 }
641
642 prev_cluster = Some(next_cluster);
643 }
644
645 let last = run.first_cluster + run.cluster_count - 1;
646 fs.fat
647 .set(&mut fs.dev, &mut self.touched, last, END_OF_CHAIN)
648 .await?;
649 }
650
651 let old_chain = self.chain.clone();
652
653 match old_chain {
654 StoredChain::Empty => {
655 self.chain = StoredChain::Contiguous {
656 first: run.first_cluster,
657 cluster_count: run.cluster_count,
658 };
659 self.current_cluster = run.first_cluster;
660 self.remaining_bytes_in_cluster = fs.fs.cluster_length;
661 }
662 StoredChain::Contiguous {
663 first,
664 cluster_count,
665 } => {
666 if has_fat_chain {
667 self.chain = StoredChain::Fat {
668 first,
669 last: run.first_cluster + run.cluster_count - 1,
670 cluster_count: cluster_count + run.cluster_count,
671 };
672 } else {
673 self.chain = StoredChain::Contiguous {
674 first,
675 cluster_count: cluster_count + run.cluster_count,
676 }
677 }
678 }
679 StoredChain::Fat {
680 first,
681 last: _last,
682 cluster_count,
683 } => {
684 self.chain = StoredChain::Fat {
685 first,
686 last: run.first_cluster + run.cluster_count - 1,
687 cluster_count: cluster_count + run.cluster_count,
688 }
689 }
690 }
691 Ok(())
692 }
693
694 #[bisync]
695 async fn allocate_clusters_for<D, const SIZE: usize, const N: usize>(
696 &mut self,
697 fs: &mut FileSystem<D, SIZE, N>,
698 num_bytes: usize,
699 ) -> ExFatResult<(), D, SIZE>
700 where
701 D: BlockDevice<SIZE>,
702 {
703 let mut cluster_count = num_bytes.div_ceil(fs.fs.cluster_length as usize) as u32;
704
705 loop {
706 let run = fs
707 .allocator
708 .allocate(&mut fs.dev, &mut self.touched, &self.chain, cluster_count)
709 .await?;
710 self.update_chain(fs, &run).await?;
711 cluster_count -= run.cluster_count;
712
713 if cluster_count == 0 {
714 return Ok(());
715 }
716 }
717 }
718
719 #[bisync]
720 async fn next_cluster_if_required<D, const SIZE: usize, const N: usize>(
721 &mut self,
722 fs: &mut FileSystem<D, SIZE, N>,
723 ) -> ExFatResult<(), D, SIZE>
724 where
725 D: BlockDevice<SIZE>,
726 {
727 if self.remaining_bytes_in_cluster == 0 {
728 self.current_cluster = self.next_cursor_id(fs).await?;
729 self.remaining_bytes_in_cluster = fs.fs.cluster_length;
730 }
731
732 Ok(())
733 }
734
735 #[bisync]
739 pub async fn write<D, const SIZE: usize, const N: usize>(
740 &mut self,
741 fs: &mut FileSystem<D, SIZE, N>,
742 buf: &[u8],
743 ) -> ExFatResult<(), D, SIZE>
744 where
745 D: BlockDevice<SIZE>,
746 {
747 if buf.is_empty() {
748 return Ok(());
749 }
750
751 fs.mount().await?;
752 if !self.open_options.write {
753 return Err(ExFatError::WriteNotEnabled);
754 }
755
756 let data_length = self.details.data_length;
757
758 let cluster_length = fs.fs.cluster_length as u64;
761 let capacity = data_length.div_ceil(cluster_length) * cluster_length;
762 let end_of_write = self.cursor + buf.len() as u64;
763 if end_of_write > capacity {
764 self.allocate_clusters_for(fs, (end_of_write - capacity) as usize)
765 .await?;
766 }
767
768 self.update_data_length(buf.len());
769
770 self.next_cluster_if_required(fs).await?;
772 let len = self.write_partial_sector(fs, buf).await?;
773
774 if len < buf.len() {
776 let start_index = len;
777 let mut aligned = Aligned([0u8; SIZE]);
778 let (blocks, remainder) = buf[start_index..].as_chunks::<SIZE>();
779
780 for block in blocks {
782 aligned.copy_from_slice(block);
783 self.next_cluster_if_required(fs).await?;
784 let sector_id = self.get_current_sector_id(fs)?;
785 fs.data_blocks
786 .write(&mut fs.dev, sector_id, &aligned)
787 .await?;
788 self.move_file_cursor(block.len());
789 }
790
791 let _len = self.write_partial_sector(fs, remainder).await?;
793 }
794
795 Ok(())
796 }
797
798 fn update_remaining_bytes_in_cluster<D, const SIZE: usize, const N: usize>(
799 &mut self,
800 fs: &FileSystem<D, SIZE, N>,
801 ) where
802 D: BlockDevice<SIZE>,
803 {
804 self.remaining_bytes_in_cluster =
805 fs.fs.cluster_length - (self.cursor % fs.fs.cluster_length as u64) as u32
806 }
807
808 #[bisync]
810 pub async fn seek<D, const SIZE: usize, const N: usize>(
811 &mut self,
812 fs: &mut FileSystem<D, SIZE, N>,
813 cursor: u64,
814 ) -> ExFatResult<(), D, SIZE>
815 where
816 D: BlockDevice<SIZE>,
817 {
818 fs.mount().await?;
819 if cursor > self.details.valid_data_length {
820 return Err(ExFatError::SeekOutOfRange);
821 }
822
823 self.cursor = cursor;
824 let num_clusters = (cursor / fs.fs.cluster_length as u64) as u32;
825 match self.chain {
826 StoredChain::Empty => {
827 self.current_cluster = self.details.first_cluster;
828 self.remaining_bytes_in_cluster = 0;
829 }
830 StoredChain::Contiguous {
831 first,
832 cluster_count: _cluster_count,
833 } => {
834 self.current_cluster = first + num_clusters;
835 self.update_remaining_bytes_in_cluster(fs);
836 }
837 StoredChain::Fat {
838 first,
839 last: _last,
840 cluster_count: _cluster_count,
841 } => {
842 let mut cluster_id = first;
843 for _ in 0..num_clusters {
844 match fs
845 .fat
846 .next_cluster_in_fat_chain(cluster_id, &mut fs.dev)
847 .await?
848 {
849 Some(cluster_id_next) => cluster_id = cluster_id_next,
850 None => return Err(ExFatError::EndOfFatChain),
851 }
852 }
853
854 self.current_cluster = cluster_id;
855 self.update_remaining_bytes_in_cluster(fs);
856 }
857 }
858
859 Ok(())
860 }
861
862 #[bisync]
867 pub(crate) async fn copy_to<D, const SIZE: usize, const N: usize>(
868 &mut self,
869 fs: &mut FileSystem<D, SIZE, N>,
870 to_path: &str,
871 ) -> ExFatResult<(), D, SIZE>
872 where
873 D: BlockDevice<SIZE>,
874 {
875 let (dir_path, file_or_dir_name) = split_path(to_path);
876 let num_clusters = self.num_clusters(fs);
877
878 let run = fs
879 .allocator
880 .find_free_clusters(&mut fs.dev, None, num_clusters, SearchPolicy::LongestRun)
881 .await?;
882
883 if run.cluster_count != num_clusters {
884 return Err(ExFatError::DiskFull);
887 }
888
889 let directory_cluster_id = fs
891 .get_or_create_directory(&mut self.touched, dir_path)
892 .await?;
893
894 let flags = GeneralSecondaryFlags::AllocationPossible | GeneralSecondaryFlags::NoFatChain;
895
896 fs.create_file_dir_entry_at(
897 &mut self.touched,
898 file_or_dir_name,
899 directory_cluster_id,
900 run.first_cluster,
901 self.details.attributes,
902 flags,
903 self.details.valid_data_length,
904 self.details.data_length,
905 )
906 .await?;
907
908 fs.allocator
909 .mark_allocated(&mut fs.dev, &mut self.touched, &run, true)
910 .await?;
911
912 let mut sector_id = fs.fs.get_heap_sector_id::<D, SIZE>(run.first_cluster)?;
913 let mut buf = Aligned([0u8; SIZE]);
914
915 while let Some(_len) = self.read(fs, buf.as_mut_slice()).await? {
916 fs.data_blocks.write(&mut fs.dev, sector_id, &buf).await?;
917 sector_id += 1;
918 }
919
920 Ok(())
921 }
922
923 fn update_data_length(&mut self, num_bytes: usize) {
924 let valid_data_length =
925 (self.cursor + num_bytes as u64).max(self.details.valid_data_length);
926 self.details.data_length = valid_data_length.max(self.details.data_length);
927 self.details.valid_data_length = valid_data_length;
928 self.touched.is_dir_entry_dirty = true;
929 }
930
931 fn get_current_sector_id<D, const SIZE: usize, const N: usize>(
932 &self,
933 fs: &mut FileSystem<D, SIZE, N>,
934 ) -> ExFatResult<u32, D, SIZE>
935 where
936 D: BlockDevice<SIZE>,
937 {
938 let cluster_offset_bytes = self.cursor % fs.fs.cluster_length as u64;
939 let start_sector_id = fs.fs.get_heap_sector_id::<D, SIZE>(self.current_cluster)?;
940 let sector_id = start_sector_id + cluster_offset_bytes as u32 / SIZE as u32;
941 Ok(sector_id)
942 }
943
944 fn num_clusters<D, const SIZE: usize, const N: usize>(
945 &self,
946 fs: &mut FileSystem<D, SIZE, N>,
947 ) -> u32
948 where
949 D: BlockDevice<SIZE>,
950 {
951 self.details
952 .data_length
953 .div_ceil(fs.fs.cluster_length as u64) as u32
954 }
955
956 #[bisync]
958 async fn convert_file_to_fat_chain_if_required<D, const SIZE: usize, const N: usize>(
959 &mut self,
960 fs: &mut FileSystem<D, SIZE, N>,
961 ) -> ExFatResult<(), D, SIZE>
962 where
963 D: BlockDevice<SIZE>,
964 {
965 if self
966 .details
967 .flags
968 .contains(GeneralSecondaryFlags::NoFatChain)
969 {
970 self.details
972 .flags
973 .set(GeneralSecondaryFlags::NoFatChain, false);
974 self.touched.is_dir_entry_dirty = true;
975
976 match self.chain {
978 StoredChain::Contiguous {
979 first,
980 cluster_count,
981 } => {
982 let tail = first + cluster_count - 1;
983 for cluster_id in first..tail {
984 fs.fat
985 .set(&mut fs.dev, &mut self.touched, cluster_id, cluster_id + 1)
986 .await?;
987 }
988 }
989 _ => return Ok(()),
990 }
991 }
992
993 Ok(())
994 }
995
996 #[bisync]
997 async fn write_partial_sector<D, const SIZE: usize, const N: usize>(
998 &mut self,
999 fs: &mut FileSystem<D, SIZE, N>,
1000 buf: &[u8],
1001 ) -> ExFatResult<usize, D, SIZE>
1002 where
1003 D: BlockDevice<SIZE>,
1004 {
1005 if buf.is_empty() {
1006 return Ok(0);
1007 }
1008
1009 let start_index = (self.cursor % SIZE as u64) as usize;
1010 let end_index = SIZE.min(start_index + buf.len());
1011 let sector_id = self.get_current_sector_id(fs)?;
1012
1013 if start_index > 0 || end_index < SIZE {
1017 let slot = fs.data_blocks.read_mut(sector_id, &mut fs.dev).await?;
1018 let len = end_index - start_index;
1019 slot.as_mut_slice()[start_index..end_index].copy_from_slice(&buf[..len]);
1020 self.touched
1021 .insert(TouchedSector::new(TouchedKind::Data, sector_id));
1022 self.move_file_cursor(len);
1023 return Ok(len);
1024 }
1025
1026 Ok(0)
1027 }
1028
1029 fn get_cluster_offset<D, const SIZE: usize, const N: usize>(
1030 &self,
1031 fs: &mut FileSystem<D, SIZE, N>,
1032 ) -> u32
1033 where
1034 D: BlockDevice<SIZE>,
1035 {
1036 (self.cursor % fs.fs.cluster_length as u64) as u32
1037 }
1038
1039 fn eof(&self) -> bool {
1041 self.cursor >= self.details.data_length
1042 }
1043
1044 fn move_file_cursor(&mut self, num_bytes: usize) {
1045 self.cursor += num_bytes as u64;
1046 self.remaining_bytes_in_cluster -= num_bytes as u32;
1047 }
1048
1049 #[bisync]
1050 async fn next_cursor_id<D, const SIZE: usize, const N: usize>(
1051 &mut self,
1052 fs: &mut FileSystem<D, SIZE, N>,
1053 ) -> ExFatResult<u32, D, SIZE>
1054 where
1055 D: BlockDevice<SIZE>,
1056 {
1057 match self.chain {
1058 StoredChain::Empty => Err(ExFatError::EndOfFatChain),
1059 StoredChain::Contiguous {
1060 first,
1061 cluster_count,
1062 } => {
1063 let cursor_id = self.current_cluster + 1;
1064 if (first..first + cluster_count).contains(&cursor_id) {
1065 Ok(cursor_id)
1066 } else {
1067 Err(ExFatError::EndOfFatChain)
1068 }
1069 }
1070 StoredChain::Fat {
1071 first: _first,
1072 last: _last,
1073 cluster_count: _len,
1074 } => {
1075 match fs
1076 .fat
1077 .next_cluster_in_fat_chain(self.current_cluster, &mut fs.dev)
1078 .await?
1079 {
1080 Some(cluster_id) => Ok(cluster_id),
1081 None => Err(ExFatError::EndOfFatChain),
1082 }
1083 }
1084 }
1085 }
1086}
1087
1088#[allow(unused)]
1089#[cfg(test)]
1090mod tests {
1091 use super::super::only_sync;
1092 use super::*;
1093 use crate::test_utils::{empty_fs, read_file};
1094
1095 #[only_sync]
1096 #[test]
1097 fn fragmented_write_terminates_fat_chain_correctly() {
1098 let mut fs = empty_fs();
1101 fs.fat.start_of_fat_sector = Some(400);
1102 let cluster_len = fs.fs.cluster_length as usize;
1103 fs.dev.blocks[1][0] |= 0b0000_0100; let create = OpenOptions::new().create(true).write(true);
1107 let mut file = fs.open("fragmented.txt", create).unwrap();
1108 file.write(&mut fs, &vec![0xAA; cluster_len]).unwrap(); file.write(&mut fs, &vec![0xBB; cluster_len]).unwrap(); file.close(&mut fs).unwrap();
1111
1112 let fat = &fs.dev.blocks[400];
1114 assert_eq!(
1115 &fat[3 * 4..3 * 4 + 4],
1116 &5u32.to_le_bytes(),
1117 "cluster 3 -> 5"
1118 );
1119 assert_eq!(
1120 &fat[5 * 4..5 * 4 + 4],
1121 &0xFFFF_FFFFu32.to_le_bytes(),
1122 "cluster 5 -> END_OF_CHAIN"
1123 );
1124
1125 let options = OpenOptions::new().read(true);
1127 let mut file = fs.open("fragmented.txt", options).unwrap();
1128 let mut buf = vec![0u8; 2 * cluster_len];
1129 file.read(&mut fs, &mut buf).unwrap();
1130 assert!(
1131 buf[..cluster_len].iter().all(|&b| b == 0xAA)
1132 && buf[cluster_len..].iter().all(|&b| b == 0xBB)
1133 );
1134 }
1135
1136 #[only_sync]
1137 #[test]
1138 fn flush_without_changes_does_not_rewrite_dir_entry() {
1139 let mut fs = empty_fs();
1140 let create = OpenOptions::new().create(true).write(true);
1141 let mut file = fs.open("hello.txt", create).unwrap();
1142 file.write(&mut fs, b"foo").unwrap();
1143 file.flush(&mut fs).unwrap();
1144 let write_count = fs.dev.write_count;
1145
1146 file.flush(&mut fs).unwrap();
1148 assert_eq!(
1149 fs.dev.write_count, write_count,
1150 "flush without changes should not write dir entries"
1151 );
1152
1153 file.write(&mut fs, b"bla").unwrap();
1154 file.flush(&mut fs).unwrap();
1155 assert!(
1156 fs.dev.write_count > write_count,
1157 "flush after write should save dir entry"
1158 );
1159 file.close(&mut fs).unwrap();
1160 }
1161
1162 #[only_sync]
1163 #[test]
1164 fn overwrite_in_place_does_not_allocate() {
1165 let mut fs = empty_fs();
1166 let cl = fs.fs.cluster_length as usize;
1167 let create = OpenOptions::new().create(true).write(true);
1168 let mut file = fs.open("a.bin", create).unwrap();
1169 file.write(&mut fs, &vec![0xAA; cl]).unwrap(); file.close(&mut fs).unwrap();
1171 let bitmap_before = fs.dev.blocks[1][0];
1172
1173 let rw = OpenOptions::new().read(true).write(true);
1174 let mut file = fs.open("a.bin", rw).unwrap();
1175 file.write(&mut fs, &vec![0xBB; cl]).unwrap(); file.close(&mut fs).unwrap();
1177
1178 assert_eq!(
1179 fs.dev.blocks[1][0], bitmap_before,
1180 "in-place overwrite must not allocate clusters (bitmap {:#010b} was {:#010b})",
1181 fs.dev.blocks[1][0], bitmap_before,
1182 );
1183 let buf = read_file(&mut fs, "a.bin");
1184 assert_eq!(buf, vec![0xBB; cl]);
1185 }
1186
1187 #[only_sync]
1188 #[test]
1189 fn overwrite_extending_past_eof_allocates_only_the_overhang() {
1190 let mut fs = empty_fs();
1191 let cl = fs.fs.cluster_length as usize;
1192 let create = OpenOptions::new().create(true).write(true);
1193 let mut file = fs.open("b.bin", create).unwrap();
1194 file.write(&mut fs, &vec![0xAA; cl]).unwrap();
1195 file.seek(&mut fs, (cl / 2) as u64).unwrap();
1196 file.write(&mut fs, &vec![0xBB; cl]).unwrap(); file.close(&mut fs).unwrap();
1198
1199 assert_eq!(fs.dev.blocks[1][0], 0b0000_0111, "clusters 2,3,4 only");
1200 let data = read_file(&mut fs, "b.bin");
1201 assert_eq!(data.len(), cl + cl / 2);
1202 assert!(data[..cl / 2].iter().all(|&b| b == 0xAA));
1203 assert!(data[cl / 2..].iter().all(|&b| b == 0xBB));
1204 }
1205
1206 #[only_sync]
1207 #[test]
1208 fn write_after_truncate_allocates_and_marks_the_bitmap() {
1209 let mut fs = empty_fs();
1210 let cl = fs.fs.cluster_length as usize;
1211 let create = OpenOptions::new().create(true).write(true);
1212 let mut file = fs.open("a.bin", create).unwrap();
1213 file.write(&mut fs, &vec![0xAA; cl]).unwrap();
1214 file.close(&mut fs).unwrap();
1215
1216 let truncate = OpenOptions::new().write(true).truncate(true);
1217 let mut file = fs.open("a.bin", truncate).unwrap();
1218 file.write(&mut fs, b"hello").unwrap();
1219 file.close(&mut fs).unwrap();
1220
1221 assert_eq!(
1222 fs.dev.blocks[1][0].count_ones(),
1223 2,
1224 "bitmap must show root + one data cluster, got {:#010b}",
1225 fs.dev.blocks[1][0]
1226 );
1227
1228 let buf = read_file(&mut fs, "a.bin");
1229 assert_eq!(&buf, b"hello");
1230 }
1231
1232 #[only_sync]
1233 #[cfg(feature = "alloc")]
1234 #[test]
1235 fn reading_a_write_only_file_fails_even_at_eof() {
1236 let mut fs = empty_fs();
1237 let create = OpenOptions::new().create(true).write(true);
1238 let mut file = fs.open("write_only.txt", create).unwrap();
1239 file.write(&mut fs, b"hello").unwrap();
1240 file.close(&mut fs).unwrap();
1241
1242 let append = OpenOptions::new().write(true).append(true);
1244 let mut file = fs.open("write_only.txt", append).unwrap();
1245
1246 let result = file.read_to_string(&mut fs);
1248 assert!(
1249 matches!(result, Err(ExFatError::ReadNotEnabled)),
1250 "read_to_string on write-only handle should fail, got: {result:?}"
1251 );
1252
1253 let mut buf = Vec::new();
1255 let result = file.read_to_end(&mut fs, &mut buf);
1256 assert!(
1257 matches!(result, Err(ExFatError::ReadNotEnabled)),
1258 "read_to_end on write-only handle should fail, got: {result:?}"
1259 );
1260
1261 let result = file.read(&mut fs, &mut [0u8; 4]);
1263 assert!(
1264 matches!(result, Err(ExFatError::ReadNotEnabled)),
1265 "read on write-only handle should fail, got: {result:?}"
1266 );
1267
1268 let result = file.read(&mut fs, &mut []);
1270 assert!(
1271 matches!(result, Err(ExFatError::ReadNotEnabled)),
1272 "read on write-only handle should fail, got: {result:?}"
1273 );
1274 }
1275
1276 #[only_sync]
1277 #[cfg(feature = "alloc")]
1278 #[test]
1279 fn allocated_reads() {
1280 let mut fs = empty_fs();
1281 let create = OpenOptions::new().create(true).write(true);
1282 let mut file = fs.open("temp.txt", create).unwrap();
1283 file.write(&mut fs, b"hello").unwrap();
1284 file.close(&mut fs).unwrap();
1285
1286 let read = OpenOptions::new().read(true);
1288 let mut file = fs.open("temp.txt", read).unwrap();
1289
1290 let result = file.read_to_string(&mut fs).unwrap();
1292 assert_eq!(result, "hello");
1293
1294 let read = OpenOptions::new().read(true);
1296 let mut file = fs.open("temp.txt", read).unwrap();
1297
1298 let mut buf = Vec::new();
1300 let len = file.read_to_end(&mut fs, &mut buf).unwrap();
1301 assert_eq!(buf.len(), len);
1302 assert_eq!(len, 5);
1303 assert_eq!(&buf, b"hello");
1304
1305 let mut buf = Vec::new();
1307 let len = file.read_to_end(&mut fs, &mut buf).unwrap();
1308 assert_eq!(len, 0);
1309 }
1310}