cache_dir/lib.rs
1//! 跨平台获取缓存目录的函数
2
3#[cfg(target_os = "android")]
4mod android;
5#[cfg(target_os = "ios")]
6mod ios;
7#[cfg(not(any(target_os = "android", target_os = "ios")))]
8mod other;
9
10#[cfg(target_os = "android")]
11use android::{cache_dir, data_dir};
12#[cfg(target_os = "ios")]
13use ios::{cache_dir, data_dir};
14#[cfg(not(any(target_os = "android", target_os = "ios")))]
15use other::{cache_dir, data_dir};
16
17use std::{
18 error::Error,
19 fmt::{Display, Formatter, Result as FmtResult},
20 path::PathBuf,
21};
22
23/// 自定义错误类型,表示在当前平台上找不到缓存目录的情况
24#[derive(Debug)]
25pub struct NoSuchDirectoryError;
26
27impl Display for NoSuchDirectoryError {
28 /// 格式化错误信息
29 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
30 write!(f, "Can't find the cache directory on current platform.")
31 }
32}
33
34impl Error for NoSuchDirectoryError {}
35
36/// 获取缓存目录的函数。
37/// 缓存目录是一种非常不可控的目录类型,目录中的文件什么时候会被删除完全取决于操作系统,特别是在移动设备上,如果您的APP使用了较多的空间,当用户在使用其他APP时,可能优先删除您APP中的数据,在这种情况下可以改用[get_data_dir]来代替。
38/// 在Windows上,此函数获取的是`%LOCALAPPDATA%\Temp`,其他平台取决于操作系统或者[dirs::data_local_dir]的实现;
39///
40/// 尝试获取当前平台的缓存目录。如果成功,返回一个包含目录路径的`Ok`值;如果失败,返回一个`Err`值,其中包含[NoSuchDirectoryError]错误。
41/// 平台包括: Windows, Linux, MacOS, Android, iOS, WASM等。
42///
43/// # 返回值
44///
45/// - `Result<PathBuf, NoSuchDirectoryError>`: 成功时返回缓存目录的路径,失败时返回错误信息。
46///
47/// # 示例
48///
49/// ```rust
50/// use cache_dir::get_cache_dir;
51///
52/// match get_cache_dir() {
53/// Ok(cache_dir) => println!("Cache directory: {:?}", cache_dir),
54/// Err(e) => eprintln!("Error: {}", e),
55/// }
56/// ```
57pub fn get_cache_dir() -> Result<PathBuf, NoSuchDirectoryError> {
58 cache_dir().map_or(Err(NoSuchDirectoryError), Ok)
59}
60
61/// 获取数据目录的函数。
62/// 数据目录是一种可靠的存储目录,可随时读写文件且无需申请权限,与[get_cache_dir]的区别是,此函数获取的数据目录更加持久。
63/// 在安卓平台此目录是APP私有目录中的`files`,Windows上是`%LOCALAPPDATA%`,其他平台取决于操作系统或者[dirs::data_local_dir]的实现;
64///
65/// 尝试获取当前平台的可写的数据目录。如果成功,返回一个包含目录路径的`Ok`值;如果失败,返回一个`Err`值,其中包含[NoSuchDirectoryError]错误。
66/// 平台包括: Windows, Linux, MacOS, Android, iOS, WASM等。
67///
68/// # 返回值
69///
70/// - `Result<PathBuf, NoSuchDirectoryError>`: 成功时返回数据目录的路径,失败时返回错误信息。
71///
72/// # 示例
73///
74/// ```rust
75/// use cache_dir::get_data_dir;
76///
77/// match get_data_dir() {
78/// Ok(data_dir) => println!("Writable data directory: {:?}", data_dir),
79/// Err(e) => eprintln!("Error: {}", e),
80/// }
81/// ```
82pub fn get_data_dir() -> Result<PathBuf, NoSuchDirectoryError> {
83 data_dir().map_or(Err(NoSuchDirectoryError), Ok)
84}