Skip to main content

cranpose_services/
storage.rs

1//! Free space on the device, so an application can tell the person before a
2//! large download or save that it will not fit.
3
4use std::{path::Path, sync::Arc};
5
6use crate::registry::ServiceRegistry;
7
8/// Reports the free space a platform measures its own way.
9pub trait StorageSpace: Send + Sync {
10    /// The bytes the application can still write on the volume that holds
11    /// `path`, or `None` where the platform cannot tell.
12    fn available(&self, path: &Path) -> Option<u64>;
13}
14
15pub type StorageSpaceRef = Arc<dyn StorageSpace>;
16
17static PLATFORM_STORAGE_SPACE: ServiceRegistry<dyn StorageSpace> = ServiceRegistry::new();
18
19/// Installs the platform's measure of free space. iOS installs one that counts
20/// the space the system frees on demand for important data.
21// forwards on purpose: the registry is private to this crate, and this is the
22// one way a platform backend installs into it.
23pub fn set_platform_storage_space(space: StorageSpaceRef) {
24    PLATFORM_STORAGE_SPACE.set(space);
25}
26
27/// The bytes the application can still write on the volume that holds `path`,
28/// or `None` where the platform cannot tell. `path` need not exist yet: the
29/// nearest folder above it that does is measured.
30pub fn available_storage(path: &Path) -> Option<u64> {
31    let existing = path.ancestors().find(|folder| folder.exists())?;
32    match PLATFORM_STORAGE_SPACE.get() {
33        Some(platform) => platform.available(existing),
34        None => file_system_available(existing),
35    }
36}
37
38#[cfg(unix)]
39fn file_system_available(path: &Path) -> Option<u64> {
40    let stat = rustix::fs::statvfs(path).ok()?;
41    Some(stat.f_bavail.saturating_mul(stat.f_frsize))
42}
43
44#[cfg(not(unix))]
45fn file_system_available(_path: &Path) -> Option<u64> {
46    None
47}
48
49#[cfg(test)]
50#[path = "tests/storage_tests.rs"]
51mod tests;