Skip to main content

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//! - **Hash table 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::io::Write;
271
272use crate::algo::compression::Compressor;
273use crate::algo::dedup::hash_table::StandardHashTable;
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 hexz_core::algo::dedup::hash_table::StandardHashTable;
368/// use std::fs::File;
369///
370/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
371/// let mut out = File::create("output.hxz")?;
372/// let mut offset = 512u64; // After header
373/// let chunk = vec![0x42; 65536]; // 64 KiB of data
374/// let compressor = Lz4Compressor::new();
375/// let hasher = Blake3Hasher;
376/// let mut hash_buf = [0u8; 32];
377///
378/// let mut compress_buf = Vec::new();
379/// let mut encrypt_buf = Vec::new();
380///
381/// let info = write_block(
382///     &mut out,
383///     &chunk,
384///     0,              // block_idx
385///     &mut offset,
386///     None::<&mut StandardHashTable>, // No dedup
387///     &compressor,
388///     None,           // No encryption
389///     &hasher,
390///     &mut hash_buf,
391///     &mut compress_buf,
392///     &mut encrypt_buf,
393/// )?;
394///
395/// println!("Block written at offset {}, size {}", info.offset, info.length);
396/// # Ok(())
397/// # }
398/// ```
399///
400/// ## With Deduplication
401///
402/// ```no_run
403/// use hexz_core::ops::write::write_block;
404/// use hexz_core::algo::compression::Lz4Compressor;
405/// use hexz_core::algo::hashing::blake3::Blake3Hasher;
406/// use hexz_core::algo::dedup::hash_table::StandardHashTable;
407/// use std::fs::File;
408///
409/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
410/// let mut out = File::create("output.hxz")?;
411/// let mut offset = 512u64;
412/// let mut dedup_map = StandardHashTable::new();
413/// let compressor = Lz4Compressor::new();
414/// let hasher = Blake3Hasher;
415/// let mut hash_buf = [0u8; 32];
416/// let mut compress_buf = Vec::new();
417/// let mut encrypt_buf = Vec::new();
418///
419/// // Write first block
420/// let chunk1 = vec![0xAA; 65536];
421/// let info1 = write_block(
422///     &mut out,
423///     &chunk1,
424///     0,
425///     &mut offset,
426///     Some(&mut dedup_map),
427///     &compressor,
428///     None,
429///     &hasher,
430///     &mut hash_buf,
431///     &mut compress_buf,
432///     &mut encrypt_buf,
433/// )?;
434/// println!("Block 0: offset={}, written", info1.offset);
435///
436/// // Write duplicate block (same content)
437/// let chunk2 = vec![0xAA; 65536];
438/// let info2 = write_block(
439///     &mut out,
440///     &chunk2,
441///     1,
442///     &mut offset,
443///     Some(&mut dedup_map),
444///     &compressor,
445///     None,
446///     &hasher,
447///     &mut hash_buf,
448///     &mut compress_buf,
449///     &mut encrypt_buf,
450/// )?;
451/// println!("Block 1: offset={}, deduplicated (no write)", info2.offset);
452/// assert_eq!(info1.offset, info2.offset); // Same offset, block reused
453/// # Ok(())
454/// # }
455/// ```
456///
457/// ## With Encryption
458///
459/// ```no_run
460/// use hexz_core::ops::write::write_block;
461/// use hexz_core::algo::compression::Lz4Compressor;
462/// use hexz_core::algo::encryption::AesGcmEncryptor;
463/// use hexz_core::algo::hashing::blake3::Blake3Hasher;
464/// use hexz_common::crypto::KeyDerivationParams;
465/// use hexz_core::algo::dedup::hash_table::StandardHashTable;
466/// use std::fs::File;
467///
468/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
469/// let mut out = File::create("output.hxz")?;
470/// let mut offset = 512u64;
471/// let compressor = Lz4Compressor::new();
472/// let hasher = Blake3Hasher;
473/// let mut hash_buf = [0u8; 32];
474///
475/// // Initialize encryptor
476/// let params = KeyDerivationParams::default();
477/// let encryptor = AesGcmEncryptor::new(
478///     b"strong_password",
479///     &params.salt,
480///     params.iterations,
481/// )?;
482///
483/// let mut compress_buf = Vec::new();
484/// let mut encrypt_buf = Vec::new();
485///
486/// let chunk = vec![0x42; 65536];
487/// let info = write_block(
488///     &mut out,
489///     &chunk,
490///     0,
491///     &mut offset,
492///     None::<&mut StandardHashTable>, // Dedup disabled (encryption prevents it)
493///     &compressor,
494///     Some(&encryptor),
495///     &hasher,
496///     &mut hash_buf,
497///     &mut compress_buf,
498///     &mut encrypt_buf,
499/// )?;
500///
501/// println!("Encrypted block: offset={}, length={}", info.offset, info.length);
502/// # Ok(())
503/// # }
504/// ```
505///
506/// # Performance
507///
508/// - **Compression**: Dominates runtime (~2 GB/s LZ4, ~500 MB/s Zstd)
509/// - **Encryption**: ~1-2 GB/s (hardware AES-NI)
510/// - **Hashing**: ~3200 MB/s (BLAKE3 for dedup)
511/// - **I/O**: Typically not bottleneck (buffered writes, ~3 GB/s sequential)
512///
513/// # Deduplication Effectiveness
514///
515/// Deduplication is most effective when:
516/// - **Fixed-size blocks**: Same content → same boundaries → same hash
517/// - **Unencrypted**: Encryption produces unique ciphertext per block (different nonces)
518/// - **Redundant data**: Duplicate files, repeated patterns, copy-on-write filesystems
519///
520/// Deduplication is ineffective when:
521/// - **Content-defined chunking**: Small shifts cause different boundaries
522/// - **Compressed input**: Pre-compressed data has low redundancy
523/// - **Unique data**: No duplicate blocks to detect
524///
525/// # Security Considerations
526///
527/// ## Block Index as Nonce
528///
529/// When encrypting, `block_idx` is used as part of the AES-GCM nonce. **CRITICAL**:
530/// - Never reuse `block_idx` values within the same encrypted snapshot
531/// - Nonce reuse breaks AES-GCM security (allows plaintext recovery)
532/// - Each logical block must have a unique index
533///
534/// ## Deduplication and Encryption
535///
536/// Deduplication is automatically disabled when encrypting because:
537/// - Each block has a unique nonce → unique ciphertext
538/// - BLAKE3(ciphertext1) ≠ BLAKE3(ciphertext2) even if plaintext is identical
539/// - Attempting dedup with encryption wastes CPU (hashing) without space savings
540///
541/// # Thread Safety
542///
543/// This function is **not thread-safe** with respect to the output writer:
544/// - Concurrent calls with the same `out` writer will interleave writes (corruption)
545/// - Concurrent calls with different writers to the same file will corrupt file
546///
547/// For parallel writing, use separate output files or implement external synchronization.
548///
549/// The dedup_map must also be externally synchronized for concurrent access.
550#[allow(clippy::too_many_arguments)]
551pub fn write_block<W: Write>(
552    out: &mut W,
553    chunk: &[u8],
554    block_idx: u64,
555    current_offset: &mut u64,
556    dedup_map: Option<&mut StandardHashTable>,
557    compressor: &dyn Compressor,
558    encryptor: Option<&dyn Encryptor>,
559    hasher: &dyn ContentHasher,
560    hash_buf: &mut [u8; 32],
561    compress_buf: &mut Vec<u8>,
562    encrypt_buf: &mut Vec<u8>,
563) -> Result<BlockInfo> {
564    // Compress the chunk into reusable buffer
565    compressor.compress_into(chunk, compress_buf)?;
566
567    // Encrypt if requested, using reusable buffer
568    let final_data: &[u8] = if let Some(enc) = encryptor {
569        enc.encrypt_into(compress_buf, block_idx, encrypt_buf)?;
570        encrypt_buf
571    } else {
572        compress_buf
573    };
574
575    let checksum = crc32fast::hash(final_data);
576    let chunk_len = chunk.len() as u32;
577    let final_len = final_data.len() as u32;
578
579    // Handle deduplication (only if not encrypting)
580    let offset = if encryptor.is_some() {
581        // No dedup for encrypted data
582        let off = *current_offset;
583        out.write_all(final_data)?;
584        *current_offset += final_len as u64;
585        off
586    } else if let Some(map) = dedup_map {
587        // Hash directly into the fixed-size buffer (no runtime bounds check).
588        *hash_buf = hasher.hash_fixed(final_data);
589
590        if let Some(existing_offset) = map.get(hash_buf) {
591            // Block already exists, reuse it — no copy needed on hit
592            existing_offset
593        } else {
594            // New block: copy hash_buf only on miss (insert needs owned key)
595            let off = *current_offset;
596            map.insert(*hash_buf, off);
597            out.write_all(final_data)?;
598            *current_offset += final_len as u64;
599            off
600        }
601    } else {
602        // No dedup, just write
603        let off = *current_offset;
604        out.write_all(final_data)?;
605        *current_offset += final_len as u64;
606        off
607    };
608
609    Ok(BlockInfo {
610        offset,
611        length: final_len,
612        logical_len: chunk_len,
613        checksum,
614    })
615}
616
617/// Creates a zero-block descriptor without writing data to disk.
618///
619/// Zero blocks (all-zero chunks) are a special case optimized for space efficiency.
620/// Instead of compressing and storing zeros, we create a metadata-only descriptor
621/// that signals to the reader to return zeros without performing any I/O.
622///
623/// # Sparse Data Optimization
624///
625/// Many VM disk images and memory dumps contain large regions of zeros:
626/// - **Unallocated disk space**: File systems often zero-initialize blocks
627/// - **Memory pages**: Unused or zero-initialized memory
628/// - **Sparse files**: Holes in sparse file systems
629///
630/// Storing these zeros (even compressed) wastes space:
631/// - **LZ4-compressed zeros**: ~100 bytes per 64 KiB block (~0.15% of original)
632/// - **Uncompressed zeros**: 64 KiB per block (100%)
633/// - **Metadata-only**: 20 bytes per block (~0.03%)
634///
635/// The metadata approach saves 99.97% of space for zero blocks.
636///
637/// # Descriptor Format
638///
639/// Zero blocks are identified by a special BlockInfo signature:
640/// - `offset = 0`: Invalid physical offset (data region starts at ≥512)
641/// - `length = 0`: No physical storage
642/// - `logical_len = N`: Original zero block size in bytes
643/// - `checksum = 0`: No checksum needed (zeros are deterministic)
644///
645/// Readers recognize this pattern and synthesize zeros without I/O.
646///
647/// # Parameters
648///
649/// - `logical_len`: Size of the zero block in bytes
650///   - Typically matches block_size (e.g., 65536 for 64 KiB blocks)
651///   - Can vary with content-defined chunking
652///   - Must be > 0 (zero-length blocks are invalid)
653///
654/// # Returns
655///
656/// `BlockInfo` descriptor with zero-block semantics:
657/// - `offset = 0`
658/// - `length = 0`
659/// - `logical_len = logical_len`
660/// - `checksum = 0`
661///
662/// # Examples
663///
664/// ## Detecting and Creating Zero Blocks
665///
666/// ```
667/// use hexz_core::ops::write::{is_zero_chunk, create_zero_block};
668/// use hexz_core::format::index::BlockInfo;
669///
670/// let chunk = vec![0u8; 65536]; // 64 KiB of zeros
671///
672/// if is_zero_chunk(&chunk) {
673///     let info = create_zero_block(chunk.len() as u32);
674///     assert_eq!(info.offset, 0);
675///     assert_eq!(info.length, 0);
676///     assert_eq!(info.logical_len, 65536);
677///     println!("Zero block: No storage required!");
678/// }
679/// ```
680///
681/// ## Usage in Packing Loop
682///
683/// ```no_run
684/// # use hexz_core::ops::write::{is_zero_chunk, create_zero_block, write_block};
685/// # use hexz_core::algo::compression::Lz4Compressor;
686/// # use hexz_core::algo::hashing::blake3::Blake3Hasher;
687/// # use hexz_core::algo::dedup::hash_table::StandardHashTable;
688/// # use std::fs::File;
689/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
690/// # let mut out = File::create("output.hxz")?;
691/// # let mut offset = 512u64;
692/// # let compressor = Lz4Compressor::new();
693/// # let hasher = Blake3Hasher;
694/// # let mut hash_buf = [0u8; 32];
695/// # let mut compress_buf = Vec::new();
696/// # let mut encrypt_buf = Vec::new();
697/// # let chunks: Vec<Vec<u8>> = vec![];
698/// for (idx, chunk) in chunks.iter().enumerate() {
699///     let info = if is_zero_chunk(chunk) {
700///         // Optimize: No compression, no write
701///         create_zero_block(chunk.len() as u32)
702///     } else {
703///         // Normal path: Compress and write
704///         write_block(&mut out, chunk, idx as u64, &mut offset, None::<&mut StandardHashTable>, &compressor, None, &hasher, &mut hash_buf, &mut compress_buf, &mut encrypt_buf)?
705///     };
706///     // Add info to index page...
707/// }
708/// # Ok(())
709/// # }
710/// ```
711///
712/// # Performance
713///
714/// - **Time complexity**: O(1) (no I/O, no computation)
715/// - **Space complexity**: O(1) (fixed-size struct)
716/// - **Typical savings**: 99.97% vs. compressed zeros
717///
718/// # Reader Behavior
719///
720/// When a reader encounters a zero block (offset=0, length=0):
721/// 1. Recognize zero-block pattern from metadata
722/// 2. Allocate buffer of size `logical_len`
723/// 3. Fill buffer with zeros (optimized memset)
724/// 4. Return buffer to caller
725///
726/// No decompression, decryption, or checksum verification is performed.
727///
728/// # Interaction with Deduplication
729///
730/// Zero blocks do not participate in deduplication:
731/// - They are never written to disk → no physical offset → no dedup entry
732/// - Each zero block gets its own metadata descriptor
733/// - This is fine: Metadata is cheap (20 bytes), and all zero blocks have same content
734///
735/// # Interaction with Encryption
736///
737/// Zero blocks work correctly with encryption:
738/// - They are detected **before** compression/encryption
739/// - Encrypted snapshots still use zero-block optimization
740/// - Readers synthesize zeros without decryption
741///
742/// This is safe because zeros are public information (no confidentiality lost).
743///
744/// # Validation
745///
746/// **IMPORTANT**: This function does NOT validate that the original chunk was actually
747/// all zeros. The caller is responsible for calling [`is_zero_chunk`] first.
748///
749/// If a non-zero chunk is incorrectly marked as a zero block, readers will return
750/// zeros instead of the original data (silent data corruption).
751pub fn create_zero_block(logical_len: u32) -> BlockInfo {
752    BlockInfo {
753        offset: 0,
754        length: 0,
755        logical_len,
756        checksum: 0,
757    }
758}
759
760/// Convenience wrapper for `write_block` that allocates hasher and buffer internally.
761///
762/// This is a simpler API for tests and one-off writes. For hot paths (like snapshot
763/// packing loops), use `write_block` directly with a reused hasher and buffer.
764#[allow(dead_code)]
765fn write_block_simple<W: Write>(
766    out: &mut W,
767    chunk: &[u8],
768    block_idx: u64,
769    current_offset: &mut u64,
770    dedup_map: Option<&mut StandardHashTable>,
771    compressor: &dyn Compressor,
772    encryptor: Option<&dyn Encryptor>,
773) -> Result<BlockInfo> {
774    use crate::algo::hashing::blake3::Blake3Hasher;
775    let hasher = Blake3Hasher;
776    let mut hash_buf = [0u8; 32];
777    let mut compress_buf = Vec::new();
778    let mut encrypt_buf = Vec::new();
779    write_block(
780        out,
781        chunk,
782        block_idx,
783        current_offset,
784        dedup_map,
785        compressor,
786        encryptor,
787        &hasher,
788        &mut hash_buf,
789        &mut compress_buf,
790        &mut encrypt_buf,
791    )
792}
793
794/// Checks if a chunk consists entirely of zero bytes.
795///
796/// This function efficiently detects all-zero chunks to enable sparse block optimization.
797/// Zero chunks are common in VM images (unallocated space), memory dumps (zero-initialized
798/// pages), and sparse files.
799///
800/// # Algorithm
801///
802/// Uses Rust's iterator `all()` combinator, which:
803/// - Short-circuits on first non-zero byte (early exit)
804/// - Compiles to SIMD instructions on modern CPUs (autovectorization)
805/// - Typically processes 16-32 bytes per instruction (AVX2/AVX-512)
806///
807/// # Parameters
808///
809/// - `chunk`: Byte slice to check
810///   - Empty slices return `true` (vacuous truth)
811///   - Typical size: 16 KiB - 256 KiB (configurable block size)
812///
813/// # Returns
814///
815/// - `true`: All bytes are zero (sparse block, use [`create_zero_block`])
816/// - `false`: At least one non-zero byte (normal block, compress and write)
817///
818/// # Performance
819///
820/// Modern CPUs with SIMD support achieve excellent throughput:
821///
822/// - **SIMD-optimized**: ~10-20 GB/s (memory bandwidth limited)
823/// - **Scalar fallback**: ~1-2 GB/s (without SIMD)
824/// - **Typical overhead**: <1% of total packing time
825///
826/// The check is always worth performing given the massive space savings for zero blocks.
827///
828/// # Examples
829///
830/// ## Basic Usage
831///
832/// ```
833/// use hexz_core::ops::write::is_zero_chunk;
834///
835/// let zeros = vec![0u8; 65536];
836/// assert!(is_zero_chunk(&zeros));
837///
838/// let data = vec![0u8, 1u8, 0u8];
839/// assert!(!is_zero_chunk(&data));
840///
841/// let empty: &[u8] = &[];
842/// assert!(is_zero_chunk(empty)); // Empty is considered "all zeros"
843/// ```
844///
845/// ## Packing Loop Integration
846///
847/// ```no_run
848/// # use hexz_core::ops::write::{is_zero_chunk, create_zero_block, write_block};
849/// # use hexz_core::algo::compression::Lz4Compressor;
850/// # use hexz_core::algo::hashing::blake3::Blake3Hasher;
851/// # use hexz_core::format::index::BlockInfo;
852/// # use hexz_core::algo::dedup::hash_table::StandardHashTable;
853/// # use std::fs::File;
854/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
855/// # let mut out = File::create("output.hxz")?;
856/// # let mut offset = 512u64;
857/// # let compressor = Lz4Compressor::new();
858/// # let hasher = Blake3Hasher;
859/// # let mut hash_buf = [0u8; 32];
860/// # let mut compress_buf = Vec::new();
861/// # let mut encrypt_buf = Vec::new();
862/// # let mut index_blocks = Vec::new();
863/// # let chunks: Vec<Vec<u8>> = vec![];
864/// for (idx, chunk) in chunks.iter().enumerate() {
865///     let info = if is_zero_chunk(chunk) {
866///         // Fast path: No compression, no write, just metadata
867///         create_zero_block(chunk.len() as u32)
868///     } else {
869///         // Slow path: Compress, write, create metadata
870///         write_block(&mut out, chunk, idx as u64, &mut offset, None::<&mut StandardHashTable>, &compressor, None, &hasher, &mut hash_buf, &mut compress_buf, &mut encrypt_buf)?
871///     };
872///     index_blocks.push(info);
873/// }
874/// # Ok(())
875/// # }
876/// ```
877///
878/// ## Benchmarking Zero Detection
879///
880/// ```
881/// use hexz_core::ops::write::is_zero_chunk;
882/// use std::time::Instant;
883///
884/// let chunk = vec![0u8; 64 * 1024 * 1024]; // 64 MiB
885/// let start = Instant::now();
886///
887/// for _ in 0..100 {
888///     let _ = is_zero_chunk(&chunk);
889/// }
890///
891/// let elapsed = start.elapsed();
892/// let throughput = (64.0 * 100.0) / elapsed.as_secs_f64(); // MB/s
893/// println!("Zero detection: {:.1} GB/s", throughput / 1024.0);
894/// ```
895///
896/// # SIMD Optimization
897///
898/// On x86-64 with AVX2, the compiler typically generates code like:
899///
900/// ```text
901/// vpxor    ymm0, ymm0, ymm0    ; Zero register
902/// loop:
903///   vmovdqu  ymm1, [rsi]        ; Load 32 bytes
904///   vpcmpeqb ymm2, ymm1, ymm0   ; Compare with zero
905///   vpmovmskb eax, ymm2         ; Extract comparison mask
906///   cmp      eax, 0xFFFFFFFF    ; All zeros?
907///   jne      found_nonzero      ; Early exit if not
908///   add      rsi, 32            ; Advance pointer
909///   loop
910/// ```
911///
912/// This processes 32 bytes per iteration (~1-2 cycles on modern CPUs).
913///
914/// # Edge Cases
915///
916/// - **Empty chunks**: Return `true` (vacuous truth, no non-zero bytes)
917/// - **Single byte**: Works correctly, no special handling needed
918/// - **Unaligned chunks**: SIMD code handles unaligned loads transparently
919///
920/// # Alternative Implementations
921///
922/// Other possible implementations (not currently used):
923///
924/// 1. **Manual SIMD**: Use `std::arch` for explicit SIMD (faster but less portable)
925/// 2. **Chunked comparison**: Process in 8-byte chunks with `u64` casts (faster scalar)
926/// 3. **Bitmap scan**: Use CPU's `bsf`/`tzcnt` to skip zero regions (complex)
927///
928/// Current implementation relies on compiler autovectorization, which works well
929/// in practice and maintains portability.
930///
931/// # Correctness
932///
933/// This function is pure and infallible:
934/// - No side effects (read-only operation)
935/// - No panics (iterator `all()` is safe for all inputs)
936/// - No undefined behavior (all byte patterns are valid)
937pub fn is_zero_chunk(chunk: &[u8]) -> bool {
938    chunk.iter().all(|&b| b == 0)
939}
940
941#[cfg(test)]
942mod tests {
943    use super::*;
944    use crate::algo::compression::{Lz4Compressor, ZstdCompressor};
945    use crate::algo::encryption::AesGcmEncryptor;
946    use std::io::Cursor;
947
948    /// Convenience wrapper that calls write_block_simple with no dedup map.
949    fn write_block_no_dedup<W: Write>(
950        out: &mut W,
951        chunk: &[u8],
952        block_idx: u64,
953        current_offset: &mut u64,
954        compressor: &dyn Compressor,
955        encryptor: Option<&dyn Encryptor>,
956    ) -> Result<BlockInfo> {
957        write_block_simple(
958            out,
959            chunk,
960            block_idx,
961            current_offset,
962            None::<&mut StandardHashTable>,
963            compressor,
964            encryptor,
965        )
966    }
967
968    #[test]
969    fn test_is_zero_chunk_all_zeros() {
970        let chunk = vec![0u8; 1024];
971        assert!(is_zero_chunk(&chunk));
972    }
973
974    #[test]
975    fn test_is_zero_chunk_with_nonzero() {
976        let mut chunk = vec![0u8; 1024];
977        chunk[512] = 1; // Single non-zero byte
978        assert!(!is_zero_chunk(&chunk));
979    }
980
981    #[test]
982    fn test_is_zero_chunk_all_nonzero() {
983        let chunk = vec![0xFFu8; 1024];
984        assert!(!is_zero_chunk(&chunk));
985    }
986
987    #[test]
988    fn test_is_zero_chunk_empty() {
989        let chunk: Vec<u8> = vec![];
990        assert!(is_zero_chunk(&chunk)); // Vacuous truth
991    }
992
993    #[test]
994    fn test_is_zero_chunk_single_zero() {
995        let chunk = vec![0u8];
996        assert!(is_zero_chunk(&chunk));
997    }
998
999    #[test]
1000    fn test_is_zero_chunk_single_nonzero() {
1001        let chunk = vec![1u8];
1002        assert!(!is_zero_chunk(&chunk));
1003    }
1004
1005    #[test]
1006    fn test_create_zero_block() {
1007        let logical_len = 65536;
1008        let info = create_zero_block(logical_len);
1009
1010        assert_eq!(info.offset, 0);
1011        assert_eq!(info.length, 0);
1012        assert_eq!(info.logical_len, logical_len);
1013        assert_eq!(info.checksum, 0);
1014    }
1015
1016    #[test]
1017    fn test_create_zero_block_various_sizes() {
1018        for size in [1, 16, 1024, 4096, 65536, 1048576] {
1019            let info = create_zero_block(size);
1020            assert_eq!(info.offset, 0);
1021            assert_eq!(info.length, 0);
1022            assert_eq!(info.logical_len, size);
1023            assert_eq!(info.checksum, 0);
1024        }
1025    }
1026
1027    #[test]
1028    fn test_write_block_basic_lz4() {
1029        let mut output = Cursor::new(Vec::new());
1030        let mut offset = 512u64; // Start after header
1031        let chunk = vec![0xAAu8; 4096];
1032        let compressor = Lz4Compressor::new();
1033
1034        let result = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None);
1035
1036        assert!(result.is_ok());
1037        let info = result.unwrap();
1038
1039        // Verify offset updated
1040        assert!(offset > 512);
1041
1042        // Verify block info
1043        assert_eq!(info.offset, 512);
1044        assert!(info.length > 0); // Compressed data written
1045        assert_eq!(info.logical_len, 4096);
1046        assert!(info.checksum != 0);
1047
1048        // Verify data was written
1049        let written = output.into_inner();
1050        assert_eq!(written.len(), (offset - 512) as usize);
1051    }
1052
1053    #[test]
1054    fn test_write_block_basic_zstd() {
1055        let mut output = Cursor::new(Vec::new());
1056        let mut offset = 512u64;
1057        let chunk = vec![0xAAu8; 4096];
1058        let compressor = ZstdCompressor::new(3, None);
1059
1060        let result = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None);
1061
1062        assert!(result.is_ok());
1063        let info = result.unwrap();
1064
1065        assert_eq!(info.offset, 512);
1066        assert!(info.length > 0);
1067        assert_eq!(info.logical_len, 4096);
1068    }
1069
1070    #[test]
1071    fn test_write_block_incompressible_data() {
1072        let mut output = Cursor::new(Vec::new());
1073        let mut offset = 512u64;
1074
1075        // Random-ish data that doesn't compress well
1076        let chunk: Vec<u8> = (0..4096).map(|i| ((i * 7 + 13) % 256) as u8).collect();
1077        let compressor = Lz4Compressor::new();
1078
1079        let result = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None);
1080
1081        assert!(result.is_ok());
1082        let info = result.unwrap();
1083
1084        // Even "incompressible" data might compress slightly or expand
1085        // Just verify it executed successfully
1086        assert_eq!(info.logical_len, chunk.len() as u32);
1087        assert!(info.length > 0);
1088    }
1089
1090    #[test]
1091    fn test_write_block_with_dedup_unique_blocks() {
1092        let mut output = Cursor::new(Vec::new());
1093        let mut offset = 512u64;
1094        let mut dedup_map = StandardHashTable::new();
1095        let compressor = Lz4Compressor::new();
1096
1097        // Write first block
1098        let chunk1 = vec![0xAAu8; 4096];
1099        let info1 = write_block_simple(
1100            &mut output,
1101            &chunk1,
1102            0,
1103            &mut offset,
1104            Some(&mut dedup_map),
1105            &compressor,
1106            None,
1107        )
1108        .unwrap();
1109
1110        let offset_after_block1 = offset;
1111
1112        // Write second unique block
1113        let chunk2 = vec![0xBBu8; 4096];
1114        let info2 = write_block_simple(
1115            &mut output,
1116            &chunk2,
1117            1,
1118            &mut offset,
1119            Some(&mut dedup_map),
1120            &compressor,
1121            None,
1122        )
1123        .unwrap();
1124
1125        // Both blocks should be written
1126        assert_eq!(info1.offset, 512);
1127        assert_eq!(info2.offset, offset_after_block1);
1128        assert!(offset > offset_after_block1);
1129
1130        // Dedup map should have 2 entries
1131        assert_eq!(dedup_map.len(), 2);
1132    }
1133
1134    #[test]
1135    fn test_write_block_with_dedup_duplicate_blocks() {
1136        let mut output = Cursor::new(Vec::new());
1137        let mut offset = 512u64;
1138        let mut dedup_map = StandardHashTable::new();
1139        let compressor = Lz4Compressor::new();
1140
1141        // Write first block
1142        let chunk1 = vec![0xAAu8; 4096];
1143        let info1 = write_block_simple(
1144            &mut output,
1145            &chunk1,
1146            0,
1147            &mut offset,
1148            Some(&mut dedup_map),
1149            &compressor,
1150            None,
1151        )
1152        .unwrap();
1153
1154        let offset_after_block1 = offset;
1155
1156        // Write duplicate block (same content)
1157        let chunk2 = vec![0xAAu8; 4096];
1158        let info2 = write_block_simple(
1159            &mut output,
1160            &chunk2,
1161            1,
1162            &mut offset,
1163            Some(&mut dedup_map),
1164            &compressor,
1165            None,
1166        )
1167        .unwrap();
1168
1169        // Second block should reuse first block's offset
1170        assert_eq!(info1.offset, info2.offset);
1171        assert_eq!(info1.length, info2.length);
1172        assert_eq!(info1.checksum, info2.checksum);
1173
1174        // Offset should not advance (no write)
1175        assert_eq!(offset, offset_after_block1);
1176
1177        // Dedup map should have 1 entry (deduplicated)
1178        assert_eq!(dedup_map.len(), 1);
1179    }
1180
1181    #[test]
1182    fn test_write_block_with_encryption() {
1183        let mut output = Cursor::new(Vec::new());
1184        let mut offset = 512u64;
1185        let chunk = vec![0xAAu8; 4096];
1186        let compressor = Lz4Compressor::new();
1187
1188        // Create encryptor
1189        let salt = [0u8; 32];
1190        let encryptor = AesGcmEncryptor::new(b"test_password", &salt, 100000).unwrap();
1191
1192        let result = write_block_no_dedup(
1193            &mut output,
1194            &chunk,
1195            0,
1196            &mut offset,
1197            &compressor,
1198            Some(&encryptor),
1199        );
1200
1201        assert!(result.is_ok());
1202        let info = result.unwrap();
1203
1204        // Encrypted data should be larger than compressed (adds GCM tag)
1205        assert!(info.length > 16); // At least tag overhead
1206        assert_eq!(info.logical_len, 4096);
1207    }
1208
1209    #[test]
1210    fn test_write_block_encryption_disables_dedup() {
1211        let mut output = Cursor::new(Vec::new());
1212        let mut offset = 512u64;
1213        let mut dedup_map = StandardHashTable::new();
1214        let compressor = Lz4Compressor::new();
1215        let salt = [0u8; 32];
1216        let encryptor = AesGcmEncryptor::new(b"test_password", &salt, 100000).unwrap();
1217
1218        // Write first encrypted block
1219        let chunk1 = vec![0xAAu8; 4096];
1220        let info1 = write_block_simple(
1221            &mut output,
1222            &chunk1,
1223            0,
1224            &mut offset,
1225            Some(&mut dedup_map),
1226            &compressor,
1227            Some(&encryptor),
1228        )
1229        .unwrap();
1230
1231        let offset_after_block1 = offset;
1232
1233        // Write second encrypted block (same content, different nonce)
1234        let chunk2 = vec![0xAAu8; 4096];
1235        let info2 = write_block_simple(
1236            &mut output,
1237            &chunk2,
1238            1,
1239            &mut offset,
1240            Some(&mut dedup_map),
1241            &compressor,
1242            Some(&encryptor),
1243        )
1244        .unwrap();
1245
1246        // Both blocks should be written (no dedup with encryption)
1247        assert_eq!(info1.offset, 512);
1248        assert_eq!(info2.offset, offset_after_block1);
1249        assert!(offset > offset_after_block1);
1250
1251        // Dedup map should be empty (encryption disables dedup)
1252        assert_eq!(dedup_map.len(), 0);
1253    }
1254
1255    #[test]
1256    fn test_write_block_multiple_sequential() {
1257        let mut output = Cursor::new(Vec::new());
1258        let mut offset = 512u64;
1259        let compressor = Lz4Compressor::new();
1260
1261        let mut expected_offset = 512u64;
1262
1263        // Write 10 blocks sequentially
1264        for i in 0..10 {
1265            let chunk = vec![i as u8; 4096];
1266            let info = write_block_no_dedup(&mut output, &chunk, i, &mut offset, &compressor, None)
1267                .unwrap();
1268
1269            assert_eq!(info.offset, expected_offset);
1270            expected_offset += info.length as u64;
1271        }
1272
1273        assert_eq!(offset, expected_offset);
1274    }
1275
1276    #[test]
1277    fn test_write_block_preserves_logical_length() {
1278        let mut output = Cursor::new(Vec::new());
1279        let mut offset = 512u64;
1280        let compressor = Lz4Compressor::new();
1281
1282        for size in [128, 1024, 4096, 65536] {
1283            let chunk = vec![0xAAu8; size];
1284            let info = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None)
1285                .unwrap();
1286
1287            assert_eq!(info.logical_len, size as u32);
1288        }
1289    }
1290
1291    #[test]
1292    fn test_write_block_checksum_differs() {
1293        let mut output1 = Cursor::new(Vec::new());
1294        let mut output2 = Cursor::new(Vec::new());
1295        let mut offset1 = 512u64;
1296        let mut offset2 = 512u64;
1297        let compressor = Lz4Compressor::new();
1298
1299        let chunk1 = vec![0xAAu8; 4096];
1300        let chunk2 = vec![0xBBu8; 4096];
1301
1302        let info1 = write_block_no_dedup(&mut output1, &chunk1, 0, &mut offset1, &compressor, None)
1303            .unwrap();
1304
1305        let info2 = write_block_no_dedup(&mut output2, &chunk2, 0, &mut offset2, &compressor, None)
1306            .unwrap();
1307
1308        // Different input data should produce different checksums
1309        assert_ne!(info1.checksum, info2.checksum);
1310    }
1311
1312    #[test]
1313    fn test_write_block_empty_chunk() {
1314        let mut output = Cursor::new(Vec::new());
1315        let mut offset = 512u64;
1316        let chunk: Vec<u8> = vec![];
1317        let compressor = Lz4Compressor::new();
1318
1319        let result = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None);
1320
1321        // Should handle empty chunk
1322        assert!(result.is_ok());
1323        let info = result.unwrap();
1324        assert_eq!(info.logical_len, 0);
1325    }
1326
1327    #[test]
1328    fn test_write_block_large_block() {
1329        let mut output = Cursor::new(Vec::new());
1330        let mut offset = 512u64;
1331        let chunk = vec![0xAAu8; 1024 * 1024]; // 1 MB
1332        let compressor = Lz4Compressor::new();
1333
1334        let result = write_block_no_dedup(&mut output, &chunk, 0, &mut offset, &compressor, None);
1335
1336        assert!(result.is_ok());
1337        let info = result.unwrap();
1338        assert_eq!(info.logical_len, 1024 * 1024);
1339        // Highly compressible data should compress well
1340        assert!(info.length < info.logical_len);
1341    }
1342
1343    #[test]
1344    fn test_integration_zero_detection_and_write() {
1345        let mut output = Cursor::new(Vec::new());
1346        let mut offset = 512u64;
1347        let compressor = Lz4Compressor::new();
1348
1349        let zero_chunk = vec![0u8; 4096];
1350        let data_chunk = vec![0xAAu8; 4096];
1351
1352        // Process zero chunk
1353        let zero_info = if is_zero_chunk(&zero_chunk) {
1354            create_zero_block(zero_chunk.len() as u32)
1355        } else {
1356            write_block_no_dedup(&mut output, &zero_chunk, 0, &mut offset, &compressor, None)
1357                .unwrap()
1358        };
1359
1360        // Process data chunk
1361        let data_info = if is_zero_chunk(&data_chunk) {
1362            create_zero_block(data_chunk.len() as u32)
1363        } else {
1364            write_block_no_dedup(&mut output, &data_chunk, 1, &mut offset, &compressor, None)
1365                .unwrap()
1366        };
1367
1368        // Zero block should not be written
1369        assert_eq!(zero_info.offset, 0);
1370        assert_eq!(zero_info.length, 0);
1371
1372        // Data block should be written
1373        assert_eq!(data_info.offset, 512);
1374        assert!(data_info.length > 0);
1375    }
1376}