crush-core 0.3.0

High-performance parallel compression library core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Cancellation support for compression operations
//!
//! This module provides thread-safe cancellation mechanisms for gracefully
//! stopping compression/decompression operations in response to user signals
//! (e.g., Ctrl+C) or programmatic cancellation requests.

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

/// Thread-safe cancellation signal for compression operations.
///
/// This trait provides a lock-free way to signal cancellation to worker threads
/// and check cancellation state without blocking. Implementations must be
/// async-signal-safe (can be called from signal handlers).
///
/// # Thread Safety
///
/// All methods are safe to call concurrently from multiple threads.
/// Implementations must use atomic operations to ensure lock-freedom.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use crush_core::cancel::{CancellationToken, AtomicCancellationToken};
///
/// let token = Arc::new(AtomicCancellationToken::new());
/// let token_worker = Arc::clone(&token);
///
/// // Worker thread checks cancellation
/// std::thread::spawn(move || {
///     while !token_worker.is_cancelled() {
///         // Do work...
///     }
/// });
///
/// // Signal handler or main thread cancels
/// token.cancel();
/// ```
pub trait CancellationToken: Send + Sync {
    /// Check if cancellation has been requested.
    ///
    /// This method is lock-free, async-signal-safe, and very fast (<10ns).
    /// It can be called from signal handlers and hot loops without concern.
    ///
    /// # Returns
    ///
    /// `true` if cancellation has been requested, `false` otherwise.
    fn is_cancelled(&self) -> bool;

    /// Request cancellation.
    ///
    /// This method is idempotent - calling it multiple times has the same
    /// effect as calling it once. Safe to call from signal handlers.
    ///
    /// # Thread Safety
    ///
    /// Multiple threads can call this concurrently. The first call to set
    /// the flag "wins", but all calls succeed.
    fn cancel(&self);

    /// Reset the cancellation state to not-cancelled.
    ///
    /// This allows reusing the same token for multiple sequential operations.
    /// NOT async-signal-safe - do not call from signal handlers.
    fn reset(&self);
}

/// Standard implementation of `CancellationToken` using `AtomicBool`.
///
/// This is the recommended implementation for most use cases.
pub struct AtomicCancellationToken {
    cancelled: AtomicBool,
}

impl AtomicCancellationToken {
    /// Create a new cancellation token in the not-cancelled state.
    #[must_use]
    pub fn new() -> Self {
        Self {
            cancelled: AtomicBool::new(false),
        }
    }
}

impl Default for AtomicCancellationToken {
    fn default() -> Self {
        Self::new()
    }
}

impl CancellationToken for AtomicCancellationToken {
    fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    fn reset(&self) {
        self.cancelled.store(false, Ordering::SeqCst);
    }
}

/// Tracks resources created during compression/decompression for guaranteed cleanup.
///
/// Uses RAII pattern - resources are automatically cleaned up when dropped unless
/// marked as complete. This ensures incomplete output files are deleted if an
/// operation is cancelled or fails.
///
/// # Thread Safety
///
/// All methods use interior mutability and are safe to call from multiple threads.
///
/// # Example
///
/// ```no_run
/// use crush_core::cancel::ResourceTracker;
/// use std::path::PathBuf;
///
/// let tracker = ResourceTracker::new();
///
/// // Register the output file to be cleaned up if operation fails
/// tracker.register_output(PathBuf::from("output.crush"));
///
/// // Register temporary files that should always be deleted
/// tracker.register_temp_file(PathBuf::from("temp.dat"));
///
/// // ... do compression work ...
///
/// // If successful, mark complete to keep the output file
/// tracker.mark_complete();
///
/// // Drop will clean up temp files but keep output (marked complete)
/// ```
///
/// # Cleanup Behavior
///
/// - **Temp files**: Always deleted on drop
/// - **Output file**: Deleted on drop UNLESS `mark_complete()` was called
/// - **On panic**: Drop runs, ensuring cleanup even during unwinding
pub struct ResourceTracker {
    output_path: Mutex<Option<PathBuf>>,
    temp_files: Mutex<Vec<PathBuf>>,
    is_complete: AtomicBool,
}

impl ResourceTracker {
    /// Create a new resource tracker.
    #[must_use]
    pub fn new() -> Self {
        Self {
            output_path: Mutex::new(None),
            temp_files: Mutex::new(Vec::new()),
            is_complete: AtomicBool::new(false),
        }
    }

    /// Register the output file path to be cleaned up if the operation doesn't complete.
    ///
    /// The output file will be deleted on drop unless `mark_complete()` is called.
    /// Only one output file can be registered (subsequent calls replace the previous).
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the output file
    pub fn register_output(&self, path: PathBuf) {
        if let Ok(mut output) = self.output_path.lock() {
            *output = Some(path);
        }
    }

    /// Register a temporary file that should always be deleted on cleanup.
    ///
    /// Temporary files are always deleted on drop, regardless of completion status.
    /// Multiple temporary files can be registered.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the temporary file
    pub fn register_temp_file(&self, path: PathBuf) {
        if let Ok(mut temps) = self.temp_files.lock() {
            temps.push(path);
        }
    }

    /// Mark the operation as successfully completed, preventing output file deletion.
    ///
    /// Call this after the operation succeeds to keep the output file.
    /// If not called, the output file will be deleted on drop (cleanup on failure).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use crush_core::cancel::ResourceTracker;
    /// # use std::path::PathBuf;
    /// let tracker = ResourceTracker::new();
    /// tracker.register_output(PathBuf::from("output.dat"));
    ///
    /// // ... do work ...
    ///
    /// if work_succeeded() {
    ///     tracker.mark_complete(); // Keep the output file
    /// }
    /// // If work failed, drop will delete the output file
    /// # fn work_succeeded() -> bool { true }
    /// ```
    pub fn mark_complete(&self) {
        self.is_complete.store(true, Ordering::SeqCst);
    }

    /// Clean up all tracked resources.
    ///
    /// # Errors
    ///
    /// Returns an error if file deletion fails (permissions, file in use, etc.).
    /// Returns the first error encountered if multiple deletions fail.
    pub fn cleanup_all(&self) -> std::io::Result<()> {
        // Always delete temp files
        if let Ok(temps) = self.temp_files.lock() {
            for temp in temps.iter() {
                if temp.exists() {
                    std::fs::remove_file(temp)?;
                }
            }
        }

        // Delete output file only if operation not complete
        if !self.is_complete.load(Ordering::SeqCst) {
            if let Ok(output) = self.output_path.lock() {
                if let Some(path) = output.as_ref() {
                    if path.exists() {
                        std::fs::remove_file(path)?;
                    }
                }
            }
        }

        Ok(())
    }
}

impl Default for ResourceTracker {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ResourceTracker {
    fn drop(&mut self) {
        if !self.is_complete.load(Ordering::SeqCst) {
            // Operation did not complete - clean up everything
            // Ignore errors in Drop - best effort cleanup
            let _ = self.cleanup_all();
        }
    }
}

#[cfg(test)]
#[allow(clippy::panic_in_result_fn)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn new_token_not_cancelled() {
        let token = AtomicCancellationToken::new();
        assert!(!token.is_cancelled());
    }

    #[test]
    fn cancel_sets_flag() {
        let token = AtomicCancellationToken::new();
        token.cancel();
        assert!(token.is_cancelled());
    }

    #[test]
    fn cancel_is_idempotent() {
        let token = AtomicCancellationToken::new();
        token.cancel();
        token.cancel();
        token.cancel();
        assert!(token.is_cancelled());
    }

    #[test]
    fn reset_clears_cancellation() {
        let token = AtomicCancellationToken::new();
        token.cancel();
        assert!(token.is_cancelled());
        token.reset();
        assert!(!token.is_cancelled());
    }

    #[test]
    fn default_creates_uncancelled_token() {
        let token = AtomicCancellationToken::default();
        assert!(!token.is_cancelled());
    }

    // ResourceTracker tests
    #[test]
    fn new_resource_tracker_is_empty() {
        let tracker = ResourceTracker::new();
        // Verify cleanup_all succeeds with no registered resources
        assert!(tracker.cleanup_all().is_ok());
    }

    #[test]
    fn resource_tracker_default() {
        let tracker = ResourceTracker::default();
        assert!(tracker.cleanup_all().is_ok());
    }

    #[test]
    fn register_output_and_mark_complete() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let output_path = dir.path().join("output.txt");

        // Create the output file
        fs::write(&output_path, b"test data")?;
        assert!(output_path.exists());

        let tracker = ResourceTracker::new();
        tracker.register_output(output_path.clone());
        tracker.mark_complete();

        // Clean up - file should NOT be deleted (marked complete)
        tracker.cleanup_all()?;
        assert!(
            output_path.exists(),
            "Completed output file should not be deleted"
        );

        Ok(())
    }

    #[test]
    fn register_output_without_complete_deletes() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let output_path = dir.path().join("output.txt");

        // Create the output file
        fs::write(&output_path, b"test data")?;
        assert!(output_path.exists());

        let tracker = ResourceTracker::new();
        tracker.register_output(output_path.clone());

        // Clean up without marking complete - file SHOULD be deleted
        tracker.cleanup_all()?;
        assert!(
            !output_path.exists(),
            "Incomplete output file should be deleted"
        );

        Ok(())
    }

    #[test]
    fn register_temp_file_always_deletes() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let temp_path = dir.path().join("temp.txt");

        // Create the temp file
        fs::write(&temp_path, b"temp data")?;
        assert!(temp_path.exists());

        let tracker = ResourceTracker::new();
        tracker.register_temp_file(temp_path.clone());
        tracker.mark_complete(); // Even if marked complete

        // Clean up - temp file should ALWAYS be deleted
        tracker.cleanup_all()?;
        assert!(!temp_path.exists(), "Temp file should always be deleted");

        Ok(())
    }

    #[test]
    fn register_multiple_temp_files() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let temp1 = dir.path().join("temp1.txt");
        let temp2 = dir.path().join("temp2.txt");
        let temp3 = dir.path().join("temp3.txt");

        // Create temp files
        fs::write(&temp1, b"temp1")?;
        fs::write(&temp2, b"temp2")?;
        fs::write(&temp3, b"temp3")?;

        let tracker = ResourceTracker::new();
        tracker.register_temp_file(temp1.clone());
        tracker.register_temp_file(temp2.clone());
        tracker.register_temp_file(temp3.clone());

        // Clean up - all temp files should be deleted
        tracker.cleanup_all()?;
        assert!(!temp1.exists());
        assert!(!temp2.exists());
        assert!(!temp3.exists());

        Ok(())
    }

    #[test]
    fn drop_cleans_up_incomplete_output() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let output_path = dir.path().join("output.txt");

        // Create the output file
        fs::write(&output_path, b"test data")?;
        assert!(output_path.exists());

        {
            let tracker = ResourceTracker::new();
            tracker.register_output(output_path.clone());
            // Drop without marking complete
        }

        // File should be deleted by Drop
        assert!(
            !output_path.exists(),
            "Drop should delete incomplete output"
        );

        Ok(())
    }

    #[test]
    fn drop_keeps_completed_output() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let output_path = dir.path().join("output.txt");

        // Create the output file
        fs::write(&output_path, b"test data")?;

        {
            let tracker = ResourceTracker::new();
            tracker.register_output(output_path.clone());
            tracker.mark_complete();
            // Drop with completion
        }

        // File should NOT be deleted
        assert!(output_path.exists(), "Drop should keep completed output");

        Ok(())
    }

    #[test]
    fn cleanup_nonexistent_files_succeeds() {
        use tempfile::TempDir;

        let dir = TempDir::new().unwrap();
        let fake_path = dir.path().join("does_not_exist.txt");

        let tracker = ResourceTracker::new();
        tracker.register_output(fake_path.clone());
        tracker.register_temp_file(fake_path);

        // Cleanup should succeed even if files don't exist
        assert!(tracker.cleanup_all().is_ok());
    }

    #[test]
    fn replace_output_registration() -> std::io::Result<()> {
        use std::fs;
        use tempfile::TempDir;

        let dir = TempDir::new()?;
        let output1 = dir.path().join("output1.txt");
        let output2 = dir.path().join("output2.txt");

        fs::write(&output1, b"data1")?;
        fs::write(&output2, b"data2")?;

        let tracker = ResourceTracker::new();
        tracker.register_output(output1.clone());
        tracker.register_output(output2.clone()); // Replace first registration

        // Only the second output should be deleted
        tracker.cleanup_all()?;

        assert!(
            output1.exists(),
            "First output should not be tracked after replacement"
        );
        assert!(!output2.exists(), "Second output should be deleted");

        Ok(())
    }
}