hexz_core/ops/write.rs
1//! Low-level write operations for Hexz snapshots.
2//!
3//! This module provides the foundational building blocks for writing compressed,
4//! encrypted, and deduplicated blocks to snapshot files. These functions implement
5//! the core write semantics used by higher-level pack operations while remaining
6//! independent of the packing workflow.
7//!
8//! # Module Purpose
9//!
10//! The write operations module serves as the bridge between the high-level packing
11//! pipeline and the raw file I/O layer. It encapsulates the logic for:
12//!
13//! - **Block Writing**: Transform raw chunks into compressed, encrypted blocks
14//! - **Deduplication**: Detect and eliminate redundant blocks via content hashing
15//! - **Zero Optimization**: Handle sparse data efficiently without storage
16//! - **Metadata Generation**: Create BlockInfo descriptors for index building
17//!
18//! # Design Philosophy
19//!
20//! These functions are designed to be composable, stateless, and easily testable.
21//! They operate on raw byte buffers and writers without knowledge of the broader
22//! packing context (progress reporting, stream management, index organization).
23//!
24//! This separation enables:
25//! - Unit testing of write logic in isolation
26//! - Reuse in different packing strategies (single-stream, multi-threaded, streaming)
27//! - Clear separation of concerns (write vs. orchestration)
28//!
29//! # Write Operation Semantics
30//!
31//! ## Block Transformation Pipeline
32//!
33//! Each block undergoes a multi-stage transformation before being written:
34//!
35//! ```text
36//! Raw Chunk (input)
37//! ↓
38//! ┌────────────────┐
39//! │ Compression │ → Compress using LZ4 or Zstd
40//! └────────────────┘ (reduces size, increases CPU)
41//! ↓
42//! ┌────────────────┐
43//! │ Encryption │ → Optional AES-256-GCM with block_idx nonce
44//! └────────────────┘ (confidentiality + integrity)
45//! ↓
46//! ┌────────────────┐
47//! │ Checksum │ → CRC32 of final data (fast integrity check)
48//! └────────────────┘
49//! ↓
50//! ┌────────────────┐
51//! │ Deduplication │ → BLAKE3 hash lookup (skip write if duplicate)
52//! └────────────────┘ (disabled for encrypted data)
53//! ↓
54//! ┌────────────────┐
55//! │ Write │ → Append to output file at current offset
56//! └────────────────┘
57//! ↓
58//! BlockInfo (metadata: offset, length, checksum)
59//! ```
60//!
61//! ## Write Behavior and Atomicity
62//!
63//! ### Single Block Writes
64//!
65//! Individual block writes via [`write_block`] are atomic with respect to the
66//! underlying file system's write atomicity guarantees:
67//!
68//! - **Buffered writes**: Data passes through OS page cache
69//! - **No fsync**: Writes are not flushed to disk until the writer is closed
70//! - **Partial write handling**: Writer's `write_all` ensures complete writes or error
71//! - **Crash behavior**: Partial blocks may be written if process crashes mid-write
72//!
73//! ### Deduplication State
74//!
75//! The deduplication map is maintained externally (by the caller). This design allows:
76//! - **Flexibility**: Caller controls when/if to enable deduplication
77//! - **Memory control**: Map lifetime and size managed by orchestration layer
78//! - **Consistency**: Map updates are immediately visible to subsequent writes
79//!
80//! ### Offset Management
81//!
82//! The `current_offset` parameter is updated atomically after each successful write.
83//! This ensures:
84//! - **Sequential allocation**: Blocks are laid out contiguously in file
85//! - **No gaps**: Every byte between header and master index is utilized
86//! - **Predictable layout**: Physical offset increases monotonically
87//!
88//! ## Block Allocation Strategy
89//!
90//! Blocks are allocated sequentially in the order they are written:
91//!
92//! ```text
93//! File Layout:
94//! ┌──────────────┬──────────┬──────────┬──────────┬─────────────┐
95//! │ Header (512B)│ Block 0 │ Block 1 │ Block 2 │ Index Pages │
96//! └──────────────┴──────────┴──────────┴──────────┴─────────────┘
97//! ↑ ↑ ↑ ↑
98//! 0 512 512+len0 512+len0+len1
99//!
100//! current_offset advances after each write:
101//! - Initial: 512 (after header)
102//! - After Block 0: 512 + len0
103//! - After Block 1: 512 + len0 + len1
104//! - After Block 2: 512 + len0 + len1 + len2
105//! ```
106//!
107//! ### Deduplication Impact
108//!
109//! When deduplication detects a duplicate block:
110//! - **No physical write**: Block is not written to disk
111//! - **Offset reuse**: BlockInfo references the existing block's offset
112//! - **Space savings**: Multiple logical blocks share one physical block
113//! - **Transparency**: Readers cannot distinguish between deduplicated and unique blocks
114//!
115//! Example with deduplication:
116//!
117//! ```text
118//! Logical Blocks: [A, B, A, C, B]
119//! Physical Blocks: [A, B, C]
120//! ↑ ↑ ↑
121//! │ │ └─ Block 3 (unique)
122//! │ └─ Block 1 (unique)
123//! └─ Block 0 (unique)
124//!
125//! BlockInfo for logical block 2: offset = offset_of(A), length = len(A)
126//! BlockInfo for logical block 4: offset = offset_of(B), length = len(B)
127//! ```
128//!
129//! ## Buffer Management
130//!
131//! This module does not perform explicit buffer management. All buffers are:
132//!
133//! - **Caller-allocated**: Input chunks are provided by caller
134//! - **Temporary allocations**: Compression/encryption output is allocated, then consumed
135//! - **No pooling**: Each operation allocates fresh buffers (GC handles reclamation)
136//!
137//! For high-performance scenarios, callers should consider:
138//! - Reusing chunk buffers across iterations
139//! - Using buffer pools for compression output (requires refactoring)
140//! - Batch writes to amortize allocation overhead
141//!
142//! ## Flush Behavior
143//!
144//! Functions in this module do NOT flush data to disk. Flushing is the caller's
145//! responsibility and typically occurs:
146//!
147//! - After writing all blocks and indices (in [`pack_snapshot`](crate::ops::pack::pack_snapshot))
148//! - Before closing the output file
149//! - Never during block writing (to maximize write batching)
150//!
151//! This design allows the OS to batch writes for optimal I/O performance.
152//!
153//! # Error Handling and Recovery
154//!
155//! ## Error Categories
156//!
157//! Write operations can fail for several reasons:
158//!
159//! ### I/O Errors
160//!
161//! - **Disk full**: No space for compressed block (`ENOSPC`)
162//! - **Permission denied**: Writer lacks write permission (`EACCES`)
163//! - **Device error**: Hardware failure, I/O timeout (`EIO`)
164//!
165//! These surface as `Error::Io` wrapping the underlying `std::io::Error`.
166//!
167//! ### Compression Errors
168//!
169//! - **Compression failure**: Compressor returns error (rare, usually indicates bug)
170//! - **Incompressible data**: Not an error; stored with expansion
171//!
172//! These surface as `Error::Compression`.
173//!
174//! ### Encryption Errors
175//!
176//! - **Cipher initialization failure**: Invalid state (should not occur in practice)
177//! - **Encryption failure**: Crypto operation fails (indicates library bug)
178//!
179//! These surface as `Error::Encryption`.
180//!
181//! ## Error Recovery
182//!
183//! Write operations provide **no automatic recovery**. On error:
184//!
185//! - **Function returns immediately**: No cleanup or rollback
186//! - **File state undefined**: Partial data may be written
187//! - **Caller responsibility**: Must handle error and clean up
188//!
189//! Typical error handling pattern in pack operations:
190//!
191//! ```text
192//! match write_block_simple(...) {
193//! Ok(info) => {
194//! // Success: Add info to index, continue
195//! }
196//! Err(e) => {
197//! // Failure: Log error, delete partial output file, return error to caller
198//! std::fs::remove_file(output)?;
199//! return Err(e);
200//! }
201//! }
202//! ```
203//!
204//! ## Partial Write Handling
205//!
206//! The underlying `Write::write_all` method ensures atomic writes of complete blocks:
207//!
208//! - **Success**: Entire block written, offset updated
209//! - **Failure**: Partial write may occur, but error is returned
210//! - **No retry**: Caller must handle retries if desired
211//!
212//! # Performance Characteristics
213//!
214//! ## Write Throughput
215//!
216//! Block write performance is dominated by compression:
217//!
218//! - **LZ4**: ~2 GB/s (minimal overhead)
219//! - **Zstd level 3**: ~200-500 MB/s (depends on data)
220//! - **Encryption**: ~1-2 GB/s (hardware AES-NI)
221//! - **BLAKE3 hashing**: ~3200 MB/s (for deduplication)
222//!
223//! Typical bottleneck: Compression CPU time.
224//!
225//! ## Deduplication Overhead
226//!
227//! BLAKE3 hashing adds ~5-10% overhead to write operations:
228//!
229//! - **Hash computation**: ~3200 MB/s throughput (BLAKE3 tree-hashed)
230//! - **HashMap lookup**: O(1) average, ~50-100 ns per lookup
231//! - **Memory usage**: ~48 bytes per unique block
232//!
233//! For datasets with <10% duplication, deduplication overhead may exceed savings.
234//! Consider disabling dedup for unique data.
235//!
236//! ## Zero Block Detection
237//!
238//! [`is_zero_chunk`] uses SIMD-optimized comparison on modern CPUs:
239//!
240//! - **Throughput**: ~10-20 GB/s (memory bandwidth limited)
241//! - **Overhead**: Negligible (~5-10 cycles per 64-byte cache line)
242//!
243//! Zero detection is always worth enabling for sparse data.
244//!
245//! # Memory Usage
246//!
247//! Per-block memory allocation:
248//!
249//! - **Input chunk**: Caller-provided (typically 64 KiB)
250//! - **Compression output**: ~1.5× chunk size worst case (incompressible data)
251//! - **Encryption output**: compression_size + 28 bytes (AES-GCM overhead)
252//! - **Dedup hash**: 32 bytes (BLAKE3 digest)
253//!
254//! Total temporary allocation per write: ~100-150 KiB (released immediately after write).
255//!
256//! # Examples
257//!
258//! See individual function documentation for usage examples.
259//!
260//! # Future Enhancements
261//!
262//! Potential improvements to write operations:
263//!
264//! - **Buffer pooling**: Reuse compression/encryption buffers to reduce allocation overhead
265//! - **Async I/O**: Use `tokio` or `io_uring` for overlapped writes
266//! - **Parallel writes**: Write multiple blocks concurrently (requires coordination)
267//! - **Write-ahead logging**: Enable atomic commits for crash safety
268
269use hexz_common::Result;
270use std::collections::HashMap;
271use std::io::Write;
272
273use crate::algo::compression::Compressor;
274use crate::algo::encryption::Encryptor;
275use crate::algo::hashing::ContentHasher;
276use crate::format::index::BlockInfo;
277
278/// Writes a compressed and optionally encrypted block to the output stream.
279///
280/// This function implements the complete block transformation pipeline: compression,
281/// optional encryption, checksum computation, deduplication, and physical write.
282/// It returns a `BlockInfo` descriptor suitable for inclusion in an index page.
283///
284/// # Transformation Pipeline
285///
286/// 1. **Compression**: Compress raw chunk using provided compressor (LZ4 or Zstd)
287/// 2. **Encryption** (optional): Encrypt compressed data with AES-256-GCM using block_idx as nonce
288/// 3. **Checksum**: Compute CRC32 of final data for integrity verification
289/// 4. **Deduplication** (optional, not for encrypted):
290/// - Compute BLAKE3 hash of final data
291/// - Check dedup_map for existing block with same hash
292/// - If found: Reuse existing offset, skip write
293/// - If new: Write block, record offset in dedup_map
294/// 5. **Write**: Append final data to output at current_offset
295/// 6. **Metadata**: Create and return BlockInfo with offset, length, checksum
296///
297/// # Parameters
298///
299/// - `out`: Output writer implementing `Write` trait
300/// - Typically a `File` or `BufWriter<File>`
301/// - Must support `write_all` for atomic block writes
302///
303/// - `chunk`: Uncompressed chunk data (raw bytes)
304/// - Typical size: 16 KiB - 256 KiB (configurable)
305/// - Must not be empty (undefined behavior for zero-length chunks)
306///
307/// - `block_idx`: Global block index (zero-based)
308/// - Used as encryption nonce (must be unique per snapshot)
309/// - Monotonically increases across all streams
310/// - Must not reuse indices within same encrypted snapshot (breaks security)
311///
312/// - `current_offset`: Mutable reference to current physical file offset
313/// - Updated after successful write: `*current_offset += bytes_written`
314/// - Not updated on error (file state undefined)
315/// - Not updated for deduplicated blocks (reuses existing offset)
316///
317/// - `dedup_map`: Optional deduplication hash table
318/// - `Some(&mut map)`: Enable dedup, use this map
319/// - `None`: Disable dedup, always write
320/// - Ignored if `encryptor.is_some()` (encryption prevents dedup)
321/// - Maps BLAKE3 hash → physical offset of first occurrence
322///
323/// - `compressor`: Compression algorithm implementation
324/// - Typically `Lz4Compressor` or `ZstdCompressor`
325/// - Must implement [`Compressor`] trait
326///
327/// - `encryptor`: Optional encryption implementation
328/// - `Some(enc)`: Encrypt compressed data with AES-256-GCM
329/// - `None`: Store compressed data unencrypted
330/// - Must implement [`Encryptor`] trait
331///
332/// - `hasher`: Content hasher for deduplication
333/// - Typically `Blake3Hasher`
334/// - Must implement [`ContentHasher`] trait
335/// - Used only when dedup_map is Some and encryptor is None
336///
337/// - `hash_buf`: Reusable buffer for hash output (must be ≥32 bytes)
338/// - Avoids allocation on every hash computation
339/// - Only used when dedup is enabled
340///
341/// # Returns
342///
343/// - `Ok(BlockInfo)`: Block written successfully, metadata returned
344/// - `offset`: Physical byte offset where block starts
345/// - `length`: Compressed (and encrypted) size in bytes
346/// - `logical_len`: Original uncompressed size
347/// - `checksum`: CRC32 of final data (compressed + encrypted)
348///
349/// - `Err(Error::Io)`: I/O error during write
350/// - Disk full, permission denied, device error
351/// - File state undefined (partial write may have occurred)
352///
353/// - `Err(Error::Compression)`: Compression failed
354/// - Rare; usually indicates library bug or corrupted input
355///
356/// - `Err(Error::Encryption)`: Encryption failed
357/// - Rare; usually indicates crypto library bug
358///
359/// # Examples
360///
361/// ## Basic Usage (No Encryption, No Dedup)
362///
363/// ```no_run
364/// use hexz_core::ops::write::write_block;
365/// use hexz_core::algo::compression::Lz4Compressor;
366/// use hexz_core::algo::hashing::blake3::Blake3Hasher;
367/// use std::fs::File;
368///
369/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
370/// let mut out = File::create("output.hxz")?;
371/// let mut offset = 512u64; // After header
372/// let chunk = vec![0x42; 65536]; // 64 KiB of data
373/// let compressor = Lz4Compressor::new();
374/// let hasher = Blake3Hasher;
375/// let mut hash_buf = [0u8; 32];
376///
377/// let info = write_block(
378/// &mut out,
379/// &chunk,
380/// 0, // block_idx
381/// &mut offset,
382/// None, // No dedup
383/// &compressor,
384/// None, // No encryption
385/// &hasher,
386/// &mut hash_buf,
387/// )?;
388///
389/// println!("Block written at offset {}, size {}", info.offset, info.length);
390/// # Ok(())
391/// # }
392/// ```
393///
394/// ## With Deduplication
395///
396/// ```no_run
397/// use hexz_core::ops::write::write_block;
398/// use hexz_core::algo::compression::Lz4Compressor;
399/// use hexz_core::algo::hashing::blake3::Blake3Hasher;
400/// use std::collections::HashMap;
401/// use std::fs::File;
402///
403/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
404/// let mut out = File::create("output.hxz")?;
405/// let mut offset = 512u64;
406/// let mut dedup_map: HashMap<[u8; 32], u64> = HashMap::new();
407/// let compressor = Lz4Compressor::new();
408/// let hasher = Blake3Hasher;
409/// let mut hash_buf = [0u8; 32];
410///
411/// // Write first block
412/// let chunk1 = vec![0xAA; 65536];
413/// let info1 = write_block(
414/// &mut out,
415/// &chunk1,
416/// 0,
417/// &mut offset,
418/// Some(&mut dedup_map),
419/// &compressor,
420/// None,
421/// &hasher,
422/// &mut hash_buf,
423/// )?;
424/// println!("Block 0: offset={}, written", info1.offset);
425///
426/// // Write duplicate block (same content)
427/// let chunk2 = vec![0xAA; 65536];
428/// let info2 = write_block(
429/// &mut out,
430/// &chunk2,
431/// 1,
432/// &mut offset,
433/// Some(&mut dedup_map),
434/// &compressor,
435/// None,
436/// &hasher,
437/// &mut hash_buf,
438/// )?;
439/// println!("Block 1: offset={}, deduplicated (no write)", info2.offset);
440/// assert_eq!(info1.offset, info2.offset); // Same offset, block reused
441/// # Ok(())
442/// # }
443/// ```
444///
445/// ## With Encryption
446///
447/// ```no_run
448/// use hexz_core::ops::write::write_block;
449/// use hexz_core::algo::compression::Lz4Compressor;
450/// use hexz_core::algo::encryption::AesGcmEncryptor;
451/// use hexz_core::algo::hashing::blake3::Blake3Hasher;
452/// use hexz_common::crypto::KeyDerivationParams;
453/// use std::fs::File;
454///
455/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
456/// let mut out = File::create("output.hxz")?;
457/// let mut offset = 512u64;
458/// let compressor = Lz4Compressor::new();
459/// let hasher = Blake3Hasher;
460/// let mut hash_buf = [0u8; 32];
461///
462/// // Initialize encryptor
463/// let params = KeyDerivationParams::default();
464/// let encryptor = AesGcmEncryptor::new(
465/// b"strong_password",
466/// ¶ms.salt,
467/// params.iterations,
468/// )?;
469///
470/// let chunk = vec![0x42; 65536];
471/// let info = write_block(
472/// &mut out,
473/// &chunk,
474/// 0,
475/// &mut offset,
476/// None, // Dedup disabled (encryption prevents it)
477/// &compressor,
478/// Some(&encryptor),
479/// &hasher,
480/// &mut hash_buf,
481/// )?;
482///
483/// println!("Encrypted block: offset={}, length={}", info.offset, info.length);
484/// # Ok(())
485/// # }
486/// ```
487///
488/// # Performance
489///
490/// - **Compression**: Dominates runtime (~2 GB/s LZ4, ~500 MB/s Zstd)
491/// - **Encryption**: ~1-2 GB/s (hardware AES-NI)
492/// - **Hashing**: ~3200 MB/s (BLAKE3 for dedup)
493/// - **I/O**: Typically not bottleneck (buffered writes, ~3 GB/s sequential)
494///
495/// # Deduplication Effectiveness
496///
497/// Deduplication is most effective when:
498/// - **Fixed-size blocks**: Same content → same boundaries → same hash
499/// - **Unencrypted**: Encryption produces unique ciphertext per block (different nonces)
500/// - **Redundant data**: Duplicate files, repeated patterns, copy-on-write filesystems
501///
502/// Deduplication is ineffective when:
503/// - **Content-defined chunking**: Small shifts cause different boundaries
504/// - **Compressed input**: Pre-compressed data has low redundancy
505/// - **Unique data**: No duplicate blocks to detect
506///
507/// # Security Considerations
508///
509/// ## Block Index as Nonce
510///
511/// When encrypting, `block_idx` is used as part of the AES-GCM nonce. **CRITICAL**:
512/// - Never reuse `block_idx` values within the same encrypted snapshot
513/// - Nonce reuse breaks AES-GCM security (allows plaintext recovery)
514/// - Each logical block must have a unique index
515///
516/// ## Deduplication and Encryption
517///
518/// Deduplication is automatically disabled when encrypting because:
519/// - Each block has a unique nonce → unique ciphertext
520/// - BLAKE3(ciphertext1) ≠ BLAKE3(ciphertext2) even if plaintext is identical
521/// - Attempting dedup with encryption wastes CPU (hashing) without space savings
522///
523/// # Thread Safety
524///
525/// This function is **not thread-safe** with respect to the output writer:
526/// - Concurrent calls with the same `out` writer will interleave writes (corruption)
527/// - Concurrent calls with different writers to the same file will corrupt file
528///
529/// For parallel writing, use separate output files or implement external synchronization.
530///
531/// The dedup_map must also be externally synchronized for concurrent access.
532#[allow(clippy::too_many_arguments)]
533pub fn write_block<W: Write>(
534 out: &mut W,
535 chunk: &[u8],
536 block_idx: u64,
537 current_offset: &mut u64,
538 dedup_map: Option<&mut HashMap<[u8; 32], u64>>,
539 compressor: &dyn Compressor,
540 encryptor: Option<&dyn Encryptor>,
541 hasher: &dyn ContentHasher,
542 hash_buf: &mut [u8],
543) -> Result<BlockInfo> {
544 // Compress the chunk
545 let compressed = compressor.compress(chunk)?;
546
547 // Encrypt if requested
548 let final_data = if let Some(enc) = encryptor {
549 enc.encrypt(&compressed, block_idx)?
550 } else {
551 compressed
552 };
553
554 let checksum = crc32fast::hash(&final_data);
555 let chunk_len = chunk.len() as u32;
556
557 // Handle deduplication (only if not encrypting)
558 let offset = if encryptor.is_some() {
559 // No dedup for encrypted data
560 let off = *current_offset;
561 out.write_all(&final_data)?;
562 *current_offset += final_data.len() as u64;
563 off
564 } else if let Some(map) = dedup_map {
565 // Use hash_into for zero-allocation hashing
566 hasher.hash_into(&final_data, hash_buf)?;
567 let mut hash_key = [0u8; 32];
568 hash_key.copy_from_slice(&hash_buf[..32]);
569
570 if let Some(&existing_offset) = map.get(&hash_key) {
571 // Block already exists, reuse it
572 existing_offset
573 } else {
574 // New block, write it and record in map
575 let off = *current_offset;
576 map.insert(hash_key, off);
577 out.write_all(&final_data)?;
578 *current_offset += final_data.len() as u64;
579 off
580 }
581 } else {
582 // No dedup, just write
583 let off = *current_offset;
584 out.write_all(&final_data)?;
585 *current_offset += final_data.len() as u64;
586 off
587 };
588
589 Ok(BlockInfo {
590 offset,
591 length: final_data.len() as u32,
592 logical_len: chunk_len,
593 checksum,
594 })
595}
596
597/// Creates a zero-block descriptor without writing data to disk.
598///
599/// Zero blocks (all-zero chunks) are a special case optimized for space efficiency.
600/// Instead of compressing and storing zeros, we create a metadata-only descriptor
601/// that signals to the reader to return zeros without performing any I/O.
602///
603/// # Sparse Data Optimization
604///
605/// Many VM disk images and memory dumps contain large regions of zeros:
606/// - **Unallocated disk space**: File systems often zero-initialize blocks
607/// - **Memory pages**: Unused or zero-initialized memory
608/// - **Sparse files**: Holes in sparse file systems
609///
610/// Storing these zeros (even compressed) wastes space:
611/// - **LZ4-compressed zeros**: ~100 bytes per 64 KiB block (~0.15% of original)
612/// - **Uncompressed zeros**: 64 KiB per block (100%)
613/// - **Metadata-only**: 20 bytes per block (~0.03%)
614///
615/// The metadata approach saves 99.97% of space for zero blocks.
616///
617/// # Descriptor Format
618///
619/// Zero blocks are identified by a special BlockInfo signature:
620/// - `offset = 0`: Invalid physical offset (data region starts at ≥512)
621/// - `length = 0`: No physical storage
622/// - `logical_len = N`: Original zero block size in bytes
623/// - `checksum = 0`: No checksum needed (zeros are deterministic)
624///
625/// Readers recognize this pattern and synthesize zeros without I/O.
626///
627/// # Parameters
628///
629/// - `logical_len`: Size of the zero block in bytes
630/// - Typically matches block_size (e.g., 65536 for 64 KiB blocks)
631/// - Can vary with content-defined chunking
632/// - Must be > 0 (zero-length blocks are invalid)
633///
634/// # Returns
635///
636/// `BlockInfo` descriptor with zero-block semantics:
637/// - `offset = 0`
638/// - `length = 0`
639/// - `logical_len = logical_len`
640/// - `checksum = 0`
641///
642/// # Examples
643///
644/// ## Detecting and Creating Zero Blocks
645///
646/// ```
647/// use hexz_core::ops::write::{is_zero_chunk, create_zero_block};
648/// use hexz_core::format::index::BlockInfo;
649///
650/// let chunk = vec![0u8; 65536]; // 64 KiB of zeros
651///
652/// if is_zero_chunk(&chunk) {
653/// let info = create_zero_block(chunk.len() as u32);
654/// assert_eq!(info.offset, 0);
655/// assert_eq!(info.length, 0);
656/// assert_eq!(info.logical_len, 65536);
657/// println!("Zero block: No storage required!");
658/// }
659/// ```
660///
661/// ## Usage in Packing Loop
662///
663/// ```no_run
664/// # use hexz_core::ops::write::{is_zero_chunk, create_zero_block, write_block};
665/// # use hexz_core::algo::compression::Lz4Compressor;
666/// # use hexz_core::algo::hashing::blake3::Blake3Hasher;
667/// # use std::fs::File;
668/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
669/// # let mut out = File::create("output.hxz")?;
670/// # let mut offset = 512u64;
671/// # let compressor = Lz4Compressor::new();
672/// # let hasher = Blake3Hasher;
673/// # let mut hash_buf = [0u8; 32];
674/// # let chunks: Vec<Vec<u8>> = vec![];
675/// for (idx, chunk) in chunks.iter().enumerate() {
676/// let info = if is_zero_chunk(chunk) {
677/// // Optimize: No compression, no write
678/// create_zero_block(chunk.len() as u32)
679/// } else {
680/// // Normal path: Compress and write
681/// write_block(&mut out, chunk, idx as u64, &mut offset, None, &compressor, None, &hasher, &mut hash_buf)?
682/// };
683/// // Add info to index page...
684/// }
685/// # Ok(())
686/// # }
687/// ```
688///
689/// # Performance
690///
691/// - **Time complexity**: O(1) (no I/O, no computation)
692/// - **Space complexity**: O(1) (fixed-size struct)
693/// - **Typical savings**: 99.97% vs. compressed zeros
694///
695/// # Reader Behavior
696///
697/// When a reader encounters a zero block (offset=0, length=0):
698/// 1. Recognize zero-block pattern from metadata
699/// 2. Allocate buffer of size `logical_len`
700/// 3. Fill buffer with zeros (optimized memset)
701/// 4. Return buffer to caller
702///
703/// No decompression, decryption, or checksum verification is performed.
704///
705/// # Interaction with Deduplication
706///
707/// Zero blocks do not participate in deduplication:
708/// - They are never written to disk → no physical offset → no dedup entry
709/// - Each zero block gets its own metadata descriptor
710/// - This is fine: Metadata is cheap (20 bytes), and all zero blocks have same content
711///
712/// # Interaction with Encryption
713///
714/// Zero blocks work correctly with encryption:
715/// - They are detected **before** compression/encryption
716/// - Encrypted snapshots still use zero-block optimization
717/// - Readers synthesize zeros without decryption
718///
719/// This is safe because zeros are public information (no confidentiality lost).
720///
721/// # Validation
722///
723/// **IMPORTANT**: This function does NOT validate that the original chunk was actually
724/// all zeros. The caller is responsible for calling [`is_zero_chunk`] first.
725///
726/// If a non-zero chunk is incorrectly marked as a zero block, readers will return
727/// zeros instead of the original data (silent data corruption).
728pub fn create_zero_block(logical_len: u32) -> BlockInfo {
729 BlockInfo {
730 offset: 0,
731 length: 0,
732 logical_len,
733 checksum: 0,
734 }
735}
736
737/// Convenience wrapper for `write_block` that allocates hasher and buffer internally.
738///
739/// This is a simpler API for tests and one-off writes. For hot paths (like snapshot
740/// packing loops), use `write_block` directly with a reused hasher and buffer.
741#[allow(dead_code)]
742fn write_block_simple<W: Write>(
743 out: &mut W,
744 chunk: &[u8],
745 block_idx: u64,
746 current_offset: &mut u64,
747 dedup_map: Option<&mut HashMap<[u8; 32], u64>>,
748 compressor: &dyn Compressor,
749 encryptor: Option<&dyn Encryptor>,
750) -> Result<BlockInfo> {
751 use crate::algo::hashing::blake3::Blake3Hasher;
752 let hasher = Blake3Hasher;
753 let mut hash_buf = [0u8; 32];
754 write_block(
755 out,
756 chunk,
757 block_idx,
758 current_offset,
759 dedup_map,
760 compressor,
761 encryptor,
762 &hasher,
763 &mut hash_buf,
764 )
765}
766
767/// Checks if a chunk consists entirely of zero bytes.
768///
769/// This function efficiently detects all-zero chunks to enable sparse block optimization.
770/// Zero chunks are common in VM images (unallocated space), memory dumps (zero-initialized
771/// pages), and sparse files.
772///
773/// # Algorithm
774///
775/// Uses Rust's iterator `all()` combinator, which:
776/// - Short-circuits on first non-zero byte (early exit)
777/// - Compiles to SIMD instructions on modern CPUs (autovectorization)
778/// - Typically processes 16-32 bytes per instruction (AVX2/AVX-512)
779///
780/// # Parameters
781///
782/// - `chunk`: Byte slice to check
783/// - Empty slices return `true` (vacuous truth)
784/// - Typical size: 16 KiB - 256 KiB (configurable block size)
785///
786/// # Returns
787///
788/// - `true`: All bytes are zero (sparse block, use [`create_zero_block`])
789/// - `false`: At least one non-zero byte (normal block, compress and write)
790///
791/// # Performance
792///
793/// Modern CPUs with SIMD support achieve excellent throughput:
794///
795/// - **SIMD-optimized**: ~10-20 GB/s (memory bandwidth limited)
796/// - **Scalar fallback**: ~1-2 GB/s (without SIMD)
797/// - **Typical overhead**: <1% of total packing time
798///
799/// The check is always worth performing given the massive space savings for zero blocks.
800///
801/// # Examples
802///
803/// ## Basic Usage
804///
805/// ```
806/// use hexz_core::ops::write::is_zero_chunk;
807///
808/// let zeros = vec![0u8; 65536];
809/// assert!(is_zero_chunk(&zeros));
810///
811/// let data = vec![0u8, 1u8, 0u8];
812/// assert!(!is_zero_chunk(&data));
813///
814/// let empty: &[u8] = &[];
815/// assert!(is_zero_chunk(empty)); // Empty is considered "all zeros"
816/// ```
817///
818/// ## Packing Loop Integration
819///
820/// ```no_run
821/// # use hexz_core::ops::write::{is_zero_chunk, create_zero_block, write_block};
822/// # use hexz_core::algo::compression::Lz4Compressor;
823/// # use hexz_core::algo::hashing::blake3::Blake3Hasher;
824/// # use hexz_core::format::index::BlockInfo;
825/// # use std::fs::File;
826/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
827/// # let mut out = File::create("output.hxz")?;
828/// # let mut offset = 512u64;
829/// # let compressor = Lz4Compressor::new();
830/// # let hasher = Blake3Hasher;
831/// # let mut hash_buf = [0u8; 32];
832/// # let mut index_blocks = Vec::new();
833/// # let chunks: Vec<Vec<u8>> = vec![];
834/// for (idx, chunk) in chunks.iter().enumerate() {
835/// let info = if is_zero_chunk(chunk) {
836/// // Fast path: No compression, no write, just metadata
837/// create_zero_block(chunk.len() as u32)
838/// } else {
839/// // Slow path: Compress, write, create metadata
840/// write_block(&mut out, chunk, idx as u64, &mut offset, None, &compressor, None, &hasher, &mut hash_buf)?
841/// };
842/// index_blocks.push(info);
843/// }
844/// # Ok(())
845/// # }
846/// ```
847///
848/// ## Benchmarking Zero Detection
849///
850/// ```
851/// use hexz_core::ops::write::is_zero_chunk;
852/// use std::time::Instant;
853///
854/// let chunk = vec![0u8; 64 * 1024 * 1024]; // 64 MiB
855/// let start = Instant::now();
856///
857/// for _ in 0..100 {
858/// let _ = is_zero_chunk(&chunk);
859/// }
860///
861/// let elapsed = start.elapsed();
862/// let throughput = (64.0 * 100.0) / elapsed.as_secs_f64(); // MB/s
863/// println!("Zero detection: {:.1} GB/s", throughput / 1024.0);
864/// ```
865///
866/// # SIMD Optimization
867///
868/// On x86-64 with AVX2, the compiler typically generates code like:
869///
870/// ```text
871/// vpxor ymm0, ymm0, ymm0 ; Zero register
872/// loop:
873/// vmovdqu ymm1, [rsi] ; Load 32 bytes
874/// vpcmpeqb ymm2, ymm1, ymm0 ; Compare with zero
875/// vpmovmskb eax, ymm2 ; Extract comparison mask
876/// cmp eax, 0xFFFFFFFF ; All zeros?
877/// jne found_nonzero ; Early exit if not
878/// add rsi, 32 ; Advance pointer
879/// loop
880/// ```
881///
882/// This processes 32 bytes per iteration (~1-2 cycles on modern CPUs).
883///
884/// # Edge Cases
885///
886/// - **Empty chunks**: Return `true` (vacuous truth, no non-zero bytes)
887/// - **Single byte**: Works correctly, no special handling needed
888/// - **Unaligned chunks**: SIMD code handles unaligned loads transparently
889///
890/// # Alternative Implementations
891///
892/// Other possible implementations (not currently used):
893///
894/// 1. **Manual SIMD**: Use `std::arch` for explicit SIMD (faster but less portable)
895/// 2. **Chunked comparison**: Process in 8-byte chunks with `u64` casts (faster scalar)
896/// 3. **Bitmap scan**: Use CPU's `bsf`/`tzcnt` to skip zero regions (complex)
897///
898/// Current implementation relies on compiler autovectorization, which works well
899/// in practice and maintains portability.
900///
901/// # Correctness
902///
903/// This function is pure and infallible:
904/// - No side effects (read-only operation)
905/// - No panics (iterator `all()` is safe for all inputs)
906/// - No undefined behavior (all byte patterns are valid)
907pub fn is_zero_chunk(chunk: &[u8]) -> bool {
908 chunk.iter().all(|&b| b == 0)
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914 use crate::algo::compression::{Lz4Compressor, ZstdCompressor};
915 use crate::algo::encryption::AesGcmEncryptor;
916 use std::collections::HashMap;
917 use std::io::Cursor;
918
919 #[test]
920 fn test_is_zero_chunk_all_zeros() {
921 let chunk = vec![0u8; 1024];
922 assert!(is_zero_chunk(&chunk));
923 }
924
925 #[test]
926 fn test_is_zero_chunk_with_nonzero() {
927 let mut chunk = vec![0u8; 1024];
928 chunk[512] = 1; // Single non-zero byte
929 assert!(!is_zero_chunk(&chunk));
930 }
931
932 #[test]
933 fn test_is_zero_chunk_all_nonzero() {
934 let chunk = vec![0xFFu8; 1024];
935 assert!(!is_zero_chunk(&chunk));
936 }
937
938 #[test]
939 fn test_is_zero_chunk_empty() {
940 let chunk: Vec<u8> = vec![];
941 assert!(is_zero_chunk(&chunk)); // Vacuous truth
942 }
943
944 #[test]
945 fn test_is_zero_chunk_single_zero() {
946 let chunk = vec![0u8];
947 assert!(is_zero_chunk(&chunk));
948 }
949
950 #[test]
951 fn test_is_zero_chunk_single_nonzero() {
952 let chunk = vec![1u8];
953 assert!(!is_zero_chunk(&chunk));
954 }
955
956 #[test]
957 fn test_create_zero_block() {
958 let logical_len = 65536;
959 let info = create_zero_block(logical_len);
960
961 assert_eq!(info.offset, 0);
962 assert_eq!(info.length, 0);
963 assert_eq!(info.logical_len, logical_len);
964 assert_eq!(info.checksum, 0);
965 }
966
967 #[test]
968 fn test_create_zero_block_various_sizes() {
969 for size in [1, 16, 1024, 4096, 65536, 1048576] {
970 let info = create_zero_block(size);
971 assert_eq!(info.offset, 0);
972 assert_eq!(info.length, 0);
973 assert_eq!(info.logical_len, size);
974 assert_eq!(info.checksum, 0);
975 }
976 }
977
978 #[test]
979 fn test_write_block_basic_lz4() {
980 let mut output = Cursor::new(Vec::new());
981 let mut offset = 512u64; // Start after header
982 let chunk = vec![0xAAu8; 4096];
983 let compressor = Lz4Compressor::new();
984
985 let result =
986 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None);
987
988 assert!(result.is_ok());
989 let info = result.unwrap();
990
991 // Verify offset updated
992 assert!(offset > 512);
993
994 // Verify block info
995 assert_eq!(info.offset, 512);
996 assert!(info.length > 0); // Compressed data written
997 assert_eq!(info.logical_len, 4096);
998 assert!(info.checksum != 0);
999
1000 // Verify data was written
1001 let written = output.into_inner();
1002 assert_eq!(written.len(), (offset - 512) as usize);
1003 }
1004
1005 #[test]
1006 fn test_write_block_basic_zstd() {
1007 let mut output = Cursor::new(Vec::new());
1008 let mut offset = 512u64;
1009 let chunk = vec![0xAAu8; 4096];
1010 let compressor = ZstdCompressor::new(3, None);
1011
1012 let result =
1013 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None);
1014
1015 assert!(result.is_ok());
1016 let info = result.unwrap();
1017
1018 assert_eq!(info.offset, 512);
1019 assert!(info.length > 0);
1020 assert_eq!(info.logical_len, 4096);
1021 }
1022
1023 #[test]
1024 fn test_write_block_incompressible_data() {
1025 let mut output = Cursor::new(Vec::new());
1026 let mut offset = 512u64;
1027
1028 // Random-ish data that doesn't compress well
1029 let chunk: Vec<u8> = (0..4096).map(|i| ((i * 7 + 13) % 256) as u8).collect();
1030 let compressor = Lz4Compressor::new();
1031
1032 let result =
1033 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None);
1034
1035 assert!(result.is_ok());
1036 let info = result.unwrap();
1037
1038 // Even "incompressible" data might compress slightly or expand
1039 // Just verify it executed successfully
1040 assert_eq!(info.logical_len, chunk.len() as u32);
1041 assert!(info.length > 0);
1042 }
1043
1044 #[test]
1045 fn test_write_block_with_dedup_unique_blocks() {
1046 let mut output = Cursor::new(Vec::new());
1047 let mut offset = 512u64;
1048 let mut dedup_map = HashMap::new();
1049 let compressor = Lz4Compressor::new();
1050
1051 // Write first block
1052 let chunk1 = vec![0xAAu8; 4096];
1053 let info1 = write_block_simple(
1054 &mut output,
1055 &chunk1,
1056 0,
1057 &mut offset,
1058 Some(&mut dedup_map),
1059 &compressor,
1060 None,
1061 )
1062 .unwrap();
1063
1064 let offset_after_block1 = offset;
1065
1066 // Write second unique block
1067 let chunk2 = vec![0xBBu8; 4096];
1068 let info2 = write_block_simple(
1069 &mut output,
1070 &chunk2,
1071 1,
1072 &mut offset,
1073 Some(&mut dedup_map),
1074 &compressor,
1075 None,
1076 )
1077 .unwrap();
1078
1079 // Both blocks should be written
1080 assert_eq!(info1.offset, 512);
1081 assert_eq!(info2.offset, offset_after_block1);
1082 assert!(offset > offset_after_block1);
1083
1084 // Dedup map should have 2 entries
1085 assert_eq!(dedup_map.len(), 2);
1086 }
1087
1088 #[test]
1089 fn test_write_block_with_dedup_duplicate_blocks() {
1090 let mut output = Cursor::new(Vec::new());
1091 let mut offset = 512u64;
1092 let mut dedup_map = HashMap::new();
1093 let compressor = Lz4Compressor::new();
1094
1095 // Write first block
1096 let chunk1 = vec![0xAAu8; 4096];
1097 let info1 = write_block_simple(
1098 &mut output,
1099 &chunk1,
1100 0,
1101 &mut offset,
1102 Some(&mut dedup_map),
1103 &compressor,
1104 None,
1105 )
1106 .unwrap();
1107
1108 let offset_after_block1 = offset;
1109
1110 // Write duplicate block (same content)
1111 let chunk2 = vec![0xAAu8; 4096];
1112 let info2 = write_block_simple(
1113 &mut output,
1114 &chunk2,
1115 1,
1116 &mut offset,
1117 Some(&mut dedup_map),
1118 &compressor,
1119 None,
1120 )
1121 .unwrap();
1122
1123 // Second block should reuse first block's offset
1124 assert_eq!(info1.offset, info2.offset);
1125 assert_eq!(info1.length, info2.length);
1126 assert_eq!(info1.checksum, info2.checksum);
1127
1128 // Offset should not advance (no write)
1129 assert_eq!(offset, offset_after_block1);
1130
1131 // Dedup map should have 1 entry (deduplicated)
1132 assert_eq!(dedup_map.len(), 1);
1133 }
1134
1135 #[test]
1136 fn test_write_block_with_encryption() {
1137 let mut output = Cursor::new(Vec::new());
1138 let mut offset = 512u64;
1139 let chunk = vec![0xAAu8; 4096];
1140 let compressor = Lz4Compressor::new();
1141
1142 // Create encryptor
1143 let salt = [0u8; 32];
1144 let encryptor = AesGcmEncryptor::new(b"test_password", &salt, 100000).unwrap();
1145
1146 let result = write_block_simple(
1147 &mut output,
1148 &chunk,
1149 0,
1150 &mut offset,
1151 None,
1152 &compressor,
1153 Some(&encryptor),
1154 );
1155
1156 assert!(result.is_ok());
1157 let info = result.unwrap();
1158
1159 // Encrypted data should be larger than compressed (adds GCM tag)
1160 assert!(info.length > 16); // At least tag overhead
1161 assert_eq!(info.logical_len, 4096);
1162 }
1163
1164 #[test]
1165 fn test_write_block_encryption_disables_dedup() {
1166 let mut output = Cursor::new(Vec::new());
1167 let mut offset = 512u64;
1168 let mut dedup_map = HashMap::new();
1169 let compressor = Lz4Compressor::new();
1170 let salt = [0u8; 32];
1171 let encryptor = AesGcmEncryptor::new(b"test_password", &salt, 100000).unwrap();
1172
1173 // Write first encrypted block
1174 let chunk1 = vec![0xAAu8; 4096];
1175 let info1 = write_block_simple(
1176 &mut output,
1177 &chunk1,
1178 0,
1179 &mut offset,
1180 Some(&mut dedup_map),
1181 &compressor,
1182 Some(&encryptor),
1183 )
1184 .unwrap();
1185
1186 let offset_after_block1 = offset;
1187
1188 // Write second encrypted block (same content, different nonce)
1189 let chunk2 = vec![0xAAu8; 4096];
1190 let info2 = write_block_simple(
1191 &mut output,
1192 &chunk2,
1193 1,
1194 &mut offset,
1195 Some(&mut dedup_map),
1196 &compressor,
1197 Some(&encryptor),
1198 )
1199 .unwrap();
1200
1201 // Both blocks should be written (no dedup with encryption)
1202 assert_eq!(info1.offset, 512);
1203 assert_eq!(info2.offset, offset_after_block1);
1204 assert!(offset > offset_after_block1);
1205
1206 // Dedup map should be empty (encryption disables dedup)
1207 assert_eq!(dedup_map.len(), 0);
1208 }
1209
1210 #[test]
1211 fn test_write_block_multiple_sequential() {
1212 let mut output = Cursor::new(Vec::new());
1213 let mut offset = 512u64;
1214 let compressor = Lz4Compressor::new();
1215
1216 let mut expected_offset = 512u64;
1217
1218 // Write 10 blocks sequentially
1219 for i in 0..10 {
1220 let chunk = vec![i as u8; 4096];
1221 let info =
1222 write_block_simple(&mut output, &chunk, i, &mut offset, None, &compressor, None)
1223 .unwrap();
1224
1225 assert_eq!(info.offset, expected_offset);
1226 expected_offset += info.length as u64;
1227 }
1228
1229 assert_eq!(offset, expected_offset);
1230 }
1231
1232 #[test]
1233 fn test_write_block_preserves_logical_length() {
1234 let mut output = Cursor::new(Vec::new());
1235 let mut offset = 512u64;
1236 let compressor = Lz4Compressor::new();
1237
1238 for size in [128, 1024, 4096, 65536] {
1239 let chunk = vec![0xAAu8; size];
1240 let info =
1241 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None)
1242 .unwrap();
1243
1244 assert_eq!(info.logical_len, size as u32);
1245 }
1246 }
1247
1248 #[test]
1249 fn test_write_block_checksum_differs() {
1250 let mut output1 = Cursor::new(Vec::new());
1251 let mut output2 = Cursor::new(Vec::new());
1252 let mut offset1 = 512u64;
1253 let mut offset2 = 512u64;
1254 let compressor = Lz4Compressor::new();
1255
1256 let chunk1 = vec![0xAAu8; 4096];
1257 let chunk2 = vec![0xBBu8; 4096];
1258
1259 let info1 = write_block_simple(
1260 &mut output1,
1261 &chunk1,
1262 0,
1263 &mut offset1,
1264 None,
1265 &compressor,
1266 None,
1267 )
1268 .unwrap();
1269
1270 let info2 = write_block_simple(
1271 &mut output2,
1272 &chunk2,
1273 0,
1274 &mut offset2,
1275 None,
1276 &compressor,
1277 None,
1278 )
1279 .unwrap();
1280
1281 // Different input data should produce different checksums
1282 assert_ne!(info1.checksum, info2.checksum);
1283 }
1284
1285 #[test]
1286 fn test_write_block_empty_chunk() {
1287 let mut output = Cursor::new(Vec::new());
1288 let mut offset = 512u64;
1289 let chunk: Vec<u8> = vec![];
1290 let compressor = Lz4Compressor::new();
1291
1292 let result =
1293 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None);
1294
1295 // Should handle empty chunk
1296 assert!(result.is_ok());
1297 let info = result.unwrap();
1298 assert_eq!(info.logical_len, 0);
1299 }
1300
1301 #[test]
1302 fn test_write_block_large_block() {
1303 let mut output = Cursor::new(Vec::new());
1304 let mut offset = 512u64;
1305 let chunk = vec![0xAAu8; 1024 * 1024]; // 1 MB
1306 let compressor = Lz4Compressor::new();
1307
1308 let result =
1309 write_block_simple(&mut output, &chunk, 0, &mut offset, None, &compressor, None);
1310
1311 assert!(result.is_ok());
1312 let info = result.unwrap();
1313 assert_eq!(info.logical_len, 1024 * 1024);
1314 // Highly compressible data should compress well
1315 assert!(info.length < info.logical_len);
1316 }
1317
1318 #[test]
1319 fn test_integration_zero_detection_and_write() {
1320 let mut output = Cursor::new(Vec::new());
1321 let mut offset = 512u64;
1322 let compressor = Lz4Compressor::new();
1323
1324 let zero_chunk = vec![0u8; 4096];
1325 let data_chunk = vec![0xAAu8; 4096];
1326
1327 // Process zero chunk
1328 let zero_info = if is_zero_chunk(&zero_chunk) {
1329 create_zero_block(zero_chunk.len() as u32)
1330 } else {
1331 write_block_simple(
1332 &mut output,
1333 &zero_chunk,
1334 0,
1335 &mut offset,
1336 None,
1337 &compressor,
1338 None,
1339 )
1340 .unwrap()
1341 };
1342
1343 // Process data chunk
1344 let data_info = if is_zero_chunk(&data_chunk) {
1345 create_zero_block(data_chunk.len() as u32)
1346 } else {
1347 write_block_simple(
1348 &mut output,
1349 &data_chunk,
1350 1,
1351 &mut offset,
1352 None,
1353 &compressor,
1354 None,
1355 )
1356 .unwrap()
1357 };
1358
1359 // Zero block should not be written
1360 assert_eq!(zero_info.offset, 0);
1361 assert_eq!(zero_info.length, 0);
1362
1363 // Data block should be written
1364 assert_eq!(data_info.offset, 512);
1365 assert!(data_info.length > 0);
1366 }
1367}