BatchOperations

Struct BatchOperations 

Source
pub struct BatchOperations { /* private fields */ }
Expand description

Batch operations manager for dataset caching

Implementations§

Source§

impl BatchOperations

Source

pub fn new(cache: CacheManager) -> Self

Create a new batch operations manager

Examples found in repository?
examples/batch_operations_demo.rs (line 17)
10fn main() {
11    println!("=== Batch Operations Demonstration ===\n");
12
13    // Create a cache manager for demonstration
14    let cache_manager = CacheManager::new().expect("Failed to create cache manager");
15
16    println!("=== Setting up Batch Operations Manager =====");
17    let batch_ops = BatchOperations::new(cache_manager)
18        .with_parallel(false) // Use sequential for deterministic demo output
19        .with_retry_config(2, Duration::from_millis(500));
20
21    println!("Batch operations manager configured:");
22    println!("  - Parallel processing: disabled (for demo)");
23    println!("  - Max retries: 2");
24    println!("  - Retry delay: 500ms");
25
26    // Demonstrate cache setup with sample data
27    println!("\n=== Sample Data Setup ========================");
28    setup_sample_cachedata(&batch_ops);
29
30    // Demonstrate batch statistics
31    println!("\n=== Cache Statistics ==========================");
32    demonstrate_cache_statistics(&batch_ops);
33
34    // Demonstrate batch processing
35    println!("\n=== Batch Processing =========================");
36    demonstrate_batch_processing(&batch_ops);
37
38    // Demonstrate selective cleanup
39    println!("\n=== Selective Cache Cleanup ==================");
40    demonstrate_selective_cleanup(&batch_ops);
41
42    // Show final cache state
43    println!("\n=== Final Cache State =========================");
44    show_final_cache_state(&batch_ops);
45
46    // Performance considerations
47    println!("\n=== Performance Considerations ================");
48    demonstrate_performance_features();
49
50    println!("\n=== Batch Operations Demo Complete ===========");
51}
Source

pub fn with_parallel(self, parallel: bool) -> Self

Configure parallel processing

Examples found in repository?
examples/batch_operations_demo.rs (line 18)
10fn main() {
11    println!("=== Batch Operations Demonstration ===\n");
12
13    // Create a cache manager for demonstration
14    let cache_manager = CacheManager::new().expect("Failed to create cache manager");
15
16    println!("=== Setting up Batch Operations Manager =====");
17    let batch_ops = BatchOperations::new(cache_manager)
18        .with_parallel(false) // Use sequential for deterministic demo output
19        .with_retry_config(2, Duration::from_millis(500));
20
21    println!("Batch operations manager configured:");
22    println!("  - Parallel processing: disabled (for demo)");
23    println!("  - Max retries: 2");
24    println!("  - Retry delay: 500ms");
25
26    // Demonstrate cache setup with sample data
27    println!("\n=== Sample Data Setup ========================");
28    setup_sample_cachedata(&batch_ops);
29
30    // Demonstrate batch statistics
31    println!("\n=== Cache Statistics ==========================");
32    demonstrate_cache_statistics(&batch_ops);
33
34    // Demonstrate batch processing
35    println!("\n=== Batch Processing =========================");
36    demonstrate_batch_processing(&batch_ops);
37
38    // Demonstrate selective cleanup
39    println!("\n=== Selective Cache Cleanup ==================");
40    demonstrate_selective_cleanup(&batch_ops);
41
42    // Show final cache state
43    println!("\n=== Final Cache State =========================");
44    show_final_cache_state(&batch_ops);
45
46    // Performance considerations
47    println!("\n=== Performance Considerations ================");
48    demonstrate_performance_features();
49
50    println!("\n=== Batch Operations Demo Complete ===========");
51}
Source

pub fn with_retry_config( self, max_retries: usize, retry_delay: Duration, ) -> Self

Configure retry settings

Examples found in repository?
examples/batch_operations_demo.rs (line 19)
10fn main() {
11    println!("=== Batch Operations Demonstration ===\n");
12
13    // Create a cache manager for demonstration
14    let cache_manager = CacheManager::new().expect("Failed to create cache manager");
15
16    println!("=== Setting up Batch Operations Manager =====");
17    let batch_ops = BatchOperations::new(cache_manager)
18        .with_parallel(false) // Use sequential for deterministic demo output
19        .with_retry_config(2, Duration::from_millis(500));
20
21    println!("Batch operations manager configured:");
22    println!("  - Parallel processing: disabled (for demo)");
23    println!("  - Max retries: 2");
24    println!("  - Retry delay: 500ms");
25
26    // Demonstrate cache setup with sample data
27    println!("\n=== Sample Data Setup ========================");
28    setup_sample_cachedata(&batch_ops);
29
30    // Demonstrate batch statistics
31    println!("\n=== Cache Statistics ==========================");
32    demonstrate_cache_statistics(&batch_ops);
33
34    // Demonstrate batch processing
35    println!("\n=== Batch Processing =========================");
36    demonstrate_batch_processing(&batch_ops);
37
38    // Demonstrate selective cleanup
39    println!("\n=== Selective Cache Cleanup ==================");
40    demonstrate_selective_cleanup(&batch_ops);
41
42    // Show final cache state
43    println!("\n=== Final Cache State =========================");
44    show_final_cache_state(&batch_ops);
45
46    // Performance considerations
47    println!("\n=== Performance Considerations ================");
48    demonstrate_performance_features();
49
50    println!("\n=== Batch Operations Demo Complete ===========");
51}
Source

pub fn batch_verify_integrity( &self, files_andhashes: &[(&str, &str)], ) -> BatchResult

Verify integrity of multiple cached files

Source

pub fn selective_cleanup( &self, patterns: &[&str], max_age_days: Option<u32>, ) -> Result<BatchResult>

Clean up cache selectively based on patterns

Examples found in repository?
examples/batch_operations_demo.rs (line 173)
160fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
161    println!("Demonstrating selective cache cleanup...");
162
163    // Show current cache state
164    let initial_stats = batch_ops.get_cache_statistics().unwrap();
165    println!(
166        "Before cleanup: {} files, {}",
167        initial_stats.success_count,
168        formatbytes(initial_stats.total_bytes)
169    );
170
171    // Example 1: Clean up temporary files
172    println!("\n1. Cleaning up temporary files (*.tmp):");
173    match batch_ops.selective_cleanup(&["*.tmp"], None) {
174        Ok(result) => {
175            println!("   {}", result.summary());
176            if result.success_count > 0 {
177                println!("   Removed {} temporary files", result.success_count);
178            }
179        }
180        Err(e) => println!("   Failed: {e}"),
181    }
182
183    // Example 2: Clean up old files (demo with 0 days to show functionality)
184    println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
185    match batch_ops.selective_cleanup(&["*"], Some(0)) {
186        Ok(result) => {
187            println!("   {}", result.summary());
188            println!("   (Note: Using 0 days for demonstration - all files are 'old')");
189        }
190        Err(e) => println!("   Failed: {e}"),
191    }
192
193    // Show final cache state
194    let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
195    println!(
196        "\nAfter cleanup: {} files, {}",
197        final_stats.success_count,
198        formatbytes(final_stats.total_bytes)
199    );
200
201    let freed_space = initial_stats
202        .total_bytes
203        .saturating_sub(final_stats.total_bytes);
204    if freed_space > 0 {
205        println!("Space freed: {}", formatbytes(freed_space));
206    }
207}
Source

pub fn batch_process<F, T, E>( &self, names: &[String], processor: F, ) -> BatchResult
where F: Fn(&str, &[u8]) -> Result<T, E> + Sync + Send + 'static, E: Display, T: Send,

Process multiple datasets with a given function

Examples found in repository?
examples/batch_operations_demo.rs (lines 117-123)
102fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
103    println!("Processing multiple cached files in batch...");
104
105    // Get list of cached files
106    let cached_files = batch_ops.list_cached_files().unwrap_or_default();
107
108    if cached_files.is_empty() {
109        println!("No cached files found for processing");
110        return;
111    }
112
113    println!("Found {} files to process", cached_files.len());
114
115    // Example 1: Validate file sizes
116    println!("\n1. File Size Validation:");
117    let result = batch_ops.batch_process(&cached_files, |name, data| {
118        if data.len() < 10 {
119            Err(format!("File {name} too small ({} bytes)", data.len()))
120        } else {
121            Ok(data.len())
122        }
123    });
124
125    println!("   {}", result.summary());
126    if result.failure_count > 0 {
127        for (file, error) in &result.failures {
128            println!("   ⚠ {file}: {error}");
129        }
130    }
131
132    // Example 2: Content type detection
133    println!("\n2. Content Type Detection:");
134    let result = batch_ops.batch_process(&cached_files, |name, data| {
135        let content_type = detect_content_type(name, data);
136        println!("   {name} -> {content_type}");
137        Ok::<String, String>(content_type)
138    });
139
140    println!("   {}", result.summary());
141
142    // Example 3: Data integrity check
143    println!("\n3. Data Integrity Check:");
144    let result = batch_ops.batch_process(&cached_files, |name, data| {
145        // Simple check: ensure data is not all zeros
146        let all_zeros = data.iter().all(|&b| b == 0);
147        if all_zeros && data.len() > 100 {
148            Err("Suspicious: large file with all zeros".to_string())
149        } else {
150            let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
151            println!("   {name} checksum: {checksum}");
152            Ok(checksum)
153        }
154    });
155
156    println!("   {}", result.summary());
157}
Source

pub fn cache_manager(&self) -> &CacheManager

Get access to the underlying cache manager

Source

pub fn write_cached(&self, name: &str, data: &[u8]) -> Result<()>

Write data to cache

Examples found in repository?
examples/batch_operations_demo.rs (line 69)
54fn setup_sample_cachedata(batch_ops: &BatchOperations) {
55    println!("Creating sample cached datasets...");
56
57    // Create various types of sample data
58    let sample_datasets = [
59        ("iris_processed.csv", create_csvdata()),
60        ("experiment_001.json", create_jsondata()),
61        ("temp_file_001.tmp", create_binarydata(100)),
62        ("temp_file_002.tmp", create_binarydata(200)),
63        ("largedataset.dat", create_binarydata(1024)),
64        ("model_weights.bin", create_binarydata(512)),
65        ("results_summary.txt", createtextdata()),
66    ];
67
68    for (name, data) in sample_datasets {
69        if let Err(e) = batch_ops.write_cached(name, &data) {
70            println!("  Warning: Failed to cache {name}: {e}");
71        } else {
72            println!("  ✓ Cached {name} ({} bytes)", data.len());
73        }
74    }
75}
Source

pub fn read_cached(&self, name: &str) -> Result<Vec<u8>>

Read data from cache

Examples found in repository?
examples/batch_operations_demo.rs (line 219)
210fn show_final_cache_state(batch_ops: &BatchOperations) {
211    println!("Final cache contents:");
212
213    match batch_ops.list_cached_files() {
214        Ok(files) => {
215            if files.is_empty() {
216                println!("  Cache is empty");
217            } else {
218                for file in files {
219                    if let Ok(data) = batch_ops.read_cached(&file) {
220                        println!("  {file} ({} bytes)", data.len());
221                    }
222                }
223            }
224        }
225        Err(e) => println!("  Failed to list files: {e}"),
226    }
227
228    // Print detailed cache report
229    if let Err(e) = batch_ops.print_cache_report() {
230        println!("Failed to generate cache report: {e}");
231    }
232}
Source

pub fn list_cached_files(&self) -> Result<Vec<String>>

List cached files

Examples found in repository?
examples/batch_operations_demo.rs (line 106)
102fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
103    println!("Processing multiple cached files in batch...");
104
105    // Get list of cached files
106    let cached_files = batch_ops.list_cached_files().unwrap_or_default();
107
108    if cached_files.is_empty() {
109        println!("No cached files found for processing");
110        return;
111    }
112
113    println!("Found {} files to process", cached_files.len());
114
115    // Example 1: Validate file sizes
116    println!("\n1. File Size Validation:");
117    let result = batch_ops.batch_process(&cached_files, |name, data| {
118        if data.len() < 10 {
119            Err(format!("File {name} too small ({} bytes)", data.len()))
120        } else {
121            Ok(data.len())
122        }
123    });
124
125    println!("   {}", result.summary());
126    if result.failure_count > 0 {
127        for (file, error) in &result.failures {
128            println!("   ⚠ {file}: {error}");
129        }
130    }
131
132    // Example 2: Content type detection
133    println!("\n2. Content Type Detection:");
134    let result = batch_ops.batch_process(&cached_files, |name, data| {
135        let content_type = detect_content_type(name, data);
136        println!("   {name} -> {content_type}");
137        Ok::<String, String>(content_type)
138    });
139
140    println!("   {}", result.summary());
141
142    // Example 3: Data integrity check
143    println!("\n3. Data Integrity Check:");
144    let result = batch_ops.batch_process(&cached_files, |name, data| {
145        // Simple check: ensure data is not all zeros
146        let all_zeros = data.iter().all(|&b| b == 0);
147        if all_zeros && data.len() > 100 {
148            Err("Suspicious: large file with all zeros".to_string())
149        } else {
150            let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
151            println!("   {name} checksum: {checksum}");
152            Ok(checksum)
153        }
154    });
155
156    println!("   {}", result.summary());
157}
158
159#[allow(dead_code)]
160fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
161    println!("Demonstrating selective cache cleanup...");
162
163    // Show current cache state
164    let initial_stats = batch_ops.get_cache_statistics().unwrap();
165    println!(
166        "Before cleanup: {} files, {}",
167        initial_stats.success_count,
168        formatbytes(initial_stats.total_bytes)
169    );
170
171    // Example 1: Clean up temporary files
172    println!("\n1. Cleaning up temporary files (*.tmp):");
173    match batch_ops.selective_cleanup(&["*.tmp"], None) {
174        Ok(result) => {
175            println!("   {}", result.summary());
176            if result.success_count > 0 {
177                println!("   Removed {} temporary files", result.success_count);
178            }
179        }
180        Err(e) => println!("   Failed: {e}"),
181    }
182
183    // Example 2: Clean up old files (demo with 0 days to show functionality)
184    println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
185    match batch_ops.selective_cleanup(&["*"], Some(0)) {
186        Ok(result) => {
187            println!("   {}", result.summary());
188            println!("   (Note: Using 0 days for demonstration - all files are 'old')");
189        }
190        Err(e) => println!("   Failed: {e}"),
191    }
192
193    // Show final cache state
194    let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
195    println!(
196        "\nAfter cleanup: {} files, {}",
197        final_stats.success_count,
198        formatbytes(final_stats.total_bytes)
199    );
200
201    let freed_space = initial_stats
202        .total_bytes
203        .saturating_sub(final_stats.total_bytes);
204    if freed_space > 0 {
205        println!("Space freed: {}", formatbytes(freed_space));
206    }
207}
208
209#[allow(dead_code)]
210fn show_final_cache_state(batch_ops: &BatchOperations) {
211    println!("Final cache contents:");
212
213    match batch_ops.list_cached_files() {
214        Ok(files) => {
215            if files.is_empty() {
216                println!("  Cache is empty");
217            } else {
218                for file in files {
219                    if let Ok(data) = batch_ops.read_cached(&file) {
220                        println!("  {file} ({} bytes)", data.len());
221                    }
222                }
223            }
224        }
225        Err(e) => println!("  Failed to list files: {e}"),
226    }
227
228    // Print detailed cache report
229    if let Err(e) = batch_ops.print_cache_report() {
230        println!("Failed to generate cache report: {e}");
231    }
232}
Source

pub fn print_cache_report(&self) -> Result<()>

Print cache report

Examples found in repository?
examples/batch_operations_demo.rs (line 229)
210fn show_final_cache_state(batch_ops: &BatchOperations) {
211    println!("Final cache contents:");
212
213    match batch_ops.list_cached_files() {
214        Ok(files) => {
215            if files.is_empty() {
216                println!("  Cache is empty");
217            } else {
218                for file in files {
219                    if let Ok(data) = batch_ops.read_cached(&file) {
220                        println!("  {file} ({} bytes)", data.len());
221                    }
222                }
223            }
224        }
225        Err(e) => println!("  Failed to list files: {e}"),
226    }
227
228    // Print detailed cache report
229    if let Err(e) = batch_ops.print_cache_report() {
230        println!("Failed to generate cache report: {e}");
231    }
232}
Source

pub fn get_cache_statistics(&self) -> Result<BatchResult>

Get statistics about cached datasets

Examples found in repository?
examples/batch_operations_demo.rs (line 79)
78fn demonstrate_cache_statistics(batch_ops: &BatchOperations) {
79    match batch_ops.get_cache_statistics() {
80        Ok(result) => {
81            println!("{}", result.summary());
82            println!("Cache analysis:");
83            println!("  - Files processed: {}", result.success_count);
84            println!("  - Total cache size: {}", formatbytes(result.total_bytes));
85            println!(
86                "  - Analysis time: {:.2}ms",
87                result.elapsed_time.as_millis()
88            );
89
90            if result.failure_count > 0 {
91                println!("  - Failed files: {}", result.failure_count);
92                for (file, error) in &result.failures {
93                    println!("    • {file}: {error}");
94                }
95            }
96        }
97        Err(e) => println!("Failed to get cache statistics: {e}"),
98    }
99}
100
101#[allow(dead_code)]
102fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
103    println!("Processing multiple cached files in batch...");
104
105    // Get list of cached files
106    let cached_files = batch_ops.list_cached_files().unwrap_or_default();
107
108    if cached_files.is_empty() {
109        println!("No cached files found for processing");
110        return;
111    }
112
113    println!("Found {} files to process", cached_files.len());
114
115    // Example 1: Validate file sizes
116    println!("\n1. File Size Validation:");
117    let result = batch_ops.batch_process(&cached_files, |name, data| {
118        if data.len() < 10 {
119            Err(format!("File {name} too small ({} bytes)", data.len()))
120        } else {
121            Ok(data.len())
122        }
123    });
124
125    println!("   {}", result.summary());
126    if result.failure_count > 0 {
127        for (file, error) in &result.failures {
128            println!("   ⚠ {file}: {error}");
129        }
130    }
131
132    // Example 2: Content type detection
133    println!("\n2. Content Type Detection:");
134    let result = batch_ops.batch_process(&cached_files, |name, data| {
135        let content_type = detect_content_type(name, data);
136        println!("   {name} -> {content_type}");
137        Ok::<String, String>(content_type)
138    });
139
140    println!("   {}", result.summary());
141
142    // Example 3: Data integrity check
143    println!("\n3. Data Integrity Check:");
144    let result = batch_ops.batch_process(&cached_files, |name, data| {
145        // Simple check: ensure data is not all zeros
146        let all_zeros = data.iter().all(|&b| b == 0);
147        if all_zeros && data.len() > 100 {
148            Err("Suspicious: large file with all zeros".to_string())
149        } else {
150            let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
151            println!("   {name} checksum: {checksum}");
152            Ok(checksum)
153        }
154    });
155
156    println!("   {}", result.summary());
157}
158
159#[allow(dead_code)]
160fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
161    println!("Demonstrating selective cache cleanup...");
162
163    // Show current cache state
164    let initial_stats = batch_ops.get_cache_statistics().unwrap();
165    println!(
166        "Before cleanup: {} files, {}",
167        initial_stats.success_count,
168        formatbytes(initial_stats.total_bytes)
169    );
170
171    // Example 1: Clean up temporary files
172    println!("\n1. Cleaning up temporary files (*.tmp):");
173    match batch_ops.selective_cleanup(&["*.tmp"], None) {
174        Ok(result) => {
175            println!("   {}", result.summary());
176            if result.success_count > 0 {
177                println!("   Removed {} temporary files", result.success_count);
178            }
179        }
180        Err(e) => println!("   Failed: {e}"),
181    }
182
183    // Example 2: Clean up old files (demo with 0 days to show functionality)
184    println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
185    match batch_ops.selective_cleanup(&["*"], Some(0)) {
186        Ok(result) => {
187            println!("   {}", result.summary());
188            println!("   (Note: Using 0 days for demonstration - all files are 'old')");
189        }
190        Err(e) => println!("   Failed: {e}"),
191    }
192
193    // Show final cache state
194    let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
195    println!(
196        "\nAfter cleanup: {} files, {}",
197        final_stats.success_count,
198        formatbytes(final_stats.total_bytes)
199    );
200
201    let freed_space = initial_stats
202        .total_bytes
203        .saturating_sub(final_stats.total_bytes);
204    if freed_space > 0 {
205        println!("Space freed: {}", formatbytes(freed_space));
206    }
207}

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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, 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