Skip to main content

FileSystem

Struct FileSystem 

Source
pub struct FileSystem<D: BlockDevice> { /* private fields */ }
Expand description

A mounted FAT32 volume.

Owns its block device. Methods take &mut self and there is no interior mutability: a consumer that needs to share a volume picks its own strategy — a mutex, a worker on another core, or sole ownership — rather than paying for one this crate guessed at.

Implementations§

Source§

impl<D: BlockDevice> FileSystem<D>

Source

pub fn open(&mut self, path: &str) -> Result<File, D::Error>

Opens the file at path.

/-separated, matching either long or short names, case insensitively — the same resolution open_dir does.

Source

pub fn read_all(&mut self, file: &File) -> Result<Vec<u8>, D::Error>

Reads the whole file.

Exactly File::len bytes — the slack in the last cluster is not part of the file and does not come back. One device transfer per run of the file’s chain, so a contiguous file of any size is one call.

The whole file is buffered, and FAT32 allows one of nearly 4 GiB, so this reports Error::OutOfMemory rather than aborting when the host cannot hold it. read_at is the way to take a large file in pieces the caller sizes.

Source

pub fn read_at( &mut self, file: &File, offset: u64, into: &mut [u8], ) -> Result<usize, D::Error>

Reads from offset into into, returning how many bytes arrived.

Short only at the end of the file: a read starting at or past File::len returns zero, and one that would run past the end stops there. Anything else short would be a device error instead.

Source§

impl<D: BlockDevice> FileSystem<D>

Source

pub fn create(&mut self, path: &str) -> Result<File, D::Error>

Creates an empty file at path.

Source

pub fn create_with_size( &mut self, path: &str, size: u32, ) -> Result<File, D::Error>

Creates a file at path with room for size bytes already allocated.

The size is a hint about the whole file, and it is what makes the result contiguous: the allocator is asked for every cluster at once and will find a single run if the volume has one, so the file can afterwards be written — and read — in a single device transfer. A file grown a write at a time gets whatever the allocator had spare each time, which is how files become fragmented.

§size reserves space; it does not set the length

The file comes back empty, and its length grows as write_at fills the space in. The reservation is real — the clusters are allocated and chained, so the contiguity is already decided — but no length is recorded over bytes nothing has written yet.

That is deliberate, and it is the difference between reserving space and lying about it. Recording size here would make the file readable at its full length before a byte of it existed, and what came back would be whatever the last file to own those clusters left behind. FAT does not erase a chain when it frees one, so those bytes are another file’s data, handed to a caller that never opened it.

Zeroing the clusters instead would fix the disclosure and cost the write twice over — once with zeros and once with the data — which is most of what this crate exists to avoid. So the length follows the data rather than leading it.

A file reserved and then never written stays zero length while holding its clusters, until it is written or removed. fsck.vfat describes that state as a file whose size does not account for its chain and offers to truncate it to zero, which releases the reservation and is the right repair — wasted space, and nothing worse. Keeping the reservation attached to a named file is what makes it visible and removable at all; a reservation held off the directory entry would leak silently the moment the caller lost interest.

§Ordering

The clusters are allocated and chained before the directory entry naming them is written. Interrupted between the two, the volume has clusters belonging to nothing — a leak, which fsck reclaims. The other order would publish a directory entry pointing at clusters the allocator still believes are free, which is how two files come to share data.

Source

pub fn create_dir(&mut self, path: &str) -> Result<u32, D::Error>

Creates a directory at path, returning its first cluster.

The parent must exist; this makes one directory, not a chain of them.

§Ordering

The new directory’s cluster is allocated, filled in with its . and .. entries, and linked into the table on the device — all before the parent gains an entry naming it. Interrupted at any point, the result is a leaked cluster holding a directory nothing points at. The other order would publish a directory entry whose cluster still held whatever the last file to own it left behind, and stale bytes in a directory read as entries.

Source

pub fn remove_dir(&mut self, path: &str) -> Result<(), D::Error>

Removes the empty directory at path.

Refuses a directory that still holds anything. Removing one would leave its contents allocated and unreachable — space no fsck run reclaims, because the clusters really are referenced, by entries nothing can find any more.

Source

pub fn write_at( &mut self, file: &mut File, offset: u64, data: &[u8], ) -> Result<(), D::Error>

Writes data at offset, growing the file if it needs to.

The file’s recorded length is updated when the write extends it. file is updated to match, so it stays usable afterwards.

§Writing past the end

A write starting beyond File::len leaves a gap, and the gap is filled with zeros before the new length publishes it. The clusters under it hold whatever the last file to own them left behind — FAT frees a chain without erasing it — so the alternative is handing a caller another file’s data under a length this crate wrote. The zeroing costs one pass over the gap, and only a caller that actually skips ahead pays it.

Source

pub fn write_file(&mut self, path: &str, data: &[u8]) -> Result<File, D::Error>

Creates path holding exactly data, replacing anything there.

The shape most callers want, and the one that produces a contiguous file: the length is known before a byte is written, so the whole chain is allocated at once.

Source

pub fn truncate(&mut self, file: &mut File, size: u32) -> Result<(), D::Error>

Sets the file’s length, freeing or allocating clusters to match.

Growing zeroes what it adds, the way every filesystem a caller has met does: the clusters it reaches into hold whatever the last file to own them left behind, and a length is a promise about content. See write_at on writing past the end, which is the same gap by another route.

§Ordering

Shrinking writes the new length to the directory entry first, and frees the tail of the chain afterwards. Interrupted between the two, the volume has clusters nothing refers to — a leak. The other order leaves a directory entry claiming clusters the allocator has already handed to someone else, and two files sharing data is a worse outcome than some space going unused until fsck runs.

Source

pub fn remove(&mut self, path: &str) -> Result<(), D::Error>

Deletes the file at path.

The entry is marked deleted before the chain is freed, for the same reason truncation shrinks first. A long name’s slots go with it: leaving them behind would produce the orphaned long-name parts fsck.vfat reports, occupying directory space nothing could reuse.

Source

pub fn rename(&mut self, from: &str, to: &str) -> Result<(), D::Error>

Renames or moves the file or directory at from to to, replacing a file already at to.

Nothing is copied: the data stays in its clusters, and only directory entries change. Both paths are /-separated and resolve the way open does. A name differing from the old one only in case is a rename; an identical one does nothing.

Handles to from are stale afterwards, as are handles to a file it replaced — see File on staleness.

FAT has no atomic rename, so what an interruption leaves behind is decided by the order of the writes, and the three cases below differ.

§Replacing a file, and why that is the useful case

The one way to change a file that an interruption cannot leave half-written is to write the new contents under another name and rename it over the old: settings.new → settings.toml. This makes that work: to always names a whole file, the old one or the new one, and never nothing and never part of one.

from’s entry is deleted first, then to’s entry is repointed at from’s data — first cluster, size, attributes and timestamps — in one write of one sector, and only then is to’s old data freed. Interrupted before the repoint, to is the old file and the new data is allocated to nothing: the save did not happen, and fsck reclaims the space. Interrupted after it, to is the new file and the old data is what leaks. No cluster ever belongs to two names — repointing first would have to and from sharing one chain until from was deleted.

Only a file replaces a file. A directory at to, or a directory at from with anything at to, is Error::AlreadyExists.

§A new name in the same directory

When the new name takes no more directory slots than the old one, the entry is rewritten where it stands: the new long-name slots and the 8.3 entry, in ascending order, over the old ones, and any the shorter name no longer needs deleted afterwards. An interruption can leave long-name slots whose checksum does not match the 8.3 entry after them, which every reader ignores — so the file is found under its old or its new name, or at worst under its 8.3 alias, and is never lost or shared.

§Anything else

A move to another directory, or a name longer than the slots it has: the new entries are written first, then the old ones deleted. This is the one case with no ordering free of a window. Interrupted between the two, the file has both names — two entries sharing one chain, which fsck.vfat reports and repairs by dropping one. The other order would leave the data named by nothing, which fsck reclaims as lost; sharing loses nothing, so it is the lesser.

A directory moved to another parent has its .. pointed at the new one, between the two steps. Moving a directory inside itself or anything it contains is Error::MoveIntoItself.

Source§

impl<D: BlockDevice> FileSystem<D>

Source

pub fn mount(device: D) -> Result<Self, D::Error>

Mounts the volume that begins at block 0 of device.

Right for a device formatted as one volume, which is what a card written by mkfs.vfat onto a raw device is.

A card with a partition table — anything an imaging tool wrote — needs one of the other two ways in: mount_partition, behind the mbr feature, which finds the volume itself; or mount_at with a block number the caller already knows.

(mount_partition is named rather than linked because a link to it does not resolve when the mbr feature is off, which would make cargo doc warn in every build that does not enable it.)

Source

pub fn mount_at(device: D, first_block: u64) -> Result<Self, D::Error>

Mounts the volume that begins at first_block.

Every block number the volume uses is relative to this, so a partitioned card works by passing the partition’s first block.

Source

pub fn mount_with( device: D, first_block: u64, codepage: Codepage, ) -> Result<Self, D::Error>

Mounts with a codepage for the volume’s 8.3 names.

Only worth supplying for a card whose short names really are not ASCII — see crate::codepage. It changes how a name is rendered and which characters can be stored in an alias; it does not change the bytes on the volume, and it does not affect long names, which are UCS-2 and need no codepage at all.

Set here and not afterwards, and read back with codepage. There is no setter on purpose: the 8.3 name a directory was parsed under is the key it is cached by, so changing the codepage under a mounted volume would leave entries findable only by the name they were read as. Mount again to change it.

Source

pub fn codepage(&self) -> &Codepage

The codepage 8.3 names are read and written through.

Source

pub fn set_clock(&mut self, clock: Box<dyn Clock>)

Supplies the clock new entries are stamped from.

Optional. Without one, everything written carries the FAT epoch, which is a real date and is the right answer for a board that does not know the time — see crate::time::Clock for why that is the default rather than a failure.

Affects only what is written afterwards. Entries already on the volume keep the timestamps they were given, and this does not go back and correct them: a device that learns the time from the network halfway through its life has files from both eras, and inventing a timestamp for the older ones would be worse than leaving them honest.

Source

pub fn mount_partition(device: D, index: usize) -> Result<Self, D::Error>

Available on crate feature mbr only.

Mounts the volume in partition-table slot index.

The third of the three ways in, and the one for a card written by an imaging tool: it reads the master boot record and mounts the partition that slot describes. index is the raw table slot, 0 to 3, rather than a count of the partitions in use — a card whose volume sits in slot 1 with slot 0 empty is a real arrangement, and numbering by use would silently mount the wrong one.

crate::mbr::PartitionTable is public for the cases this does not cover: finding the FAT partition when its slot is not known, or handling a device that might have no table at all.

The volume is held to the partition’s length as well as the device’s, so a boot sector claiming more sectors than the partition it sits in is refused here even on a device that cannot report its own size.

§Errors

Error::NoPartitionTable when block 0 is not a partition table — including when it is a boot sector, which is the shape mount handles. Error::NoSuchPartition when the slot is empty or out of range.

Source

pub fn mount_first_fat(device: D) -> Result<Self, D::Error>

Available on crate feature mbr only.

Mounts the device’s FAT volume, whichever way it was formatted.

For a card whose layout is not known in advance, which is most of them. With a partition table, this mounts the first partition whose type byte says FAT — by type rather than by slot, because imaging tools usually put the volume in slot 0 but not always, and a card with a separate data partition has more than one entry. Like mount_partition, the volume is held to that partition’s length. With no table, the device is one bare volume, as some tools format a small card, and this is mount.

Telling the two apart is the part worth not writing by hand: a boot sector and a partition table end with the same 0x55AA, so the obvious check answers yes to either — see crate::mbr::PartitionTable::read.

§Errors

Error::NoFatPartition when there is a table and nothing in it is FAT. Error::NoPartitionTable for the placeholder table a GPT disk carries, which this declines as mount_partition does. Otherwise whatever mounting the volume found.

Source

pub fn first_block(&self) -> u64

The device block the volume begins at: 0 for a bare volume, the partition’s first block for one mounted through a table.

For a board’s console line about what it mounted, which is where a card imaged differently from the last one first shows.

Source

pub fn boot_sector(&self) -> &BootSector

The volume’s validated geometry.

Source

pub fn fs_info(&self) -> &FsInfo

The volume’s free-space hints, such as they are.

Source

pub fn fat(&self) -> &Fat

The resident allocation table.

Source

pub fn is_dirty(&self) -> bool

Whether the volume was already marked dirty when this mount found it.

True means the last writer did not finish: either it never synced, or it lost power partway through. It says nothing about what is wrong, only that something might be — under this crate’s write ordering the likely damage is leaked clusters, which cost space and nothing else, but the volume may equally have been written by something with weaker ordering.

This reports what was on the volume at mount, and does not change when this mount sets the flag for its own writes.

Source

pub fn runs(&self, cluster: u32) -> Result<Vec<Run>, D::Error>

The runs the chain starting at cluster occupies.

Reported through this volume’s error type rather than the table’s, so a caller mixing it with reads and writes has one type to handle. Ask fat directly for the narrower FatError.

Source

pub fn read_run(&mut self, run: &Run, into: &mut [u8]) -> Result<(), D::Error>

Reads a run’s clusters into into, in one device transfer.

into must be exactly the run’s length in bytes; anything else is Error::BufferLength. One call per run is the property everything else is arranged to make possible, so this deliberately offers no way to read a run piecemeal.

Both ends of the run are checked against the volume, not just the first. Run’s fields are public, so a run a caller assembled — as opposed to one runs returned — can start inside the volume and end outside it, and the transfer would then continue off the end of the data area into whatever follows it. On a partitioned card that is another filesystem.

Source

pub fn read_chain(&mut self, cluster: u32) -> Result<Vec<u8>, D::Error>

Reads the whole chain beginning at cluster, one transfer per run.

Returns every byte of every cluster, so the caller truncates to the file’s recorded size — the chain knows how much space a file occupies, not how much of it is meaningful.

The buffer is as large as the chain, and the chain’s length comes off the volume, so this reports Error::OutOfMemory rather than aborting when it will not fit — see that variant. A corrupt chain can be as long as the volume has clusters.

Source

pub fn root_cluster(&self) -> u32

The first cluster of the root directory.

Source

pub fn read_dir(&mut self, cluster: u32) -> Result<&Directory, D::Error>

The directory whose chain begins at cluster, reading and parsing it if this is the first time it has been asked for.

One transfer per run of the directory’s chain on the first call, and no device traffic at all afterwards. That second property is what makes opening several files in one directory cheap, and it is the thing a per-block implementation cannot offer however good its caching is.

Source

pub fn root_dir(&mut self) -> Result<&Directory, D::Error>

The root directory.

Source

pub fn open_dir(&mut self, path: &str) -> Result<&Directory, D::Error>

The directory at path, which is /-separated and may name either long or short names.

A leading slash is optional and . components are skipped, so /ROMS, ROMS and ./ROMS are the same directory.

Source

pub fn forget_directories(&mut self)

Forgets every parsed directory.

Only needed if something outside this crate has written to the volume underneath it, which is not a supported arrangement — but the alternative to offering this is a caller with a stale cache and no way to say so.

Source

pub fn sync(&mut self) -> Result<(), D::Error>

Writes every change made since the last sync to the device.

Each dirty stretch of the allocation table is written once per copy the volume carries, and the free-space hints are refreshed. Until this is called, allocations and truncations exist only in memory.

Directory entries are not deferred — see the ordering notes on create_with_size and truncate. They go to the device when they are written, because their order relative to table changes is what decides what a power cut leaves behind.

§The dirty flag

Finishing clears the volume’s dirty flag, so a volume synced before being put away mounts clean and one dropped without a sync does not. That flag is the only way an unclean shutdown is detectable at all; nothing else on the volume records that a writer was interrupted.

Only the flag this mount set is cleared. A volume that arrived dirty and was never written to keeps its warning: this crate has not repaired anything, and clearing a flag it did not set would throw away the one signal that something needs looking at.

A sync with nothing to write does nothing at all, so calling it more often than necessary costs nothing.

Source

pub fn unmount(self) -> Result<D, D::Error>

Syncs, and gives the block device back.

The tidy way to finish with a volume. FileSystem cannot do this when it is dropped, because writing to a device can fail and a drop has nowhere to report that to — so an unsynced volume that is simply dropped stays marked dirty, which is the correct outcome rather than a silent one.

Source

pub fn device(&self) -> &D

The block device this volume sits on.

Source

pub fn device_mut(&mut self) -> &mut D

The block device, mutably.

Reaching past the filesystem to its device is a way to corrupt a mounted volume, so this exists for devices that carry their own state worth reaching — an instrumented one that counts transfers, say — rather than for writing blocks behind the filesystem’s back.

Source

pub fn into_device(self) -> D

Gives the block device back.

Trait Implementations§

Source§

impl<D: BlockDevice + Debug> Debug for FileSystem<D>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Written out rather than derived, because a clock is a trait object and requiring every implementation of Clock to be Debug would be a tax on implementors for the sake of one line of output. The parsed directories are summarised rather than printed: a volume that has walked a ROM directory would otherwise put three hundred entries into the first panic message that mentions it.

Auto Trait Implementations§

§

impl<D> !RefUnwindSafe for FileSystem<D>

§

impl<D> !Send for FileSystem<D>

§

impl<D> !Sync for FileSystem<D>

§

impl<D> !UnwindSafe for FileSystem<D>

§

impl<D> Freeze for FileSystem<D>
where D: Freeze,

§

impl<D> Unpin for FileSystem<D>
where D: Unpin,

§

impl<D> UnsafeUnpin for FileSystem<D>
where D: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.