CacheFileInfo

Struct CacheFileInfo 

Source
pub struct CacheFileInfo {
    pub name: String,
    pub size_bytes: u64,
    pub modified: Option<SystemTime>,
}
Expand description

Information about a cached file

Fields§

§name: String

Name of the cached file

§size_bytes: u64

Size in bytes

§modified: Option<SystemTime>

Last modified time

Implementations§

Source§

impl CacheFileInfo

Source

pub fn formatted_size(&self) -> String

Get file size formatted as human-readable string

Examples found in repository?
examples/cache_management_demo.rs (line 115)
10fn main() {
11    println!("=== Enhanced Cache Management Demonstration ===\n");
12
13    // Demonstrate platform-specific cache directory detection
14    println!("=== Platform-Specific Cache Directory =========");
15    match get_cachedir() {
16        Ok(cachedir) => {
17            println!("Default cache directory: {}", cachedir.display());
18            println!("Platform: {}", std::env::consts::OS);
19        }
20        Err(e) => {
21            println!("Error getting cache directory: {e}");
22        }
23    }
24    println!();
25
26    // Demonstrate environment variable override
27    println!("=== Environment Variable Configuration =========");
28    println!("Set SCIRS2_CACHE_DIR to override default cache location");
29    println!("Set SCIRS2_OFFLINE=true to enable offline mode");
30    if let Ok(cache_env) = std::env::var("SCIRS2_CACHE_DIR") {
31        println!("Custom cache directory: {cache_env}");
32    } else {
33        println!("Using default cache directory");
34    }
35
36    if let Ok(offline_env) = std::env::var("SCIRS2_OFFLINE") {
37        println!("Offline mode: {offline_env}");
38    } else {
39        println!("Offline mode: Not set (defaults to false)");
40    }
41    println!();
42
43    // Create a temporary cache for demonstration
44    let tempdir = tempfile::tempdir().expect("Operation failed");
45    let demo_cachedir = tempdir.path().join("demo_cache");
46
47    // Demonstrate cache with size limits
48    println!("=== Cache with Size Limits =====================");
49    let mut cache_manager = CacheManager::with_full_config(
50        demo_cachedir.clone(),
51        50,          // 50 items in memory cache
52        3600,        // 1 hour TTL
53        1024 * 1024, // 1MB disk cache limit
54        false,       // Not in offline mode
55    );
56
57    println!("Created cache with 1MB size limit");
58    println!("Cache directory: {}", demo_cachedir.display());
59
60    // Add some test data to the cache
61    let cache = DatasetCache::with_full_config(demo_cachedir.clone(), 50, 3600, 1024 * 1024, false);
62
63    // Write several files of different sizes
64    let smalldata = vec![0u8; 1024]; // 1KB
65    let mediumdata = vec![1u8; 10240]; // 10KB
66    let largedata = vec![2u8; 102400]; // 100KB
67
68    cache
69        .write_cached("small_file.dat", &smalldata)
70        .expect("Operation failed");
71    cache
72        .write_cached("medium_file.dat", &mediumdata)
73        .expect("Operation failed");
74    cache
75        .write_cached("large_file.dat", &largedata)
76        .expect("Operation failed");
77
78    println!("Added test files to cache");
79    println!();
80
81    // Demonstrate basic cache statistics
82    println!("=== Basic Cache Statistics ====================");
83    let basic_stats = cache_manager.get_stats();
84    println!("Files: {}", basic_stats.file_count);
85    println!("Total size: {}", basic_stats.formatted_size());
86    println!();
87
88    // Demonstrate detailed cache statistics
89    println!("=== Detailed Cache Statistics ==================");
90    match cache_manager.get_detailed_stats() {
91        Ok(detailed_stats) => {
92            println!("Cache Directory: {}", detailed_stats.cachedir.display());
93            println!(
94                "Total Size: {} ({} files)",
95                detailed_stats.formatted_size(),
96                detailed_stats.file_count
97            );
98            println!("Max Size: {}", detailed_stats.formatted_max_size());
99            println!("Usage: {:.1}%", detailed_stats.usage_percentage() * 100.0);
100            println!(
101                "Offline Mode: {}",
102                if detailed_stats.offline_mode {
103                    "Enabled"
104                } else {
105                    "Disabled"
106                }
107            );
108
109            if !detailed_stats.files.is_empty() {
110                println!("\nCached Files (sorted by size):");
111                for file in &detailed_stats.files {
112                    println!(
113                        "  {} - {} (modified {})",
114                        file.name,
115                        file.formatted_size(),
116                        file.formatted_modified()
117                    );
118                }
119            }
120        }
121        Err(e) => {
122            println!("Error getting detailed stats: {e}");
123        }
124    }
125    println!();
126
127    // Demonstrate cache management operations
128    println!("=== Cache Management Operations ===============");
129    println!("Available operations:");
130    println!("1. List cached files");
131    let cached_files = cache_manager.list_cached_files().expect("Operation failed");
132    for file in &cached_files {
133        println!("   - {file}");
134    }
135
136    println!("2. Check if specific files are cached");
137    println!(
138        "   small_file.dat: {}",
139        cache_manager.is_cached("small_file.dat")
140    );
141    println!(
142        "   nonexistent.dat: {}",
143        cache_manager.is_cached("nonexistent.dat")
144    );
145
146    println!("3. Remove specific file");
147    cache_manager
148        .remove("medium_file.dat")
149        .expect("Operation failed");
150    println!("   Removed medium_file.dat");
151    println!(
152        "   Files remaining: {}",
153        cache_manager
154            .list_cached_files()
155            .expect("Operation failed")
156            .len()
157    );
158    println!();
159
160    // Demonstrate offline mode
161    println!("=== Offline Mode Configuration ================");
162    println!("Current offline mode: {}", cache_manager.is_offline());
163    cache_manager.set_offline_mode(true);
164    println!("Enabled offline mode: {}", cache_manager.is_offline());
165    cache_manager.set_offline_mode(false);
166    println!("Disabled offline mode: {}", cache_manager.is_offline());
167    println!();
168
169    // Demonstrate cache size management
170    println!("=== Cache Size Management =====================");
171    println!(
172        "Current max cache size: {} bytes",
173        cache_manager.max_cache_size()
174    );
175    cache_manager.set_max_cache_size(512 * 1024); // 512KB
176    println!(
177        "Set max cache size to: {} bytes",
178        cache_manager.max_cache_size()
179    );
180
181    // Add a large file that would exceed the new limit
182    let very_largedata = vec![3u8; 400 * 1024]; // 400KB
183    cache
184        .write_cached("very_large_file.dat", &very_largedata)
185        .expect("Operation failed");
186
187    let final_stats = cache_manager
188        .get_detailed_stats()
189        .expect("Operation failed");
190    println!(
191        "Final cache size: {} (should be within limit)",
192        final_stats.formatted_size()
193    );
194    println!(
195        "Final usage: {:.1}%",
196        final_stats.usage_percentage() * 100.0
197    );
198    println!();
199
200    // Demonstrate cache cleanup
201    println!("=== Cache Cleanup ==============================");
202    println!(
203        "Files before cleanup: {}",
204        cache_manager
205            .list_cached_files()
206            .expect("Operation failed")
207            .len()
208    );
209    cache_manager
210        .cleanup_old_files(100 * 1024)
211        .expect("Operation failed"); // Clean up to fit 100KB
212    let cleanup_stats = cache_manager
213        .get_detailed_stats()
214        .expect("Operation failed");
215    println!("Files after cleanup: {}", cleanup_stats.file_count);
216    println!("Size after cleanup: {}", cleanup_stats.formatted_size());
217    println!();
218
219    // Demonstrate cache report
220    println!("=== Complete Cache Report ======================");
221    cache_manager
222        .print_cache_report()
223        .expect("Operation failed");
224    println!();
225
226    // Clear all cache data
227    println!("=== Cache Clearing =============================");
228    cache_manager.clear_all().expect("Operation failed");
229    let empty_stats = cache_manager.get_stats();
230    println!("Files after clearing: {}", empty_stats.file_count);
231    println!("Size after clearing: {}", empty_stats.formatted_size());
232    println!();
233
234    // Demonstrate configuration examples
235    println!("=== Configuration Examples =====================");
236    println!("Example configurations for different use cases:");
237    println!();
238
239    println!("1. Development (small cache, frequent cleanup):");
240    println!("   CacheManager::with_full_config(cachedir, 20, 1800, 50*1024*1024, false)");
241    println!("   - 20 items in memory, 30 min TTL, 50MB disk limit");
242    println!();
243
244    println!("2. Production (large cache, longer retention):");
245    println!("   CacheManager::with_full_config(cachedir, 500, 86400, 1024*1024*1024, false)");
246    println!("   - 500 items in memory, 24 hour TTL, 1GB disk limit");
247    println!();
248
249    println!("3. Offline environment:");
250    println!("   CacheManager::with_full_config(cachedir, 100, 3600, 0, true)");
251    println!("   - Offline mode enabled, unlimited disk cache");
252    println!();
253
254    println!("4. Memory-constrained (minimal cache):");
255    println!("   CacheManager::with_full_config(cachedir, 10, 900, 10*1024*1024, false)");
256    println!("   - 10 items in memory, 15 min TTL, 10MB disk limit");
257    println!();
258
259    println!("=== Cache Management Demo Complete =============");
260}
Source

pub fn formatted_modified(&self) -> String

Get formatted modification time

Examples found in repository?
examples/cache_management_demo.rs (line 116)
10fn main() {
11    println!("=== Enhanced Cache Management Demonstration ===\n");
12
13    // Demonstrate platform-specific cache directory detection
14    println!("=== Platform-Specific Cache Directory =========");
15    match get_cachedir() {
16        Ok(cachedir) => {
17            println!("Default cache directory: {}", cachedir.display());
18            println!("Platform: {}", std::env::consts::OS);
19        }
20        Err(e) => {
21            println!("Error getting cache directory: {e}");
22        }
23    }
24    println!();
25
26    // Demonstrate environment variable override
27    println!("=== Environment Variable Configuration =========");
28    println!("Set SCIRS2_CACHE_DIR to override default cache location");
29    println!("Set SCIRS2_OFFLINE=true to enable offline mode");
30    if let Ok(cache_env) = std::env::var("SCIRS2_CACHE_DIR") {
31        println!("Custom cache directory: {cache_env}");
32    } else {
33        println!("Using default cache directory");
34    }
35
36    if let Ok(offline_env) = std::env::var("SCIRS2_OFFLINE") {
37        println!("Offline mode: {offline_env}");
38    } else {
39        println!("Offline mode: Not set (defaults to false)");
40    }
41    println!();
42
43    // Create a temporary cache for demonstration
44    let tempdir = tempfile::tempdir().expect("Operation failed");
45    let demo_cachedir = tempdir.path().join("demo_cache");
46
47    // Demonstrate cache with size limits
48    println!("=== Cache with Size Limits =====================");
49    let mut cache_manager = CacheManager::with_full_config(
50        demo_cachedir.clone(),
51        50,          // 50 items in memory cache
52        3600,        // 1 hour TTL
53        1024 * 1024, // 1MB disk cache limit
54        false,       // Not in offline mode
55    );
56
57    println!("Created cache with 1MB size limit");
58    println!("Cache directory: {}", demo_cachedir.display());
59
60    // Add some test data to the cache
61    let cache = DatasetCache::with_full_config(demo_cachedir.clone(), 50, 3600, 1024 * 1024, false);
62
63    // Write several files of different sizes
64    let smalldata = vec![0u8; 1024]; // 1KB
65    let mediumdata = vec![1u8; 10240]; // 10KB
66    let largedata = vec![2u8; 102400]; // 100KB
67
68    cache
69        .write_cached("small_file.dat", &smalldata)
70        .expect("Operation failed");
71    cache
72        .write_cached("medium_file.dat", &mediumdata)
73        .expect("Operation failed");
74    cache
75        .write_cached("large_file.dat", &largedata)
76        .expect("Operation failed");
77
78    println!("Added test files to cache");
79    println!();
80
81    // Demonstrate basic cache statistics
82    println!("=== Basic Cache Statistics ====================");
83    let basic_stats = cache_manager.get_stats();
84    println!("Files: {}", basic_stats.file_count);
85    println!("Total size: {}", basic_stats.formatted_size());
86    println!();
87
88    // Demonstrate detailed cache statistics
89    println!("=== Detailed Cache Statistics ==================");
90    match cache_manager.get_detailed_stats() {
91        Ok(detailed_stats) => {
92            println!("Cache Directory: {}", detailed_stats.cachedir.display());
93            println!(
94                "Total Size: {} ({} files)",
95                detailed_stats.formatted_size(),
96                detailed_stats.file_count
97            );
98            println!("Max Size: {}", detailed_stats.formatted_max_size());
99            println!("Usage: {:.1}%", detailed_stats.usage_percentage() * 100.0);
100            println!(
101                "Offline Mode: {}",
102                if detailed_stats.offline_mode {
103                    "Enabled"
104                } else {
105                    "Disabled"
106                }
107            );
108
109            if !detailed_stats.files.is_empty() {
110                println!("\nCached Files (sorted by size):");
111                for file in &detailed_stats.files {
112                    println!(
113                        "  {} - {} (modified {})",
114                        file.name,
115                        file.formatted_size(),
116                        file.formatted_modified()
117                    );
118                }
119            }
120        }
121        Err(e) => {
122            println!("Error getting detailed stats: {e}");
123        }
124    }
125    println!();
126
127    // Demonstrate cache management operations
128    println!("=== Cache Management Operations ===============");
129    println!("Available operations:");
130    println!("1. List cached files");
131    let cached_files = cache_manager.list_cached_files().expect("Operation failed");
132    for file in &cached_files {
133        println!("   - {file}");
134    }
135
136    println!("2. Check if specific files are cached");
137    println!(
138        "   small_file.dat: {}",
139        cache_manager.is_cached("small_file.dat")
140    );
141    println!(
142        "   nonexistent.dat: {}",
143        cache_manager.is_cached("nonexistent.dat")
144    );
145
146    println!("3. Remove specific file");
147    cache_manager
148        .remove("medium_file.dat")
149        .expect("Operation failed");
150    println!("   Removed medium_file.dat");
151    println!(
152        "   Files remaining: {}",
153        cache_manager
154            .list_cached_files()
155            .expect("Operation failed")
156            .len()
157    );
158    println!();
159
160    // Demonstrate offline mode
161    println!("=== Offline Mode Configuration ================");
162    println!("Current offline mode: {}", cache_manager.is_offline());
163    cache_manager.set_offline_mode(true);
164    println!("Enabled offline mode: {}", cache_manager.is_offline());
165    cache_manager.set_offline_mode(false);
166    println!("Disabled offline mode: {}", cache_manager.is_offline());
167    println!();
168
169    // Demonstrate cache size management
170    println!("=== Cache Size Management =====================");
171    println!(
172        "Current max cache size: {} bytes",
173        cache_manager.max_cache_size()
174    );
175    cache_manager.set_max_cache_size(512 * 1024); // 512KB
176    println!(
177        "Set max cache size to: {} bytes",
178        cache_manager.max_cache_size()
179    );
180
181    // Add a large file that would exceed the new limit
182    let very_largedata = vec![3u8; 400 * 1024]; // 400KB
183    cache
184        .write_cached("very_large_file.dat", &very_largedata)
185        .expect("Operation failed");
186
187    let final_stats = cache_manager
188        .get_detailed_stats()
189        .expect("Operation failed");
190    println!(
191        "Final cache size: {} (should be within limit)",
192        final_stats.formatted_size()
193    );
194    println!(
195        "Final usage: {:.1}%",
196        final_stats.usage_percentage() * 100.0
197    );
198    println!();
199
200    // Demonstrate cache cleanup
201    println!("=== Cache Cleanup ==============================");
202    println!(
203        "Files before cleanup: {}",
204        cache_manager
205            .list_cached_files()
206            .expect("Operation failed")
207            .len()
208    );
209    cache_manager
210        .cleanup_old_files(100 * 1024)
211        .expect("Operation failed"); // Clean up to fit 100KB
212    let cleanup_stats = cache_manager
213        .get_detailed_stats()
214        .expect("Operation failed");
215    println!("Files after cleanup: {}", cleanup_stats.file_count);
216    println!("Size after cleanup: {}", cleanup_stats.formatted_size());
217    println!();
218
219    // Demonstrate cache report
220    println!("=== Complete Cache Report ======================");
221    cache_manager
222        .print_cache_report()
223        .expect("Operation failed");
224    println!();
225
226    // Clear all cache data
227    println!("=== Cache Clearing =============================");
228    cache_manager.clear_all().expect("Operation failed");
229    let empty_stats = cache_manager.get_stats();
230    println!("Files after clearing: {}", empty_stats.file_count);
231    println!("Size after clearing: {}", empty_stats.formatted_size());
232    println!();
233
234    // Demonstrate configuration examples
235    println!("=== Configuration Examples =====================");
236    println!("Example configurations for different use cases:");
237    println!();
238
239    println!("1. Development (small cache, frequent cleanup):");
240    println!("   CacheManager::with_full_config(cachedir, 20, 1800, 50*1024*1024, false)");
241    println!("   - 20 items in memory, 30 min TTL, 50MB disk limit");
242    println!();
243
244    println!("2. Production (large cache, longer retention):");
245    println!("   CacheManager::with_full_config(cachedir, 500, 86400, 1024*1024*1024, false)");
246    println!("   - 500 items in memory, 24 hour TTL, 1GB disk limit");
247    println!();
248
249    println!("3. Offline environment:");
250    println!("   CacheManager::with_full_config(cachedir, 100, 3600, 0, true)");
251    println!("   - Offline mode enabled, unlimited disk cache");
252    println!();
253
254    println!("4. Memory-constrained (minimal cache):");
255    println!("   CacheManager::with_full_config(cachedir, 10, 900, 10*1024*1024, false)");
256    println!("   - 10 items in memory, 15 min TTL, 10MB disk limit");
257    println!();
258
259    println!("=== Cache Management Demo Complete =============");
260}

Trait Implementations§

Source§

impl Clone for CacheFileInfo

Source§

fn clone(&self) -> CacheFileInfo

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CacheFileInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more