1use std::path::PathBuf;
8
9pub use nsh_core::ByteSize;
10
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct CacheOptions {
16 pub location: CacheLocation,
18 pub images: CachePolicy,
21}
22
23impl CacheOptions {
24 pub fn at(location: CacheLocation) -> Self {
26 Self {
27 location,
28 ..Self::default()
29 }
30 }
31
32 pub fn off() -> Self {
34 Self::at(CacheLocation::Off)
35 }
36
37 #[must_use]
39 pub fn with_images(mut self, images: CachePolicy) -> Self {
40 self.images = images;
41 self
42 }
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum CacheLocation {
49 #[default]
54 System,
55 Dir(PathBuf),
57 Off,
59}
60
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum CachePolicy {
65 #[default]
68 Default,
69 MaxSize(ByteSize),
71 Off,
73}
74
75impl CacheOptions {
76 #[cfg(not(target_arch = "wasm32"))]
80 pub(crate) fn dir(&self, app_id: Option<&str>, kind: &str) -> Option<PathBuf> {
81 let root = match &self.location {
82 CacheLocation::System => crate::storage::cache_dir()?,
83 CacheLocation::Dir(dir) => dir.clone(),
84 CacheLocation::Off => return None,
85 };
86 Some(root.join(crate::app_dir_name(app_id)).join(kind))
87 }
88
89 #[cfg(not(target_arch = "wasm32"))]
91 pub(crate) fn open_images(&self, app_id: Option<&str>) -> Option<nsh_core::image::DiskCache> {
92 let size = match self.images {
93 CachePolicy::Default => nsh_core::image::DEFAULT_DISK_CACHE_SIZE,
94 CachePolicy::MaxSize(size) => size,
95 CachePolicy::Off => return None,
96 };
97 nsh_core::image::DiskCache::open(self.dir(app_id, "images")?, size)
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use std::path::Path;
104
105 use super::*;
106
107 #[test]
108 fn caches_live_in_their_apps_directory() {
109 let options = CacheOptions::at(CacheLocation::Dir("/c".into()));
110 let images = options.open_images(Some("com.example.chat")).unwrap();
111 assert_eq!(images.dir(), Path::new("/c/com.example.chat/images"));
112 assert_eq!(images.max_size(), ByteSize::mib(256));
113 let odd = options.open_images(Some("a/b")).unwrap();
115 assert_eq!(odd.dir(), Path::new("/c/default/images"));
116 let small = options
117 .clone()
118 .with_images(CachePolicy::MaxSize(ByteSize::mib(8)));
119 assert_eq!(
120 small.open_images(None).unwrap().max_size(),
121 ByteSize::mib(8)
122 );
123 assert!(
124 options
125 .clone()
126 .with_images(CachePolicy::Off)
127 .open_images(None)
128 .is_none()
129 );
130 assert!(
131 options
132 .with_images(CachePolicy::MaxSize(ByteSize::ZERO))
133 .open_images(None)
134 .is_none()
135 );
136 assert!(CacheOptions::off().open_images(None).is_none());
137 }
138}