simple-fatfs 0.1.0-alpha.2

A simple-to-use FAT filesystem library for Rust (mainly targeted at embedded systems)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
use crate::*;
use embedded_io::*;
use embedded_io_adapters::std::FromStd;

use akin::akin;
use test_log::test;

static MINFS: &[u8] = include_bytes!("../../imgs/minfs.img");
static FAT12: &[u8] = include_bytes!("../../imgs/fat12.img");
static FAT16: &[u8] = include_bytes!("../../imgs/fat16.img");
static FAT32: &[u8] = include_bytes!("../../imgs/fat32.img");

#[test]
#[allow(non_snake_case)]
fn check_FAT_offset() {
    use crate::fat::BootRecord;

    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let fat_offset = match &*fs.boot_record.borrow() {
        BootRecord::Fat(boot_record_fat) => boot_record_fat.first_fat_sector(),
        BootRecord::ExFAT(_boot_record_exfat) => unreachable!(),
    };

    // we manually read the first and second entry of the FAT table
    fs.load_nth_sector(fat_offset.into()).unwrap();

    let first_entry = u16::from_le_bytes(fs.sector_buffer.borrow()[..2].try_into().unwrap());
    let media_type = if let BootRecord::Fat(boot_record_fat) = &*fs.boot_record.borrow() {
        boot_record_fat.bpb._media_type
    } else {
        unreachable!("this should be a FAT16 filesystem")
    };
    assert_eq!(u16::MAX << 8 | u16::from(media_type), first_entry);

    let second_entry = u16::from_le_bytes(fs.sector_buffer.borrow()[2..4].try_into().unwrap());
    assert_eq!(u16::MAX, second_entry);
}

#[test]
fn read_file_in_root_dir() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/root.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "I am in the filesystem's root!!!\n\n";
    assert_eq!(file_string, EXPECTED_STR);
}

fn assert_vec_is_string(buf: &[u8], expected_string: &str) {
    let string = std::str::from_utf8(buf).unwrap();
    let expected_size = expected_string.len();
    assert_eq!(buf.len(), expected_size);

    assert_eq!(string, expected_string);
}
fn assert_file_against_string<S>(file: &mut ROFile<'_, S>, expected_string: &str)
where
    S: Read + Write + Seek,
{
    let mut buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut buf).unwrap();

    assert_vec_is_string(&buf, expected_string);
}

static BEE_MOVIE_SCRIPT: &str = include_str!("../../tests/bee movie script.txt");
fn assert_vec_is_bee_movie_script(buf: &[u8]) {
    assert_vec_is_string(buf, BEE_MOVIE_SCRIPT)
}
fn assert_file_is_bee_movie_script<S>(file: &mut ROFile<'_, S>)
where
    S: Read + Write + Seek,
{
    assert_file_against_string(file, BEE_MOVIE_SCRIPT);
}
static I_DONT_NEED_A_BADGE: &str = include_str!("../../tests/I don't need a badge.txt");
fn assert_file_is_i_dont_need_a_badge<S>(file: &mut ROFile<'_, S>)
where
    S: Read + Write + Seek,
{
    assert_file_against_string(file, I_DONT_NEED_A_BADGE);
}
#[test]
fn read_huge_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/bee movie script.txt").unwrap();
    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn seek_n_read() {
    use std::io::Cursor;

    // this uses the famous "I'd like to interject for a moment" copypasta as a test file
    // you can find it online by just searching this term

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/GNU ⁄ Linux copypasta.txt").unwrap();
    let mut file_bytes = [0_u8; 4096];

    // we first perform a forward seek...
    const EXPECTED_STR1: &str = "Linux is the kernel";
    file.seek(SeekFrom::Start(792)).unwrap();
    let bytes_read = file.read(&mut file_bytes[..EXPECTED_STR1.len()]).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&file_bytes[..bytes_read]),
        EXPECTED_STR1
    );

    // ...then a backward one
    const EXPECTED_STR2: &str = "What you're referring to as Linux, is in fact, GNU/Linux";
    file.seek(SeekFrom::Start(39)).unwrap();
    let bytes_read = file.read(&mut file_bytes[..EXPECTED_STR2.len()]).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&file_bytes[..bytes_read]),
        EXPECTED_STR2
    );
}

#[test]
// this won't actually modify the .img file or the static slices,
// since we run .to_owned(), which basically clones the data in the static slices,
// in order to make the Cursor readable/writable
fn write_to_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT12.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_rw_file("/root.txt").unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_bee_movie_script(&mut file);

    // now let's do something else
    // this write operations will happen between 2 clusters
    const TEXT_OFFSET: u64 = 4598;
    const TEXT: &str = "Hello from the other side";

    file.seek(SeekFrom::Start(TEXT_OFFSET)).unwrap();
    file.write_all(TEXT.as_bytes()).unwrap();

    // seek back to the start of where we wrote our text
    file.seek(SeekFrom::Current(-i64::try_from(TEXT.len()).unwrap()))
        .unwrap();
    let mut buf = [0_u8; TEXT.len()];
    file.read_exact(&mut buf).unwrap();
    let stored_text = std::str::from_utf8(&buf).unwrap();

    assert_eq!(TEXT, stored_text);

    // we are also gonna write the bee movie ten more times to see if FAT12 can correctly handle split entries
    for i in 0..10 {
        log::debug!("Writing the bee movie script for the {i} consecutive time",);

        let start_offset = file.seek(SeekFrom::End(0)).unwrap();

        file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
        file.seek(SeekFrom::Start(start_offset)).unwrap();

        let mut buf = vec![0_u8; BEE_MOVIE_SCRIPT.len()];
        file.read_exact(buf.as_mut_slice()).unwrap();

        assert_vec_is_bee_movie_script(&buf);
    }
}

#[test]
fn create_root_dir_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.create_file("/new.txt").unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_subdir_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs
        .create_file("/another root directory/baby i am free.txt")
        .unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_lots_of_files() {
    use regex::Regex;
    use std::io::Cursor;

    const FILE_COUNT: usize = 1_000;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    for i in 1..=FILE_COUNT {
        let name = PathBuf::from(&format!("/another root directory/{i}.txt"));
        let mut file = fs.create_file(&name).unwrap();

        file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
        file.rewind().unwrap();

        drop(file);
    }

    let dir = fs.read_dir("/another root directory/").unwrap();
    let mut found = [false; FILE_COUNT];
    let re = Regex::new(r"([0-9]*).txt").unwrap();
    for entry in dir {
        let entry = entry.unwrap();
        if entry.is_file() {
            let file_name = entry.path().file_name().unwrap();
            if let Some(c_id) = re.captures(file_name) {
                let id: usize = c_id[1].parse().unwrap();
                if (1..=FILE_COUNT).contains(&id) {
                    found[id - 1] = true;
                    let mut file = entry.to_ro_file().unwrap();
                    assert_file_is_i_dont_need_a_badge(&mut file);
                } else {
                    log::error!("Found unexpected file with name \"{id}\"")
                }
            }
        }
    }

    let mut all_found = true;
    for (id, id_found) in found.iter().enumerate() {
        if !id_found {
            all_found = false;
            log::error!("File /another root directory/{id}.txt not found")
        }
    }

    assert!(
        all_found,
        "Some files that were created weren't found during directory iteration"
    )
}

#[test]
fn create_directory_in_root_and_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.create_dir("/unbelievable").unwrap();
    let mut file = fs.create_file("/unbelievable/baby i am free.txt").unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_directory_in_subdir_and_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.create_dir("/another root directory2").unwrap();
    let mut file = fs
        .create_file(PathBuf::from(
            "/another root directory/bee movie script.txt",
        ))
        .unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn rename_root_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/root.txt", "/rootdir/not root.txt").unwrap();

    let mut file = fs.get_ro_file("/rootdir/not root.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "I am in the filesystem's root!!!\n\n";
    assert_eq!(file_string, EXPECTED_STR);
}

#[test]
fn rename_nonroot_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/rootdir/example.txt", "/another root directory/hello.txt")
        .unwrap();

    let mut file = fs.get_ro_file("/another root directory/hello.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "I am not in the root directory :(\n\n";
    assert_eq!(file_string, EXPECTED_STR);
}

#[test]
fn rename_root_directory() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/rootdir", "/rootdir2").unwrap();

    let mut file = fs.get_ro_file("/rootdir2/example.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "I am not in the root directory :(\n\n";
    assert_eq!(file_string, EXPECTED_STR);
}

#[test]
fn rename_root_file_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/hello.txt", "/emptydir/bye.txt").unwrap();

    let mut file = fs.get_ro_file("/emptydir/bye.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "Hello from a FAT32 filesystem!!!\n";
    assert_eq!(file_string, EXPECTED_STR);
}

#[test]
fn rename_nonroot_file_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/secret/bee movie script.txt", "/BEES.txt")
        .unwrap();

    let mut file = fs.get_ro_file("/BEES.txt").unwrap();

    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn rename_root_directory_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.rename("/secret", "/emptydir/secret").unwrap();

    let mut file = fs
        .get_ro_file("/emptydir/secret/bee movie script.txt")
        .unwrap();

    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn remove_root_dir_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    // the bee movie script (here) is in the root directory region
    let file_path = "/bee movie script.txt";
    let file = fs.get_rw_file(file_path).unwrap();
    file.remove().unwrap();

    // the file should now be gone
    let file_result = fs.get_ro_file(file_path);
    match file_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("file should have been deleted by now"),
    }
}

#[test]
fn remove_data_region_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT12.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    // the bee movie script (here) is in the data region
    let file_path = "/test/bee movie script.txt";
    let file = fs.get_rw_file(file_path).unwrap();
    file.remove().unwrap();

    // the file should now be gone
    let file_result = fs.get_ro_file(file_path);
    match file_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("file should have been deleted by now"),
    }
}

#[test]
fn remove_empty_dir() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let dir_path = "/another root directory/";

    fs.remove_empty_dir(dir_path).unwrap();

    // the directory should now be gone
    let dir_result = fs.read_dir(dir_path);
    match dir_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the directory should have been deleted by now"),
    }
}

#[test]
fn remove_nonempty_dir_with_readonly_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let dir_path = "/rootdir/";

    // the directory should contain a read-only file (example.txt)
    let del_result = fs.remove_dir_all(dir_path);
    match del_result {
        Err(err) => match err {
            FSError::ReadOnlyFile => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the directory shouldn't have been removed already"),
    }

    // this should now remove the directory
    fs.remove_dir_all_unchecked(dir_path).unwrap();

    // the directory should now be gone
    let dir_result = fs.read_dir(dir_path);
    match dir_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the directory should have been deleted by now"),
    }
}
akin! {
    let &fat_type = [FAT12, FAT16, FAT32];
    let &unused_entries = [5, 2, 1];

    #[test]
    #[allow(non_snake_case)]
    fn entry_defragment_~*fat_type() {
        const UNUSED_ENTRY_COUNT: EntryCount = *unused_entries;

        use std::io::Cursor;

        let mut storage = FromStd::new(Cursor::new(~*fat_type.to_owned()));
        let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();
        fs.show_hidden(true);

        // ik, this is dirty
        let old_entry_count = {
            let mut i: EntryCount = 0;

            fs.go_to_dir("/").unwrap();

            let mut current_entry = EntryLocation {
                unit: fs.dir_info.borrow().chain_start,
                index: 0,
            };

            while let Some(next_entry) = current_entry
                .next_entry(&fs)
                .unwrap()
                .filter(|entry| entry.entry_status(&fs).unwrap() != EntryStatus::LastUnused)
            {
                current_entry = next_entry;
                i += 1
            }

            // we miss the last entry because of the .filter
            i + 1
        };

        log::info!("Old entry count: {old_entry_count}");

        let old_names: Box<[Box<str>]> = fs
            .read_dir("/")
            .unwrap()
            .map(|entry| entry.unwrap())
            .map(|entry| entry.path().file_name().unwrap().to_owned())
            .map(Box::from)
            .collect();

        let new_entry_count = fs.defragment_entry_chain().unwrap();

        log::info!("New entry count: {new_entry_count}");

        let new_names: Box<[Box<str>]> = fs
            .read_dir("/")
            .unwrap()
            .map(|entry| entry.unwrap())
            .map(|entry| entry.path().file_name().unwrap().to_owned())
            .map(Box::from)
            .collect();

        assert_eq!(old_names, new_names);
        assert_eq!(old_entry_count - UNUSED_ENTRY_COUNT, new_entry_count);
    }
}

#[test]
#[allow(non_snake_case)]
fn FAT_tables_after_write_are_identical() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    assert!(
        fs.FAT_tables_are_identical().unwrap(),
        concat!(
            "this should pass. ",
            "if it doesn't, either the corresponding .img file's FAT tables aren't identical",
            "or the tables_are_identical function doesn't work correctly"
        )
    );

    // let's write the bee movie script to root.txt (why not), check, truncate the file, then check again
    let mut file = fs.get_rw_file("root.txt").unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
    assert!(file.fs.FAT_tables_are_identical().unwrap());

    file.seek(SeekFrom::Start(10_000)).unwrap();
    assert!(file.fs.FAT_tables_are_identical().unwrap());
}

#[test]
fn truncate_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_rw_file("/bee movie script.txt").unwrap();

    // we are gonna truncate the bee movie script down to 20 000 bytes
    const NEW_SIZE: usize = 20_000;
    file.seek(SeekFrom::Start(20_000)).unwrap();
    file.truncate().unwrap();

    file.rewind().unwrap();
    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    let mut expected_string = BEE_MOVIE_SCRIPT.to_string();
    expected_string.truncate(NEW_SIZE);

    assert_eq!(file_string, expected_string);
}

#[test]
fn read_only_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let file_result = fs.get_rw_file("/rootdir/example.txt");

    match file_result {
        Err(err) => match err {
            FSError::ReadOnlyFile => (),
            _ => panic!("unexpected IOError"),
        },
        _ => panic!("file is marked read-only, yet somehow we got a RWFile for it"),
    }
}

#[test]
fn get_hidden_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT12.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let file_path = "/hidden";
    {
        let file_result = fs.get_ro_file(file_path);
        match file_result {
            Err(err) => match err {
                FSError::NotFound => (),
                _ => panic!("unexpected IOError"),
            },
            _ => panic!("file should be hidden by default"),
        }
    }

    {
        // let's now allow the filesystem to list hidden files
        fs.show_hidden(true);
        let file = fs.get_ro_file(file_path).unwrap();
        assert!(file.attributes.hidden);
    }
}

#[test]
fn read_file_in_subdir() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/rootdir/example.txt").unwrap();

    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let file_string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "I am not in the root directory :(\n\n";
    assert_eq!(file_string, EXPECTED_STR);
}

#[test]
fn check_file_timestamps() {
    use ::time::macros::*;

    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let file = fs.get_ro_file("/rootdir/example.txt").unwrap();

    assert_eq!(Some(datetime!(2024-07-11 13:02:38.15)), file.created);
    assert_eq!(datetime!(2024-07-11 13:02:38.0), file.modified);
    assert_eq!(Some(date!(2024 - 07 - 11)), file.accessed);
}

#[test]
fn modify_file_timestamps() {
    use ::time::macros::*;

    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_rw_file("/bee movie script.txt").unwrap();

    // back to the future we go
    file.set_accessed(date!(1985 - 07 - 3));

    drop(file);

    let file = fs.get_ro_file("/bee movie script.txt").unwrap();

    assert_eq!(&Some(date!(1985 - 07 - 3)), file.last_accessed_date());
}

#[test]
fn check_last_accessed_ro() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/rootdir/example.txt").unwrap();

    // read some data
    let mut target = [0; 42];
    file.read(&mut target).unwrap();

    drop(file);

    let file = fs.get_ro_file("/rootdir/example.txt").unwrap();

    assert_ne!(&Some(DefaultClock.now().date()), file.last_accessed_date());
}

#[test]
fn check_last_accessed_rw() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new().with_update_file_fields(true)).unwrap();

    let mut file = fs.get_rw_file("/bee movie script.txt").unwrap();

    // read some data
    let mut target = [0; 42];
    file.read(&mut target).unwrap();

    drop(file);

    let file = fs.get_ro_file("/bee movie script.txt").unwrap();

    assert_eq!(&Some(DefaultClock.now().date()), file.last_accessed_date());
}

#[test]
fn check_last_modified() {
    use ::time::Duration;

    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT16.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new().with_update_file_fields(true)).unwrap();

    let mut file = fs.get_rw_file("/bee movie script.txt").unwrap();

    // just some random data
    file.write(&[49, 65, 47]).unwrap();

    drop(file);

    let file = fs.get_ro_file("/bee movie script.txt").unwrap();

    assert_eq!(&Some(DefaultClock.now().date()), file.last_accessed_date());
    // I find it highly unlikely that this test won't have been completed within 15 seconds
    assert!(DefaultClock.now() - *file.modification_time() < Duration::seconds(15));
}

#[test]
fn read_file_fat12() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT12.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    {
        let mut file = fs.get_ro_file("/foo/bar.txt").unwrap();
        let mut file_buf = vec![0; file.file_size() as usize];
        file.read_exact(&mut file_buf).unwrap();
        let file_string = str::from_utf8(&file_buf).unwrap();
        const EXPECTED_STR: &str = "Hello, World!\n";
        assert_eq!(file_string, EXPECTED_STR);
    }

    {
        // please not that the FAT12 image has been modified so that
        // one FAT entry of the file we are reading is split between different sectors
        // this way, we also test for this case
        let mut file = fs.get_ro_file("/test/bee movie script.txt").unwrap();
        assert_file_is_bee_movie_script(&mut file);
    }
}

#[test]
fn read_file_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/secret/bee movie script.txt").unwrap();

    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn create_file_root_dir_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs
        .create_file("/bee movie script or something ig.txt")
        .unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_file_subdir_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.create_file("/secret/baby i am free.txt").unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_directory_in_root_and_file_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.create_dir("/unbelievable").unwrap();
    let mut file = fs.create_file("/unbelievable/baby i am free.txt").unwrap();

    file.write_all(I_DONT_NEED_A_BADGE.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_i_dont_need_a_badge(&mut file);
}

#[test]
fn create_directory_in_subdir_and_file_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    fs.create_dir("/another root directory").unwrap();
    let mut file = fs
        .create_file(PathBuf::from(
            "/another root directory/bee movie script.txt",
        ))
        .unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
    file.rewind().unwrap();

    assert_file_is_bee_movie_script(&mut file);
}

#[test]
fn seek_n_read_fat32() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_ro_file("/hello.txt").unwrap();
    file.seek(SeekFrom::Start(13)).unwrap();

    #[allow(clippy::cast_possible_truncation)]
    let mut file_buf =
        vec![0; (file.file_size() - file.stream_position().unwrap() as u32) as usize];
    file.read_exact(&mut file_buf).unwrap();
    let string = str::from_utf8(&file_buf).unwrap();
    const EXPECTED_STR: &str = "FAT32 filesystem!!!\n";

    assert_eq!(string, EXPECTED_STR);
}

#[test]
fn write_to_fat32_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let mut file = fs.get_rw_file("/hello.txt").unwrap();
    // an arbitrary offset to seek to
    const START_OFFSET: u64 = 1436;
    file.seek(SeekFrom::Start(START_OFFSET)).unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();

    // seek back
    file.seek(SeekFrom::Current(
        -i64::try_from(BEE_MOVIE_SCRIPT.len()).unwrap(),
    ))
    .unwrap();

    // read back what we wrote
    #[allow(clippy::cast_possible_truncation)]
    let mut file_buf =
        vec![0; (file.file_size() - file.stream_position().unwrap() as u32) as usize];
    file.read_exact(&mut file_buf).unwrap();
    let string = str::from_utf8(&file_buf).unwrap();
    assert_eq!(string, BEE_MOVIE_SCRIPT);

    // let's also read back what was (and hopefully still is)
    // at the start of the file
    const EXPECTED_STR: &str = "Hello from a FAT32 filesystem!!!\n";
    file.rewind().unwrap();
    let mut buf = [0_u8; EXPECTED_STR.len()];
    file.read_exact(&mut buf).unwrap();

    let stored_text = std::str::from_utf8(&buf).unwrap();
    assert_eq!(stored_text, EXPECTED_STR)
}

#[test]
fn truncate_fat32_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    const EXPECTED_STR: &str = "Hello fr";

    let mut file = fs.get_rw_file("/hello.txt").unwrap();
    file.seek(SeekFrom::Start(EXPECTED_STR.len() as u64))
        .unwrap();
    file.truncate().unwrap();

    file.rewind().unwrap();
    let mut file_buf = vec![0; file.file_size() as usize];
    file.read_exact(&mut file_buf).unwrap();
    let string = str::from_utf8(&file_buf).unwrap();
    assert_eq!(string, EXPECTED_STR);
}

#[test]
fn remove_fat32_file() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let file_path = "/secret/bee movie script.txt";

    let file = fs.get_rw_file(file_path).unwrap();
    file.remove().unwrap();

    // the file should now be gone
    let file_result = fs.get_ro_file(file_path);
    match file_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("file should have been deleted by now"),
    }
}

#[test]
fn remove_empty_fat32_dir() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let dir_path = "/emptydir/";

    fs.remove_empty_dir(dir_path).unwrap();

    // the directory should now be gone
    let dir_result = fs.read_dir(dir_path);
    match dir_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the directory should have been deleted by now"),
    }
}

#[test]
fn remove_nonempty_fat32_dir() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let dir_path = "/secret/";

    fs.remove_dir_all(dir_path).unwrap();

    // the directory should now be gone
    let dir_result = fs.read_dir(dir_path);
    match dir_result {
        Err(err) => match err {
            FSError::NotFound => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the directory should have been deleted by now"),
    }
}

#[test]
fn attempt_to_remove_file_as_directory() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    let dir_path = "/hello.txt";

    let fs_result = fs.remove_dir_all(dir_path);

    match fs_result {
        Err(err) => match err {
            FSError::NotADirectory => (),
            _ => panic!("unexpected IOError: {err:?}"),
        },
        _ => panic!("the filesystem struct should have detected that this isn't a directory"),
    }
}

#[test]
fn read_dir_and_go_back() {
    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    for entry in fs.read_dir("/").unwrap() {
        let entry = entry.unwrap();

        if entry.path() == "/secret/" {
            let mut secret_dir = entry.to_dir().unwrap();

            let bee_movie_script_found = secret_dir.any(|res| {
                if let Ok(entry) = res {
                    entry.is_file() && entry.path() == "/secret/bee movie script.txt"
                } else {
                    false
                }
            });

            assert!(
                bee_movie_script_found,
                "couldn't find \"/secret/bee movie script.txt\""
            )
        }
    }
}

#[test]
#[allow(non_snake_case)]
fn FAT_tables_after_fat32_write_are_identical() {
    use crate::fat::{BootRecord, Ebr};

    use std::io::Cursor;

    let mut storage = FromStd::new(Cursor::new(FAT32.to_owned()));
    let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

    match &*fs.boot_record.borrow() {
        BootRecord::Fat(boot_record_fat) => match &boot_record_fat.ebr {
            Ebr::FAT32(ebr_fat32, _) => assert!(
                !ebr_fat32.extended_flags.mirroring_disabled(),
                "mirroring should be enabled for this .img file"
            ),
            _ => unreachable!(),
        },
        _ => unreachable!(),
    }

    assert!(
        fs.FAT_tables_are_identical().unwrap(),
        concat!(
            "this should pass. ",
            "if it doesn't, either the corresponding .img file's FAT tables aren't identical",
            "or the tables_are_identical function doesn't work correctly"
        )
    );

    // let's write the bee movie script to root.txt (why not), check, truncate the file, then check again
    let mut file = fs.get_rw_file("hello.txt").unwrap();

    file.write_all(BEE_MOVIE_SCRIPT.as_bytes()).unwrap();
    assert!(file.fs.FAT_tables_are_identical().unwrap());

    file.seek(SeekFrom::Start(10_000)).unwrap();
    file.truncate().unwrap();
    assert!(file.fs.FAT_tables_are_identical().unwrap());
}

#[test]
fn assert_img_fat_type() {
    static TEST_CASES: &[(&[u8], FATType)] = &[
        (MINFS, FATType::FAT12),
        (FAT12, FATType::FAT12),
        (FAT16, FATType::FAT16),
        (FAT32, FATType::FAT32),
    ];

    for case in TEST_CASES {
        use std::io::Cursor;

        let mut storage = FromStd::new(Cursor::new(case.0));
        let fs = FileSystem::new(&mut storage, FSOptions::new()).unwrap();

        assert_eq!(fs.fat_type(), case.1)
    }
}