cranpose_services/
storage.rs1use std::{path::Path, sync::Arc};
5
6use crate::registry::ServiceRegistry;
7
8pub trait StorageSpace: Send + Sync {
10 fn available(&self, path: &Path) -> Option<u64>;
13}
14
15pub type StorageSpaceRef = Arc<dyn StorageSpace>;
17
18static PLATFORM_STORAGE_SPACE: ServiceRegistry<dyn StorageSpace> = ServiceRegistry::new();
19
20pub fn set_platform_storage_space(space: StorageSpaceRef) {
25 PLATFORM_STORAGE_SPACE.set(space);
26}
27
28pub fn available_storage(path: &Path) -> Option<u64> {
32 let existing = path.ancestors().find(|folder| folder.exists())?;
33 match PLATFORM_STORAGE_SPACE.get() {
34 Some(platform) => platform.available(existing),
35 None => file_system_available(existing),
36 }
37}
38
39#[cfg(unix)]
40fn file_system_available(path: &Path) -> Option<u64> {
41 let stat = rustix::fs::statvfs(path).ok()?;
42 Some(stat.f_bavail.saturating_mul(stat.f_frsize))
43}
44
45#[cfg(not(unix))]
46fn file_system_available(_path: &Path) -> Option<u64> {
47 None
48}
49
50#[cfg(test)]
51#[path = "tests/storage_tests.rs"]
52mod tests;