Cotton code
99 lines · 4.0 KB · RustRaw
//! The DISK seam — what this device's own storage is doing.//!//! `read.storage` is the one read whose answer is not in the database at all://! it is about the phone. So it is written against a trait rather than against//! `std::fs`, for the reason every other seam in this tree exists — a test that//! has to create three gigabytes of real files to check a number is a test//! nobody runs.//!//! ## Why `free_bytes` can answer nothing, and why that is not a fallback//!//! There is no free-space call in Rust's standard library, and this lane adds//! no platform crate to get one. That is the smaller half of the reason. The//! larger half is that on iOS the number people mean is//! `volumeAvailableCapacityForImportantUsageKey` — what the system will//! actually let an app have, after purgeable caches — and a `statvfs` answer is//! a DIFFERENT, larger number that would tell the person they have room they do//! not have.//!//! So [`SystemDisk`] answers `None`, the read says `freeBytes: null` WITH the//! reason beside it, and the seam is here for 4b's Swift half to fill with the//! number iOS actually enforces. A silent zero, or a `statvfs` figure dressed//! up as the same thing, is exactly the masked fallback this repo does not//! allow.use std::path::Path;/// What this device's storage is doing, asked rather than measured inline.pub trait Disk: Send + Sync + std::fmt::Debug {    /// One file's allocated contents; absent is zero, unreadable is unknown.    fn file_size(&self, _path: &Path) -> Option<u64> { None }    /// Every byte under one directory, walked. `0` for a directory that is not    /// there — a store nothing has written to yet occupies nothing, which is a    /// fact rather than an error.    fn size_of(&self, path: &Path) -> u64;    /// How much room is left on the volume that holds this path, when the    /// platform has told us. See the module note for why the default is `None`.    fn free_bytes(&self, path: &Path) -> Option<u64>;}/// The real disk: a walk for the sizes, and nothing for the free space.#[derive(Debug, Clone, Copy, Default)]pub struct SystemDisk;/// What [`SystemDisk::free_bytes`] says instead of a number.pub const NO_FREE_SPACE_READING: &str =    "how much room is left is a question this core cannot ask: the number iOS enforces is \     volumeAvailableCapacityForImportantUsage, which only the app side can read.";impl Disk for SystemDisk {    fn file_size(&self, path: &Path) -> Option<u64> {        match std::fs::metadata(path) {            Ok(metadata) if metadata.is_file() => Some(metadata.len()),            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(0),            _ => None,        }    }    fn size_of(&self, path: &Path) -> u64 {        walk(path)    }    fn free_bytes(&self, _path: &Path) -> Option<u64> {        None    }}/// Bytes under one directory.////// Iterative rather than recursive, and it never follows a symlink: a media/// store is thousands of files deep in two levels, and a link out of it would/// let a walk wander into the rest of the filesystem — or into itself./// Unreadable entries are skipped rather than failing the whole answer, because/// a settings screen that says nothing because one file was busy is worse than/// one that is a few kilobytes light.fn walk(root: &Path) -> u64 {    let mut total = 0u64;    let mut pending = vec![root.to_path_buf()];    while let Some(directory) = pending.pop() {        let Ok(entries) = std::fs::read_dir(&directory) else {            continue;        };        for entry in entries.flatten() {            let Ok(kind) = entry.file_type() else {                continue;            };            if kind.is_symlink() {                continue;            }            if kind.is_dir() {                pending.push(entry.path());            } else if let Ok(meta) = entry.metadata() {                total = total.saturating_add(meta.len());            }        }    }    total}