pub struct BatchOperations { /* private fields */ }
Expand description
Batch operations manager for dataset caching
Implementations§
Source§impl BatchOperations
impl BatchOperations
Sourcepub fn new(cache: CacheManager) -> Self
pub fn new(cache: CacheManager) -> Self
Create a new batch operations manager
Examples found in repository?
examples/batch_operations_demo.rs (line 17)
9fn main() {
10 println!("=== Batch Operations Demonstration ===\n");
11
12 // Create a cache manager for demonstration
13 let cache_dir = scirs2_datasets::get_cache_dir().unwrap();
14 let cache_manager = CacheManager::new(cache_dir, 100, 3600);
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_cache_data(&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}
Sourcepub fn with_parallel(self, parallel: bool) -> Self
pub fn with_parallel(self, parallel: bool) -> Self
Configure parallel processing
Examples found in repository?
examples/batch_operations_demo.rs (line 18)
9fn main() {
10 println!("=== Batch Operations Demonstration ===\n");
11
12 // Create a cache manager for demonstration
13 let cache_dir = scirs2_datasets::get_cache_dir().unwrap();
14 let cache_manager = CacheManager::new(cache_dir, 100, 3600);
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_cache_data(&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}
Sourcepub fn with_retry_config(
self,
max_retries: usize,
retry_delay: Duration,
) -> Self
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)
9fn main() {
10 println!("=== Batch Operations Demonstration ===\n");
11
12 // Create a cache manager for demonstration
13 let cache_dir = scirs2_datasets::get_cache_dir().unwrap();
14 let cache_manager = CacheManager::new(cache_dir, 100, 3600);
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_cache_data(&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}
Sourcepub fn batch_verify_integrity(
&self,
files_and_hashes: &[(&str, &str)],
) -> BatchResult
pub fn batch_verify_integrity( &self, files_and_hashes: &[(&str, &str)], ) -> BatchResult
Verify integrity of multiple cached files
Sourcepub fn selective_cleanup(
&self,
patterns: &[&str],
max_age_days: Option<u32>,
) -> Result<BatchResult>
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 169)
156fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
157 println!("Demonstrating selective cache cleanup...");
158
159 // Show current cache state
160 let initial_stats = batch_ops.get_cache_statistics().unwrap();
161 println!(
162 "Before cleanup: {} files, {}",
163 initial_stats.success_count,
164 format_bytes(initial_stats.total_bytes)
165 );
166
167 // Example 1: Clean up temporary files
168 println!("\n1. Cleaning up temporary files (*.tmp):");
169 match batch_ops.selective_cleanup(&["*.tmp"], None) {
170 Ok(result) => {
171 println!(" {}", result.summary());
172 if result.success_count > 0 {
173 println!(" Removed {} temporary files", result.success_count);
174 }
175 }
176 Err(e) => println!(" Failed: {}", e),
177 }
178
179 // Example 2: Clean up old files (demo with 0 days to show functionality)
180 println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
181 match batch_ops.selective_cleanup(&["*"], Some(0)) {
182 Ok(result) => {
183 println!(" {}", result.summary());
184 println!(" (Note: Using 0 days for demonstration - all files are 'old')");
185 }
186 Err(e) => println!(" Failed: {}", e),
187 }
188
189 // Show final cache state
190 let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
191 println!(
192 "\nAfter cleanup: {} files, {}",
193 final_stats.success_count,
194 format_bytes(final_stats.total_bytes)
195 );
196
197 let freed_space = initial_stats
198 .total_bytes
199 .saturating_sub(final_stats.total_bytes);
200 if freed_space > 0 {
201 println!("Space freed: {}", format_bytes(freed_space));
202 }
203}
Sourcepub fn batch_process<F, T, E>(
&self,
names: &[String],
processor: F,
) -> BatchResult
pub fn batch_process<F, T, E>( &self, names: &[String], processor: F, ) -> BatchResult
Process multiple datasets with a given function
Examples found in repository?
examples/batch_operations_demo.rs (lines 114-120)
99fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
100 println!("Processing multiple cached files in batch...");
101
102 // Get list of cached files
103 let cached_files = batch_ops.list_cached_files().unwrap_or_default();
104
105 if cached_files.is_empty() {
106 println!("No cached files found for processing");
107 return;
108 }
109
110 println!("Found {} files to process", cached_files.len());
111
112 // Example 1: Validate file sizes
113 println!("\n1. File Size Validation:");
114 let result = batch_ops.batch_process(&cached_files, |name, data| {
115 if data.len() < 10 {
116 Err(format!("File {} too small ({} bytes)", name, data.len()))
117 } else {
118 Ok(data.len())
119 }
120 });
121
122 println!(" {}", result.summary());
123 if result.failure_count > 0 {
124 for (file, error) in &result.failures {
125 println!(" ⚠ {}: {}", file, error);
126 }
127 }
128
129 // Example 2: Content type detection
130 println!("\n2. Content Type Detection:");
131 let result = batch_ops.batch_process(&cached_files, |name, data| {
132 let content_type = detect_content_type(name, data);
133 println!(" {} -> {}", name, content_type);
134 Ok::<String, String>(content_type)
135 });
136
137 println!(" {}", result.summary());
138
139 // Example 3: Data integrity check
140 println!("\n3. Data Integrity Check:");
141 let result = batch_ops.batch_process(&cached_files, |name, data| {
142 // Simple check: ensure data is not all zeros
143 let all_zeros = data.iter().all(|&b| b == 0);
144 if all_zeros && data.len() > 100 {
145 Err("Suspicious: large file with all zeros".to_string())
146 } else {
147 let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
148 println!(" {} checksum: {}", name, checksum);
149 Ok(checksum)
150 }
151 });
152
153 println!(" {}", result.summary());
154}
Sourcepub fn cache_manager(&self) -> &CacheManager
pub fn cache_manager(&self) -> &CacheManager
Get access to the underlying cache manager
Sourcepub fn write_cached(&self, name: &str, data: &[u8]) -> Result<()>
pub fn write_cached(&self, name: &str, data: &[u8]) -> Result<()>
Write data to cache
Examples found in repository?
examples/batch_operations_demo.rs (line 68)
53fn setup_sample_cache_data(batch_ops: &BatchOperations) {
54 println!("Creating sample cached datasets...");
55
56 // Create various types of sample data
57 let sample_datasets = [
58 ("iris_processed.csv", create_csv_data()),
59 ("experiment_001.json", create_json_data()),
60 ("temp_file_001.tmp", create_binary_data(100)),
61 ("temp_file_002.tmp", create_binary_data(200)),
62 ("large_dataset.dat", create_binary_data(1024)),
63 ("model_weights.bin", create_binary_data(512)),
64 ("results_summary.txt", create_text_data()),
65 ];
66
67 for (name, data) in sample_datasets {
68 if let Err(e) = batch_ops.write_cached(name, &data) {
69 println!(" Warning: Failed to cache {}: {}", name, e);
70 } else {
71 println!(" ✓ Cached {} ({} bytes)", name, data.len());
72 }
73 }
74}
Sourcepub fn read_cached(&self, name: &str) -> Result<Vec<u8>>
pub fn read_cached(&self, name: &str) -> Result<Vec<u8>>
Read data from cache
Examples found in repository?
examples/batch_operations_demo.rs (line 214)
205fn show_final_cache_state(batch_ops: &BatchOperations) {
206 println!("Final cache contents:");
207
208 match batch_ops.list_cached_files() {
209 Ok(files) => {
210 if files.is_empty() {
211 println!(" Cache is empty");
212 } else {
213 for file in files {
214 if let Ok(data) = batch_ops.read_cached(&file) {
215 println!(" {} ({} bytes)", file, data.len());
216 }
217 }
218 }
219 }
220 Err(e) => println!(" Failed to list files: {}", e),
221 }
222
223 // Print detailed cache report
224 if let Err(e) = batch_ops.print_cache_report() {
225 println!("Failed to generate cache report: {}", e);
226 }
227}
Sourcepub fn list_cached_files(&self) -> Result<Vec<String>>
pub fn list_cached_files(&self) -> Result<Vec<String>>
List cached files
Examples found in repository?
examples/batch_operations_demo.rs (line 103)
99fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
100 println!("Processing multiple cached files in batch...");
101
102 // Get list of cached files
103 let cached_files = batch_ops.list_cached_files().unwrap_or_default();
104
105 if cached_files.is_empty() {
106 println!("No cached files found for processing");
107 return;
108 }
109
110 println!("Found {} files to process", cached_files.len());
111
112 // Example 1: Validate file sizes
113 println!("\n1. File Size Validation:");
114 let result = batch_ops.batch_process(&cached_files, |name, data| {
115 if data.len() < 10 {
116 Err(format!("File {} too small ({} bytes)", name, data.len()))
117 } else {
118 Ok(data.len())
119 }
120 });
121
122 println!(" {}", result.summary());
123 if result.failure_count > 0 {
124 for (file, error) in &result.failures {
125 println!(" ⚠ {}: {}", file, error);
126 }
127 }
128
129 // Example 2: Content type detection
130 println!("\n2. Content Type Detection:");
131 let result = batch_ops.batch_process(&cached_files, |name, data| {
132 let content_type = detect_content_type(name, data);
133 println!(" {} -> {}", name, content_type);
134 Ok::<String, String>(content_type)
135 });
136
137 println!(" {}", result.summary());
138
139 // Example 3: Data integrity check
140 println!("\n3. Data Integrity Check:");
141 let result = batch_ops.batch_process(&cached_files, |name, data| {
142 // Simple check: ensure data is not all zeros
143 let all_zeros = data.iter().all(|&b| b == 0);
144 if all_zeros && data.len() > 100 {
145 Err("Suspicious: large file with all zeros".to_string())
146 } else {
147 let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
148 println!(" {} checksum: {}", name, checksum);
149 Ok(checksum)
150 }
151 });
152
153 println!(" {}", result.summary());
154}
155
156fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
157 println!("Demonstrating selective cache cleanup...");
158
159 // Show current cache state
160 let initial_stats = batch_ops.get_cache_statistics().unwrap();
161 println!(
162 "Before cleanup: {} files, {}",
163 initial_stats.success_count,
164 format_bytes(initial_stats.total_bytes)
165 );
166
167 // Example 1: Clean up temporary files
168 println!("\n1. Cleaning up temporary files (*.tmp):");
169 match batch_ops.selective_cleanup(&["*.tmp"], None) {
170 Ok(result) => {
171 println!(" {}", result.summary());
172 if result.success_count > 0 {
173 println!(" Removed {} temporary files", result.success_count);
174 }
175 }
176 Err(e) => println!(" Failed: {}", e),
177 }
178
179 // Example 2: Clean up old files (demo with 0 days to show functionality)
180 println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
181 match batch_ops.selective_cleanup(&["*"], Some(0)) {
182 Ok(result) => {
183 println!(" {}", result.summary());
184 println!(" (Note: Using 0 days for demonstration - all files are 'old')");
185 }
186 Err(e) => println!(" Failed: {}", e),
187 }
188
189 // Show final cache state
190 let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
191 println!(
192 "\nAfter cleanup: {} files, {}",
193 final_stats.success_count,
194 format_bytes(final_stats.total_bytes)
195 );
196
197 let freed_space = initial_stats
198 .total_bytes
199 .saturating_sub(final_stats.total_bytes);
200 if freed_space > 0 {
201 println!("Space freed: {}", format_bytes(freed_space));
202 }
203}
204
205fn show_final_cache_state(batch_ops: &BatchOperations) {
206 println!("Final cache contents:");
207
208 match batch_ops.list_cached_files() {
209 Ok(files) => {
210 if files.is_empty() {
211 println!(" Cache is empty");
212 } else {
213 for file in files {
214 if let Ok(data) = batch_ops.read_cached(&file) {
215 println!(" {} ({} bytes)", file, data.len());
216 }
217 }
218 }
219 }
220 Err(e) => println!(" Failed to list files: {}", e),
221 }
222
223 // Print detailed cache report
224 if let Err(e) = batch_ops.print_cache_report() {
225 println!("Failed to generate cache report: {}", e);
226 }
227}
Sourcepub fn print_cache_report(&self) -> Result<()>
pub fn print_cache_report(&self) -> Result<()>
Print cache report
Examples found in repository?
examples/batch_operations_demo.rs (line 224)
205fn show_final_cache_state(batch_ops: &BatchOperations) {
206 println!("Final cache contents:");
207
208 match batch_ops.list_cached_files() {
209 Ok(files) => {
210 if files.is_empty() {
211 println!(" Cache is empty");
212 } else {
213 for file in files {
214 if let Ok(data) = batch_ops.read_cached(&file) {
215 println!(" {} ({} bytes)", file, data.len());
216 }
217 }
218 }
219 }
220 Err(e) => println!(" Failed to list files: {}", e),
221 }
222
223 // Print detailed cache report
224 if let Err(e) = batch_ops.print_cache_report() {
225 println!("Failed to generate cache report: {}", e);
226 }
227}
Sourcepub fn get_cache_statistics(&self) -> Result<BatchResult>
pub fn get_cache_statistics(&self) -> Result<BatchResult>
Get statistics about cached datasets
Examples found in repository?
examples/batch_operations_demo.rs (line 77)
76fn demonstrate_cache_statistics(batch_ops: &BatchOperations) {
77 match batch_ops.get_cache_statistics() {
78 Ok(result) => {
79 println!("{}", result.summary());
80 println!("Cache analysis:");
81 println!(" - Files processed: {}", result.success_count);
82 println!(" - Total cache size: {}", format_bytes(result.total_bytes));
83 println!(
84 " - Analysis time: {:.2}ms",
85 result.elapsed_time.as_millis()
86 );
87
88 if result.failure_count > 0 {
89 println!(" - Failed files: {}", result.failure_count);
90 for (file, error) in &result.failures {
91 println!(" • {}: {}", file, error);
92 }
93 }
94 }
95 Err(e) => println!("Failed to get cache statistics: {}", e),
96 }
97}
98
99fn demonstrate_batch_processing(batch_ops: &BatchOperations) {
100 println!("Processing multiple cached files in batch...");
101
102 // Get list of cached files
103 let cached_files = batch_ops.list_cached_files().unwrap_or_default();
104
105 if cached_files.is_empty() {
106 println!("No cached files found for processing");
107 return;
108 }
109
110 println!("Found {} files to process", cached_files.len());
111
112 // Example 1: Validate file sizes
113 println!("\n1. File Size Validation:");
114 let result = batch_ops.batch_process(&cached_files, |name, data| {
115 if data.len() < 10 {
116 Err(format!("File {} too small ({} bytes)", name, data.len()))
117 } else {
118 Ok(data.len())
119 }
120 });
121
122 println!(" {}", result.summary());
123 if result.failure_count > 0 {
124 for (file, error) in &result.failures {
125 println!(" ⚠ {}: {}", file, error);
126 }
127 }
128
129 // Example 2: Content type detection
130 println!("\n2. Content Type Detection:");
131 let result = batch_ops.batch_process(&cached_files, |name, data| {
132 let content_type = detect_content_type(name, data);
133 println!(" {} -> {}", name, content_type);
134 Ok::<String, String>(content_type)
135 });
136
137 println!(" {}", result.summary());
138
139 // Example 3: Data integrity check
140 println!("\n3. Data Integrity Check:");
141 let result = batch_ops.batch_process(&cached_files, |name, data| {
142 // Simple check: ensure data is not all zeros
143 let all_zeros = data.iter().all(|&b| b == 0);
144 if all_zeros && data.len() > 100 {
145 Err("Suspicious: large file with all zeros".to_string())
146 } else {
147 let checksum = data.iter().map(|&b| b as u32).sum::<u32>();
148 println!(" {} checksum: {}", name, checksum);
149 Ok(checksum)
150 }
151 });
152
153 println!(" {}", result.summary());
154}
155
156fn demonstrate_selective_cleanup(batch_ops: &BatchOperations) {
157 println!("Demonstrating selective cache cleanup...");
158
159 // Show current cache state
160 let initial_stats = batch_ops.get_cache_statistics().unwrap();
161 println!(
162 "Before cleanup: {} files, {}",
163 initial_stats.success_count,
164 format_bytes(initial_stats.total_bytes)
165 );
166
167 // Example 1: Clean up temporary files
168 println!("\n1. Cleaning up temporary files (*.tmp):");
169 match batch_ops.selective_cleanup(&["*.tmp"], None) {
170 Ok(result) => {
171 println!(" {}", result.summary());
172 if result.success_count > 0 {
173 println!(" Removed {} temporary files", result.success_count);
174 }
175 }
176 Err(e) => println!(" Failed: {}", e),
177 }
178
179 // Example 2: Clean up old files (demo with 0 days to show functionality)
180 println!("\n2. Age-based cleanup (files older than 0 days - for demo):");
181 match batch_ops.selective_cleanup(&["*"], Some(0)) {
182 Ok(result) => {
183 println!(" {}", result.summary());
184 println!(" (Note: Using 0 days for demonstration - all files are 'old')");
185 }
186 Err(e) => println!(" Failed: {}", e),
187 }
188
189 // Show final cache state
190 let final_stats = batch_ops.get_cache_statistics().unwrap_or_default();
191 println!(
192 "\nAfter cleanup: {} files, {}",
193 final_stats.success_count,
194 format_bytes(final_stats.total_bytes)
195 );
196
197 let freed_space = initial_stats
198 .total_bytes
199 .saturating_sub(final_stats.total_bytes);
200 if freed_space > 0 {
201 println!("Space freed: {}", format_bytes(freed_space));
202 }
203}
Auto Trait Implementations§
impl !Freeze for BatchOperations
impl !RefUnwindSafe for BatchOperations
impl Send for BatchOperations
impl !Sync for BatchOperations
impl Unpin for BatchOperations
impl UnwindSafe for BatchOperations
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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