forked from trussed-dev/littlefs2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.rs
More file actions
1494 lines (1302 loc) · 49.4 KB
/
fs.rs
File metadata and controls
1494 lines (1302 loc) · 49.4 KB
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
//! Experimental Filesystem version using closures.
use core::{cell::RefCell, cmp, mem, slice};
use bitflags::bitflags;
use generic_array::typenum::marker_traits::Unsigned;
use littlefs2_sys as ll;
use serde::{Deserialize, Serialize};
// so far, don't need `heapless-bytes`.
pub type Bytes<SIZE> = generic_array::GenericArray<u8, SIZE>;
use crate::{
driver,
io::{self, Result},
path::{Path, PathBuf},
};
struct Cache<Storage: driver::Storage> {
read: Bytes<Storage::CACHE_SIZE>,
write: Bytes<Storage::CACHE_SIZE>,
// lookahead: aligned::Aligned<aligned::A4, Bytes<Storage::LOOKAHEAD_SIZE>>,
lookahead: generic_array::GenericArray<u64, Storage::LOOKAHEAD_SIZE>,
}
impl<S: driver::Storage> Cache<S> {
pub fn new() -> Self {
Self {
read: Default::default(),
write: Default::default(),
lookahead: Default::default(),
}
}
}
impl<S: driver::Storage> Default for Cache<S> {
fn default() -> Self {
Self::new()
}
}
pub struct Allocation<Storage: driver::Storage> {
cache: Cache<Storage>,
config: ll::lfs_config,
state: ll::lfs_t,
}
// pub fn check_storage_requirements(
impl<Storage: driver::Storage> Default for Allocation<Storage> {
fn default() -> Self {
Self::new()
}
}
impl<Storage: driver::Storage> Allocation<Storage> {
pub fn new() -> Allocation<Storage> {
let read_size: u32 = Storage::READ_SIZE as _;
let write_size: u32 = Storage::WRITE_SIZE as _;
let block_size: u32 = Storage::BLOCK_SIZE as _;
let cache_size: u32 = <Storage as driver::Storage>::CACHE_SIZE::U32;
let lookahead_size: u32 = 8 * <Storage as driver::Storage>::LOOKAHEAD_SIZE::U32;
let block_cycles: i32 = Storage::BLOCK_CYCLES as _;
let block_count: u32 = Storage::BLOCK_COUNT as _;
debug_assert!(block_cycles >= -1);
debug_assert!(block_cycles != 0);
debug_assert!(block_count > 0);
debug_assert!(read_size > 0);
debug_assert!(write_size > 0);
// https://github.com/ARMmbed/littlefs/issues/264
// Technically, 104 is enough.
debug_assert!(block_size >= 128);
debug_assert!(cache_size > 0);
debug_assert!(lookahead_size > 0);
// cache must be multiple of read
debug_assert!(read_size <= cache_size);
debug_assert!(cache_size % read_size == 0);
// cache must be multiple of write
debug_assert!(write_size <= cache_size);
debug_assert!(cache_size % write_size == 0);
// block must be multiple of cache
debug_assert!(cache_size <= block_size);
debug_assert!(block_size % cache_size == 0);
let cache = Cache::new();
let filename_max_plus_one: u32 = crate::consts::FILENAME_MAX_PLUS_ONE;
debug_assert!(filename_max_plus_one > 1);
debug_assert!(filename_max_plus_one <= 1_022 + 1);
// limitation of ll-bindings
debug_assert!(filename_max_plus_one == 255 + 1);
let path_max_plus_one: u32 = crate::consts::PATH_MAX_PLUS_ONE as _;
// TODO: any upper limit?
debug_assert!(path_max_plus_one >= filename_max_plus_one);
let file_max = crate::consts::FILEBYTES_MAX;
assert!(file_max > 0);
assert!(file_max <= 2_147_483_647);
// limitation of ll-bindings
assert!(file_max == 2_147_483_647);
let attr_max: u32 = crate::consts::ATTRBYTES_MAX;
assert!(attr_max > 0);
assert!(attr_max <= 1_022);
// limitation of ll-bindings
assert!(attr_max == 1_022);
let config = ll::lfs_config {
context: core::ptr::null_mut(),
read: Some(<Filesystem<'_, Storage>>::lfs_config_read),
prog: Some(<Filesystem<'_, Storage>>::lfs_config_prog),
erase: Some(<Filesystem<'_, Storage>>::lfs_config_erase),
sync: Some(<Filesystem<'_, Storage>>::lfs_config_sync),
// read: None,
// prog: None,
// erase: None,
// sync: None,
read_size,
prog_size: write_size,
block_size,
block_count,
block_cycles,
cache_size,
lookahead_size,
read_buffer: core::ptr::null_mut(),
prog_buffer: core::ptr::null_mut(),
lookahead_buffer: core::ptr::null_mut(),
name_max: filename_max_plus_one.wrapping_sub(1),
file_max,
attr_max,
};
Self {
cache,
state: unsafe { mem::MaybeUninit::zeroed().assume_init() },
config,
}
}
}
// pub struct Filesystem<'alloc, 'storage, Storage: driver::Storage> {
// pub(crate) alloc: &'alloc mut Allocation<Storage>,
// pub(crate) storage: &'storage mut Storage,
// }
// one lifetime is simpler than two... hopefully should be enough
// also consider "erasing" the lifetime completely
pub struct Filesystem<'a, Storage: driver::Storage> {
alloc: RefCell<&'a mut Allocation<Storage>>,
storage: &'a mut Storage,
}
/// Regular file vs directory
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum FileType {
File,
Dir,
}
impl FileType {
#[allow(clippy::all)] // following `std::fs`
pub fn is_dir(&self) -> bool {
*self == FileType::Dir
}
#[allow(clippy::all)] // following `std::fs`
pub fn is_file(&self) -> bool {
*self == FileType::File
}
}
/// File type (regular vs directory) and size of a file.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
file_type: FileType,
size: usize,
}
impl Metadata {
pub fn file_type(&self) -> FileType {
self.file_type
}
pub fn is_dir(&self) -> bool {
self.file_type().is_dir()
}
pub fn is_file(&self) -> bool {
self.file_type().is_file()
}
pub fn len(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
}
impl From<ll::lfs_info> for Metadata {
fn from(info: ll::lfs_info) -> Self {
let file_type = match info.type_ as u32 {
ll::lfs_type_LFS_TYPE_DIR => FileType::Dir,
ll::lfs_type_LFS_TYPE_REG => FileType::File,
_ => {
unreachable!();
}
};
Metadata {
file_type,
size: info.size as usize,
}
}
}
impl<Storage: driver::Storage> Filesystem<'_, Storage> {
pub fn allocate() -> Allocation<Storage> {
Allocation::new()
}
pub fn format(storage: &mut Storage) -> Result<()> {
let alloc = &mut Allocation::new();
let fs = Filesystem::new(alloc, storage);
let mut alloc = fs.alloc.borrow_mut();
let return_code = unsafe { ll::lfs_format(&mut alloc.state, &alloc.config) };
io::result_from((), return_code)
}
// TODO: check if this is equivalent to `is_formatted`.
pub fn is_mountable(storage: &mut Storage) -> bool {
let alloc = &mut Allocation::new();
matches!(Filesystem::mount(alloc, storage), Ok(_))
}
// Can BorrowMut be implemented "unsafely" instead?
// This is intended to be a second option, besides `into_inner`, to
// get access to the Flash peripheral in Storage.
pub unsafe fn borrow_storage_mut(&mut self) -> &mut Storage {
self.storage
}
/// This API avoids the need for using `Allocation`.
pub fn mount_and_then<R>(
storage: &mut Storage,
f: impl FnOnce(&Filesystem<'_, Storage>) -> Result<R>,
) -> Result<R> {
let mut alloc = Allocation::new();
let fs = Filesystem::mount(&mut alloc, storage)?;
f(&fs)
}
/// Total number of blocks in the filesystem
pub fn total_blocks(&self) -> usize {
Storage::BLOCK_COUNT
}
/// Total number of bytes in the filesystem
pub fn total_space(&self) -> usize {
Storage::BLOCK_COUNT * Storage::BLOCK_SIZE
}
/// Available number of unused blocks in the filesystem
///
/// Upstream littlefs documentation notes (on its "current size" function):
/// "Result is best effort. If files share COW structures, the returned size may be larger
/// than the filesystem actually is."
///
/// So it would seem that there are *at least* the number of blocks returned
/// by this method available, at any given time.
pub fn available_blocks(&self) -> Result<usize> {
let return_code = unsafe { ll::lfs_fs_size(&mut self.alloc.borrow_mut().state) };
io::result_from(return_code, return_code)
.map(|blocks| self.total_blocks() - blocks as usize)
}
/// Available number of unused bytes in the filesystem
///
/// This is a lower bound, more may be available. First, more blocks may be available as
/// explained in [`available_blocks`](struct.Filesystem.html#method.available_blocks).
/// Second, files may be inlined.
pub fn available_space(&self) -> Result<usize> {
self.available_blocks()
.map(|blocks| blocks * Storage::BLOCK_SIZE)
}
/// Remove a file or directory.
pub fn remove(&self, path: &Path) -> Result<()> {
let return_code =
unsafe { ll::lfs_remove(&mut self.alloc.borrow_mut().state, path.as_ptr()) };
io::result_from((), return_code)
}
/// Remove a file or directory.
pub fn remove_dir(&self, path: &Path) -> Result<()> {
self.remove(path)
}
/// TODO: This method fails if some `println!` calls are removed.
/// Whyy?
#[cfg(feature = "dir-entry-path")]
pub fn remove_dir_all(&self, path: &Path) -> Result<()> {
self.remove_dir_all_where(path, &|_| true).map(|_| ())
}
#[cfg(feature = "dir-entry-path")]
pub fn remove_dir_all_where<P>(&self, path: &Path, predicate: &P) -> Result<usize>
where
P: Fn(&DirEntry) -> bool,
{
if !path.exists(self) {
debug_now!("no such directory {}, early return", path);
return Ok(0);
}
let mut skipped_any = false;
let mut files_removed = 0;
debug_now!("starting to remove_dir_all_where in {}", path);
self.read_dir_and_then(path, |read_dir| {
// skip "." and ".."
for entry in read_dir.skip(2) {
let entry = entry?;
if entry.file_type().is_file() {
if predicate(&entry) {
debug_now!("removing file {}", &entry.path());
self.remove(entry.path())?;
debug_now!("...done");
files_removed += 1;
} else {
debug_now!("skipping file {}", &entry.path());
skipped_any = true;
}
}
if entry.file_type().is_dir() {
debug_now!("recursing into directory {}", &entry.path());
files_removed += self.remove_dir_all_where(entry.path(), predicate)?;
debug_now!("...back");
}
}
Ok(())
})?;
if !skipped_any {
debug_now!("removing directory {} too", &path);
self.remove_dir(path)?;
debug_now!("..worked");
}
Ok(files_removed)
}
/// Rename or move a file or directory.
pub fn rename(&self, from: &Path, to: &Path) -> Result<()> {
let return_code = unsafe {
ll::lfs_rename(
&mut self.alloc.borrow_mut().state,
from.as_ptr(),
to.as_ptr(),
)
};
io::result_from((), return_code)
}
/// Given a path, query the filesystem to get information about a file or directory.
///
/// To read user attributes, use
/// [`Filesystem::attribute`](struct.Filesystem.html#method.attribute)
pub fn metadata(&self, path: &Path) -> Result<Metadata> {
// do *not* not call assume_init here and pass into the unsafe block.
// strange things happen ;)
// TODO: Check we don't have UB here *too*.
// I think it's fine, as we immediately copy out the data
// to our own structure.
let mut info: ll::lfs_info = unsafe { mem::MaybeUninit::zeroed().assume_init() };
let return_code =
unsafe { ll::lfs_stat(&mut self.alloc.borrow_mut().state, path.as_ptr(), &mut info) };
io::result_from((), return_code).map(|_| info.into())
}
pub fn create_file_and_then<R>(
&self,
path: &Path,
f: impl FnOnce(&File<'_, '_, Storage>) -> Result<R>,
) -> Result<R> {
File::create_and_then(self, path, f)
}
pub fn open_file_and_then<R>(
&self,
path: &Path,
f: impl FnOnce(&File<'_, '_, Storage>) -> Result<R>,
) -> Result<R> {
File::open_and_then(self, path, f)
}
pub fn with_options() -> OpenOptions {
OpenOptions::new()
}
pub fn open_file_with_options_and_then<R>(
&self,
o: impl FnOnce(&mut OpenOptions) -> &OpenOptions,
path: &Path,
f: impl FnOnce(&File<'_, '_, Storage>) -> Result<R>,
) -> Result<R> {
let mut options = OpenOptions::new();
o(&mut options).open_and_then(self, path, f)
}
/// Read attribute.
pub fn attribute(&self, path: &Path, id: u8) -> Result<Option<Attribute>> {
let mut attribute = Attribute::new(id);
let attr_max = crate::consts::ATTRBYTES_MAX;
let return_code = unsafe {
ll::lfs_getattr(
&mut self.alloc.borrow_mut().state,
path.as_ptr(),
id,
&mut attribute.data as *mut _ as *mut cty::c_void,
attr_max,
)
};
if return_code >= 0 {
attribute.size = cmp::min(attr_max, return_code as u32) as usize;
return Ok(Some(attribute));
}
if return_code == ll::lfs_error_LFS_ERR_NOATTR {
return Ok(None);
}
io::result_from((), return_code)?;
// TODO: get rid of this
unreachable!();
}
/// Remove attribute.
pub fn remove_attribute(&self, path: &Path, id: u8) -> Result<()> {
let return_code =
unsafe { ll::lfs_removeattr(&mut self.alloc.borrow_mut().state, path.as_ptr(), id) };
io::result_from((), return_code)
}
/// Set attribute.
pub fn set_attribute(&self, path: &Path, attribute: &Attribute) -> Result<()> {
let return_code = unsafe {
ll::lfs_setattr(
&mut self.alloc.borrow_mut().state,
path.as_ptr(),
attribute.id,
&attribute.data as *const _ as *const cty::c_void,
attribute.size as u32,
)
};
io::result_from((), return_code)
}
/// C callback interface used by LittleFS to read data with the lower level system below the
/// filesystem.
extern "C" fn lfs_config_read(
c: *const ll::lfs_config,
block: ll::lfs_block_t,
off: ll::lfs_off_t,
buffer: *mut cty::c_void,
size: ll::lfs_size_t,
) -> cty::c_int {
// println!("in lfs_config_read for {} bytes", size);
let storage = unsafe { &mut *((*c).context as *mut Storage) };
debug_assert!(!c.is_null());
let block_size = unsafe { c.read().block_size };
let off = (block * block_size + off) as usize;
let buf: &mut [u8] = unsafe { slice::from_raw_parts_mut(buffer as *mut u8, size as usize) };
io::error_code_from(storage.read(off, buf))
}
/// C callback interface used by LittleFS to program data with the lower level system below the
/// filesystem.
extern "C" fn lfs_config_prog(
c: *const ll::lfs_config,
block: ll::lfs_block_t,
off: ll::lfs_off_t,
buffer: *const cty::c_void,
size: ll::lfs_size_t,
) -> cty::c_int {
// println!("in lfs_config_prog");
let storage = unsafe { &mut *((*c).context as *mut Storage) };
debug_assert!(!c.is_null());
// let block_size = unsafe { c.read().block_size };
let block_size = Storage::BLOCK_SIZE as u32;
let off = (block * block_size + off) as usize;
let buf: &[u8] = unsafe { slice::from_raw_parts(buffer as *const u8, size as usize) };
io::error_code_from(storage.write(off, buf))
}
/// C callback interface used by LittleFS to erase data with the lower level system below the
/// filesystem.
extern "C" fn lfs_config_erase(c: *const ll::lfs_config, block: ll::lfs_block_t) -> cty::c_int {
// println!("in lfs_config_erase");
let storage = unsafe { &mut *((*c).context as *mut Storage) };
let off = block as usize * Storage::BLOCK_SIZE;
io::error_code_from(storage.erase(off, Storage::BLOCK_SIZE))
}
/// C callback interface used by LittleFS to sync data with the lower level interface below the
/// filesystem. Note that this function currently does nothing.
extern "C" fn lfs_config_sync(_c: *const ll::lfs_config) -> i32 {
// println!("in lfs_config_sync");
// Do nothing; we presume that data is synchronized.
0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
/// Custom user attribute that can be set on files and directories.
///
/// Consists of an numerical identifier between 0 and 255, and arbitrary
/// binary data up to size `ATTRBYTES_MAX`.
///
/// Use [`Filesystem::attribute`](struct.Filesystem.html#method.attribute),
/// [`Filesystem::set_attribute`](struct.Filesystem.html#method.set_attribute), and
/// [`Filesystem::clear_attribute`](struct.Filesystem.html#method.clear_attribute).
pub struct Attribute {
id: u8,
data: Bytes<crate::consts::ATTRBYTES_MAX_TYPE>,
size: usize,
}
impl Attribute {
pub fn new(id: u8) -> Self {
Attribute {
id,
data: Default::default(),
size: 0,
}
}
pub fn id(&self) -> u8 {
self.id
}
pub fn data(&self) -> &[u8] {
let attr_max = crate::consts::ATTRBYTES_MAX as _;
let len = cmp::min(attr_max, self.size);
&self.data[..len]
}
pub fn set_data(&mut self, data: &[u8]) -> &mut Self {
let attr_max = crate::consts::ATTRBYTES_MAX as _;
let len = cmp::min(attr_max, data.len());
self.data[..len].copy_from_slice(&data[..len]);
self.size = len;
for entry in self.data[len..].iter_mut() {
*entry = 0;
}
self
}
}
bitflags! {
/// Definition of file open flags which can be mixed and matched as appropriate. These definitions
/// are reminiscent of the ones defined by POSIX.
struct FileOpenFlags: u32 {
/// Open file in read only mode.
const READ = 0x1;
/// Open file in write only mode.
const WRITE = 0x2;
/// Open file for reading and writing.
const READWRITE = Self::READ.bits | Self::WRITE.bits;
/// Create the file if it does not exist.
const CREATE = 0x0100;
/// Fail if creating a file that already exists.
/// TODO: Good name for this
const EXCL = 0x0200;
/// Truncate the file if it already exists.
const TRUNCATE = 0x0400;
/// Open the file in append only mode.
const APPEND = 0x0800;
}
}
/// The state of a `File`. Pre-allocate with `File::allocate`.
pub struct FileAllocation<S: driver::Storage> {
cache: Bytes<S::CACHE_SIZE>,
state: ll::lfs_file_t,
config: ll::lfs_file_config,
}
impl<S: driver::Storage> Default for FileAllocation<S> {
fn default() -> Self {
Self::new()
}
}
impl<S: driver::Storage> FileAllocation<S> {
pub fn new() -> Self {
let cache_size: u32 = <S as driver::Storage>::CACHE_SIZE::to_u32();
debug_assert!(cache_size > 0);
unsafe { mem::MaybeUninit::zeroed().assume_init() }
}
}
pub struct File<'a, 'b, S: driver::Storage> {
alloc: RefCell<&'b mut FileAllocation<S>>,
fs: &'b Filesystem<'a, S>,
}
impl<'a, 'b, Storage: driver::Storage> File<'a, 'b, Storage> {
pub fn allocate() -> FileAllocation<Storage> {
FileAllocation::new()
}
/// Returns a new OpenOptions object.
///
/// This function returns a new OpenOptions object that you can use to open or create a file
/// with specific options if open() or create() are not appropriate.
///
/// It is equivalent to OpenOptions::new() but allows you to write more readable code.
/// This also avoids the need to import OpenOptions`.
pub fn with_options() -> OpenOptions {
OpenOptions::new()
}
pub unsafe fn open(
fs: &'b Filesystem<'a, Storage>,
alloc: &'b mut FileAllocation<Storage>,
path: &Path,
) -> Result<Self> {
OpenOptions::new().read(true).open(fs, alloc, path)
}
pub fn open_and_then<R>(
fs: &Filesystem<'a, Storage>,
path: &Path,
f: impl FnOnce(&File<'_, '_, Storage>) -> Result<R>,
) -> Result<R> {
OpenOptions::new().read(true).open_and_then(fs, path, f)
}
pub unsafe fn create(
fs: &'b Filesystem<'a, Storage>,
alloc: &'b mut FileAllocation<Storage>,
path: &Path,
) -> Result<Self> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(fs, alloc, path)
}
pub fn create_and_then<R>(
fs: &Filesystem<'a, Storage>,
path: &Path,
f: impl FnOnce(&File<'_, '_, Storage>) -> Result<R>,
) -> Result<R> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open_and_then(fs, path, f)
}
// Safety-hatch to experiment with missing parts of API
pub unsafe fn borrow_filesystem<'c>(&'c mut self) -> &'c Filesystem<'a, Storage> {
self.fs
}
/// Sync the file and drop it from the internal linked list.
/// Not doing this is UB, which is why we have all the closure-based APIs.
///
/// TODO: check if this can be closed >1 times, if so make it safe
///
/// Update: It seems like there's an assertion on a flag called `LFS_F_OPENED`:
/// https://github.com/ARMmbed/littlefs/blob/4c9146ea539f72749d6cc3ea076372a81b12cb11/lfs.c#L2549
/// https://github.com/ARMmbed/littlefs/blob/4c9146ea539f72749d6cc3ea076372a81b12cb11/lfs.c#L2566
///
/// - On second call, shouldn't find ourselves in the "mlist of mdirs"
/// - Since we don't have dynamically allocated buffers, at least we don't hit the double-free.
/// - Not sure what happens in `lfs_file_sync`, but it should be easy to just error on
/// not LFS_F_OPENED...
pub unsafe fn close(self) -> Result<()> {
let return_code = ll::lfs_file_close(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
);
io::result_from((), return_code)
}
/// Synchronize file contents to storage.
pub fn sync(&self) -> Result<()> {
let return_code = unsafe {
ll::lfs_file_sync(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
)
};
io::result_from((), return_code)
}
/// Size of the file in bytes.
pub fn len(&self) -> Result<usize> {
let return_code = unsafe {
ll::lfs_file_size(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
)
};
io::result_from(return_code as usize, return_code)
}
/// Truncates or extends the underlying file, updating the size of this file to become size.
///
/// If the size is less than the current file's size, then the file will be shrunk. If it is
/// greater than the current file's size, then the file will be extended to size and have all
/// of the intermediate data filled in with 0s.
pub fn set_len(&self, size: usize) -> Result<()> {
let return_code = unsafe {
ll::lfs_file_truncate(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
size as u32,
)
};
io::result_from((), return_code)
}
// This belongs in `io::Read` but really don't want that to have a generic parameter
pub fn read_to_end<const N: usize>(&self, buf: &mut heapless::Vec<u8, N>) -> Result<usize> {
// My understanding of
// https://github.com/ARMmbed/littlefs/blob/4c9146ea539f72749d6cc3ea076372a81b12cb11/lfs.c#L2816
// is that littlefs keeps reading until either the buffer is full, or the file is exhausted
let had = buf.len();
// no panic by construction
buf.resize_default(buf.capacity()).unwrap();
// use io::Read;
let read = self.read(&mut buf[had..])?;
// no panic by construction
buf.resize_default(had + read).unwrap();
Ok(read)
}
pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
<Self as io::Read>::read(self, buf)
}
pub fn seek(&self, pos: io::SeekFrom) -> Result<usize> {
<Self as io::Seek>::seek(self, pos)
}
pub fn write(&self, buf: &[u8]) -> Result<usize> {
<Self as io::Write>::write(self, buf)
}
}
/// Options and flags which can be used to configure how a file is opened.
///
/// This builder exposes the ability to configure how a File is opened and what operations
/// are permitted on the open file. The File::open and File::create methods are aliases
/// for commonly used options using this builder.
///
/// Consider `File::with_options()` to avoid having to `use` OpenOptions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OpenOptions(FileOpenFlags);
impl Default for OpenOptions {
fn default() -> Self {
Self::new()
}
}
impl OpenOptions {
/// Open the file with the options previously specified, keeping references.
///
/// unsafe since UB can arise if files are not closed (see below).
///
/// The alternative method `open_and_then` is suggested.
///
/// Note that:
/// - files *must* be closed before going out of scope (they are stored in a linked list),
/// closing removes them from there
/// - since littlefs is supposed to be *fail-safe*, we can't just close files in
/// Drop and panic if something went wrong.
pub unsafe fn open<'a, 'b, S: driver::Storage>(
&self,
fs: &'b Filesystem<'a, S>,
alloc: &'b mut FileAllocation<S>,
path: &Path,
) -> Result<File<'a, 'b, S>> {
alloc.config.buffer = &mut alloc.cache as *mut _ as *mut cty::c_void;
let return_code = ll::lfs_file_opencfg(
&mut fs.alloc.borrow_mut().state,
&mut alloc.state,
path.as_ptr(),
self.0.bits() as i32,
&alloc.config,
);
let file = File {
alloc: RefCell::new(alloc),
fs,
};
io::result_from(file, return_code)
}
/// (Hopefully) safe abstraction around `open`.
pub fn open_and_then<'a, R, S: driver::Storage>(
&self,
fs: &Filesystem<'a, S>,
path: &Path,
f: impl FnOnce(&File<'a, '_, S>) -> Result<R>,
) -> Result<R> {
let mut alloc = FileAllocation::new(); // lifetime 'c
let mut file = unsafe { self.open(fs, &mut alloc, path)? };
// Q: what is the actually correct behaviour?
// E.g. if res is Ok but closing gives an error.
// Or if closing fails because something is broken and
// we'd already know that from an Err res.
let res = f(&mut file);
unsafe { file.close()? };
res
}
pub fn new() -> Self {
OpenOptions(FileOpenFlags::empty())
}
pub fn read(&mut self, read: bool) -> &mut Self {
if read {
self.0.insert(FileOpenFlags::READ)
} else {
self.0.remove(FileOpenFlags::READ)
};
self
}
pub fn write(&mut self, write: bool) -> &mut Self {
if write {
self.0.insert(FileOpenFlags::WRITE)
} else {
self.0.remove(FileOpenFlags::WRITE)
};
self
}
pub fn append(&mut self, append: bool) -> &mut Self {
if append {
self.0.insert(FileOpenFlags::APPEND)
} else {
self.0.remove(FileOpenFlags::APPEND)
};
self
}
pub fn create(&mut self, create: bool) -> &mut Self {
if create {
self.0.insert(FileOpenFlags::CREATE)
} else {
self.0.remove(FileOpenFlags::CREATE)
};
self
}
pub fn create_new(&mut self, create_new: bool) -> &mut Self {
if create_new {
self.0.insert(FileOpenFlags::EXCL);
self.0.insert(FileOpenFlags::CREATE);
} else {
self.0.remove(FileOpenFlags::EXCL);
self.0.remove(FileOpenFlags::CREATE);
};
self
}
pub fn truncate(&mut self, truncate: bool) -> &mut Self {
if truncate {
self.0.insert(FileOpenFlags::TRUNCATE)
} else {
self.0.remove(FileOpenFlags::TRUNCATE)
};
self
}
}
impl<S: driver::Storage> io::Read for File<'_, '_, S> {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
let return_code = unsafe {
ll::lfs_file_read(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
buf.as_mut_ptr() as *mut cty::c_void,
buf.len() as u32,
)
};
io::result_from(return_code as usize, return_code)
}
}
impl<S: driver::Storage> io::Seek for File<'_, '_, S> {
fn seek(&self, pos: io::SeekFrom) -> Result<usize> {
let return_code = unsafe {
ll::lfs_file_seek(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
pos.off(),
pos.whence(),
)
};
io::result_from(return_code as usize, return_code)
}
}
impl<S: driver::Storage> io::Write for File<'_, '_, S> {
fn write(&self, buf: &[u8]) -> Result<usize> {
let return_code = unsafe {
ll::lfs_file_write(
&mut self.fs.alloc.borrow_mut().state,
&mut self.alloc.borrow_mut().state,
buf.as_ptr() as *const cty::c_void,
buf.len() as u32,
)
};
io::result_from(return_code as usize, return_code)
}
fn flush(&self) -> Result<()> {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirEntry {
file_name: PathBuf,
metadata: Metadata,
#[cfg(feature = "dir-entry-path")]
path: PathBuf,
}
impl DirEntry {
// // Returns the full path to the file that this entry represents.
// pub fn path(&self) -> Path {}
// Returns the metadata for the file that this entry points at.
pub fn metadata(&self) -> Metadata {
self.metadata.clone()
}
// Returns the file type for the file that this entry points at.
pub fn file_type(&self) -> FileType {
self.metadata.file_type
}
// Returns the bare file name of this directory entry without any other leading path component.
pub fn file_name(&self) -> &Path {
&self.file_name
}
/// Returns the full path to the file that this entry represents.
///
/// The full path is created by joining the original path to read_dir with the filename of this entry.
#[cfg(feature = "dir-entry-path")]
pub fn path(&self) -> &Path {
&self.path
}
#[cfg(feature = "dir-entry-path")]
#[doc(hidden)]
// This is used in `crypto-service` to "namespace" paths
// by mutating a DirEntry in-place.
pub unsafe fn path_buf_mut(&mut self) -> &mut PathBuf {
&mut self.path
}
}
pub struct ReadDirAllocation {
state: ll::lfs_dir_t,
}
impl Default for ReadDirAllocation {
fn default() -> Self {
Self::new()
}
}
impl ReadDirAllocation {
pub fn new() -> Self {
unsafe { mem::MaybeUninit::zeroed().assume_init() }