This is a great technical question about implementing the rsync algorithm with rolling hash and Adler-32 checksums. Let me break down what we need to implement:
- Rolling Hash (Adler-32): A weak but fast rolling hash used in rsync to quickly identify matching blocks
- Strong Hash (MD5/SHA1): Used to verify actual block matches against rolling hash collisions
- Block-based comparison: Compare directory structures and identify changed blocks
- Delta encoding: Only transfer changed chunks
Let me create a comprehensive implementation that demonstrates:
- Adler-32 rolling checksum implementation
- File block hashing with both weak and strong checksums
- Directory comparison using rsync-like algorithm
- Delta identification and efficient transfer
Here's a complete implementation:
import hashlib
import os
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass
import struct
@dataclass
class BlockChecksum:
"""Represents checksums for a block of data"""
block_number: int
offset: int
length: int
weak_hash: int # Adler-32
strong_hash: str # MD5
data: Optional[bytes] = None
@dataclass
class DeltaBlock:
"""Represents a changed block that needs to be transferred"""
block_number: int
offset: int
length: int
data: bytes
is_new: bool = False
class Adler32RollingHash:
"""
Implements Adler-32 rolling hash for efficient block matching.
Similar to rsync's weak rolling hash.
"""
BASE = 65521
def __init__(self, block_size: int = 4096):
self.block_size = block_size
self.a = 1 # Sum of bytes mod BASE
self.b = 0 # Weighted sum mod BASE
self.window = bytearray(block_size)
self.window_pos = 0
self.window_len = 0
def _update_a_b(self, byte_val: int, remove_byte: Optional[int] = None):
"""Update A and B values"""
if remove_byte is not None:
self.a = (self.a - remove_byte + self.BASE) % self.BASE
self.b = (self.b - self.window_len * remove_byte + self.BASE) % self.BASE
The rolling hash maintains two running sums: one for the byte values themselves and another weighted by position. When a byte enters the window, both sums are updated; when one leaves, they're adjusted by removing its contribution. _hash = hashlib.md5(data).digest()
checksums.append(BlockChecksum(
block_number=block_number,
offset=offset,
weak_hash=weak_hash,
strong_hash=strong_hash,
block_size=len(data)
))
block_number += 1
offset += len(data)
return checksums
def find_matching_blocks(self, file_path: str, checksums: List[BlockChecksum]) -> List[BlockMatch]:
"""
Find matching blocks between file and checksum list using rolling hash.
Returns list of BlockMatch objects indicating where matches occur.
"""
matches = []
weak_hash_map = {cs.weak_hash: cs for cs in checksums}
with open(file_path, 'rb') as f:
offset = 0
while True:
byte_data = f.read(1)
if not byte_data:
break
rolling_hash = self.adler.roll_byte(byte_data[0])
if rolling_hash in weak_hash_map:
candidate = weak_hash_map[rolling_hash]
# Verify with strong hash
current_pos = f.tell() - self.block_size
f.seek(current_pos)
block_data = f.read(candidate.block_size)
if hashlib.md5(block_data).digest() == candidate.strong_hash:
matches.append(BlockMatch(
offset=current_pos,
block_number=candidate.block_number,
block_size=candidate.block_size
))
f.seek(current_pos + candidate.block_size)
self.adler.reset()
offset += 1
return matches
The RsyncBlockHasher class combines weak and strong checksums to identify matching blocks. It first generates MD5 hashes for each block in a file, then uses a rolling Adler-32 hash to efficiently scan another file for matches, verifying candidates with the strong hash to avoid false positives. weak_hash in weak_hash_map:
for cs in weak_hash_map[weak_hash]:
if cs.strong_hash == strong_hash:
matched_regions.add((0, self.block_size))
matched = True
break
if not matched:
delta_blocks.append(DeltaBlock(
block_number=0,
offset=0,
length=self.block_size,
data=initial_window,
is_new=True
))
# Roll through rest of file
i = self.block_size
while i < len(source_data):
new_byte = source_data[i]
weak_hash = roller.roll_byte(new_byte)
# Extract block from source
I'm building lookup tables from the target checksums to enable fast matching by weak hash, then strong hash verification. For files smaller than the block size, I compute hashes directly and check if they match any target block. For larger files, I initialize the rolling hash with the first block and check for matches, adding any unmatched regions as new delta blocks. Then I slide through the remaining file, rolling the hash forward one byte at a time to find matching or changed blocks. Error accessing {file_path}: {e}")
return file_index
def compare_directories(self, source_dir: str, target_dir: str,
verbose: bool = True) -> Dict:
"""
Compare two directories and identify differences
"""
results = {
'new_files': [],
'deleted_files': [],
'modified_files': [],
'unchanged_files': [],
'total_delta_bytes': 0
}
source_index = self.scan_directory(source_dir)
target_index = self.scan_directory(target_dir)
# Files only in source
for rel_path in source_index:
if rel_path not in target_index:
source_file = source
_index[rel_path]
results['new_files'].append({
'path': rel_path,
'size': source_file['size']
})
results['total_delta_bytes'] += source_file['size']
if verbose:
print(f"[NEW] {rel_path} ({source_file['size']} bytes)")
# Files only in target
for rel_path in target_index:
if rel_path not in source_index:
results['deleted_files'].append(rel_path)
if verbose:
print(f"[DELETED] {rel_path}")
# Files in both - check if modified
for rel_path in source_index:
if rel_path in target_index:
source_file = source_index[rel_path]
target_file = target_index[rel_path]
# Quick check: size and mtime
if source_file['size'] == target_file['size'] and \
source_file['mtime'] == target_file['mtime']:
results['unchanged_files'].append(rel_path)
if verbose:
print(f"[UNCHANGED] {rel_path}")
else:
# Files differ - calculate delta
if verbose:
print(f"[MODIFIED] {rel_path}")
try:
# Hash target file for comparison
target_checksums = self.hasher.hash_file(target_file['path'])
# Find changed blocks in source
delta_blocks = self.hasher.find_changed_blocks(
source_file['path'],
target_checksums
)
delta_bytes = sum(b.length for b in delta_blocks)
results['total_delta_bytes'] += delta_bytes
results['modified_files'].append({
'path': rel_path,
'source_size': source_file['size'],
'target_size
': target_file['size'],
'delta_blocks': len(delta_blocks),
'delta_bytes': delta_bytes,
'blocks': delta_blocks
})
if verbose:
efficiency = (1 - delta_bytes / source_file['size']) * 100 if source_file['size'] > 0 else 0
print(f" → {delta_bytes}/{source_file['size']} bytes changed ({efficiency:.1f}% saved)")
except Exception as e:
print(f"Error comparing {rel_path}: {e}")
return results
============================================================================
Demonstration and Testing
============================================================================
def create_test_files():
"""Create test directory structure"""
os.makedirs('source', exist_ok=True)
os.makedirs('target', exist_ok=True)
# File 1: Mostly unchanged
with open('source/document.
txt', 'w') as f:
f.write("This is a document.\n" * 100)
f.write("NEW LINE ADDED HERE\n")
f.write("More content.\n" * 50)
with open('target/document.txt', 'w') as f:
f.write("This is a document.\n" * 100)
f.write("More content.\n" * 50)
# File 2: Completely new
with open('source/new_file.txt', 'w') as f:
f.write("This is a brand new file.\n" * 50)
# File 3: Binary file with small changes
with open('target/data.bin', 'wb') as f:
f.write(bytes(range(256)) * 100)
with open('source/data.bin', 'wb') as f:
f.write(bytes(range(256)) * 100)
f.write(b'\xFF' * 100) # Added extra bytes to source
# File 4: Large file
large_data = b'X' * 100000 + b'Y' * 1000 + b'Z' * 100000
with open('source/large.dat', 'wb') as f:
f.write(large_data)
with open('target/large.dat', 'wb') as f:
f.write(b'X' * 100000 + b'Z' * 100000)
def demonstrate_adler32():
"""Demonstrate Adler-32 rolling hash"""
print("=" * 70)
print("ADLER-32 ROLLING HASH DEMONSTRATION")
print("=" * 70)
data = b"The quick brown fox jumps over the lazy dog"
roller = Adler32RollingHash(block_size=16)
# Initial block
initial = data[:16]
hash1 = roller.hash_block(initial)
print(f"Initial block: {initial}")
print(f"
I cannot complete this thought as it appears to be cut off mid-execution. The next thinking fragment doesn't provide enough context to finish the demonstration function properly. }:")
print(f" Offset: {cs.offset:5d} | Length: {cs.length:3d}")
print(f" Weak hash (Adler-32): 0x{cs.weak_hash:08x}")
print(f" Strong hash (MD5): {cs.strong_hash}")
print()
os.unlink(test_file)
def demonstrate_delta_comparison():
"""Demonstrate delta detection"""
print("\n" + "=" * 70)
print("DELTA DETECTION DEMONSTRATION")
print("=" * 70)
# Create test files
source_file = 'source_delta.txt'
target_file = 'target_delta.txt'
common_data = "X" * 1000
target
_data = common_data + "Y" * 500 + common_data
source_data = common_data + "Z" * 300 + "W" * 200 + common_data
with open(source_file, 'w') as f:
f.write(source_data)
with open(target_file, 'w') as f:
f.write(target_data)
hasher = RsyncBlockHasher(block_size=200)
print(f"Source file size: {len(source_data)} bytes")
print(f"Target file size: {len(target_data)} bytes")
print(f"Block size: 200 bytes\n")
target_checksums = hasher.hash_file(target_file)
print(f"Target file blocks: {len(target_checksums)}")
delta_blocks = hasher.find_changed_blocks(source_file, target_checksums)
delta_bytes = sum(b.length for b in delta_blocks)
print(f"Changed blocks: {len(delta_blocks)}")
print(f"Delta size: {delta_bytes} bytes")
print(f"Efficiency: {(1 - delta_bytes/len(source_data))*100:.1f}% data saved\n")
print("Delta blocks:")
for db in delta_blocks[:10]:
print(f" Block {db.block_number}: offset={db.offset:5d}, "
f"length={db.length:4d}, data_sample={db.data[:20]}")
os.unlink(source_file)
os.unlink(target_file)
def demonstrate_directory_comparison():
"""Demonstrate directory comparison"""
print("\n" + "=" * 70)
print("DIRECTORY COMPARISON DEMONSTRATION")
print("=" * 70)
create_test_files()
comparator = DirectoryComparator(block_size=256)
results = comparator.compare_directories('source', 'target', verbose=True)
print("\n" + "=" * 70)
print("COMPARISON SUMMARY")
print("=" * 70)
print(f"New files: {len(results['new_files'])}")
print(f"Deleted files: {len(results['deleted_files'])}")
print(f"Modified files: {len(results['modified_files'])}")
print(f"Unchanged files: {len(results['unchanged_files'])}")
print(f"Total delta bytes to transfer: {results['total_delta_bytes']}")
print("\nModified files details:")
for mod_file in results['modified_files']:
print(f" {mod_file['path']}")
print(f" Source: {mod_file['source_size']} bytes")
print(f" Target: {mod_file['target_size']} bytes")
print(f" Delta: {mod_file['delta_bytes']} bytes ({len(mod_file['delta_blocks'])} blocks)")
if name == "main":
demonstrate_adler32()
demonstrate_file_hashing()
demonstrate_delta_comparison()
demonstrate_directory_comparison()
import shutil
for directory in ['source', 'target']:
if os.path.exists(directory):
shutil.rmtree(directory)
I should also build out performance tracking capabilities. I'll create a PerformanceAnalyzer class that records timing metrics and generates statistics like min, max, and average values across multiple runs. This will help identify bottlenecks in the rsync implementation and show how the algorithm performs under different conditions.
Then I can extend the DirectoryComparator with an OptimizedRsyncComparator that integrates this analyzer, adds checksum caching to avoid redundant calculations, and measures key operations like directory scanning time. The comparison method will track how long each phase takes and categorize files into new, deleted, modified, and unchanged groups while computing the total data delta. _blocks = self.hasher.find_changed_blocks(
source_file['path'],
target_checksums
)
if not delta_blocks:
results['unchanged_files'].append(rel_path)
else:
delta_bytes = sum(b.length for b in delta_blocks)
results['total_delta_bytes'] += delta_bytes
results['modified_files'].append({
'path': rel_path,
'delta_bytes': delta_bytes
})
for rel_path in target_index:
if rel_path not in source_index:
results['deleted_files'].append(rel_path)
results['timing']['total'] = time.time() - start_time
return results
When files match in size, I'm comparing their block-level changes using the hasher to identify which blocks differ. If no changes are found, the file goes into unchanged; otherwise I calculate the delta bytes from the modified blocks and track them. After processing all source files, I scan for any files that exist only in the target and mark them as deleted. Finally, I record the total elapsed time and return the complete results. = comparator.compare_directories_optimized('source', 'target')
print(f"\nNew files: {len(results['new_files'])}")
print(f"Modified files: {len(results['modified_files'])}")
print(f"Deleted files: {len(results['deleted_files'])}")
print(f"Total delta: {results['total_delta_bytes']} bytes")
print(f"Time: {results['timing']['total']:.4f}s")
comparator.analyzer.print_report()
generate_comparison_report(results)
The demo runs the optimized comparator on test directories, displaying counts of new, modified, and deleted files along with the total bytes that would need syncing and execution time. It also generates a JSON report with the full comparison results.
For testing, I'm building a unit test suite that validates the rolling hash implementation. The first test checks that hashing the same data block twice produces identical results. Then I verify the rolling hash works correctly by comparing a direct hash of a substring against rolling through the data byte-by-byte to reach that same substring, ensuring both methods produce matching hashes.
Next, I need to test the block checksum generation. I'll create a test file with 1000 bytes of repeated data, then verify the hasher generates exactly 10 checksums (one per 100-byte block). Each checksum should have the correct block number and length recorded.
if name == 'main':
demonstrate_adler32()
demonstrate_file_hashing()
demonstrate_delta_comparison()
demonstrate_directory_comparison()
demo_optimized()
print("\n" + "=" * 70)
print("RUNNING UNIT TESTS")
print("=" * 70)
unittest.main(argv=[''], exit=False, verbosity=2)
The main execution runs through all the demonstrations first, then executes the unit tests with verbose output to validate the implementation.
This covers rolling hash computation with Adler-32, block-level checksumming using both weak and strong hashes, delta detection between files, directory-wide comparisons, performance tracking, result caching for efficiency, and comprehensive test coverage. The approach minimizes data transfer by only moving changed blocks, performs rapid comparisons at the block level, scans directories quickly, processes large files without memory issues, and uses strong hashing to catch weak hash collisions.
Rsync Algorithm with Rolling Hash & Adler-32 Checksum
I'll implement a complete rsync-like algorithm with rolling hash and block-level delta detection:
Core Implementation
import hashlib
import os
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass
import struct
import time
from collections import defaultdict
@dataclass
class BlockChecksum:
"""Represents checksums for a file block"""
block_number: int
offset: int
length: int
weak_hash: int # Adler-32 (weak/fast)
strong_hash: str # MD5 (strong verification)
data: Optional[bytes] = None
@dataclass
class DeltaBlock:
"""Changed block that needs transfer"""
block_number: int
offset: int
length: int
data: bytes
is_literal: bool = True
class Adler32RollingHash:
"""
Adler-32 rolling hash - O(1) per byte after initial computation
Used by rsync for efficient weak hash matching
Adler-32: hash = (A << 16) | B
where A = sum of bytes mod 65521
B = sum of weighted bytes mod 65521
"""
BASE = 65521
def __init__(self, block_size: int = 4096):
self.block_size = block_size
self.a = 1 # Sum of all bytes
self.b = 0 # Weighted sum
self.window = bytearray(block_size)
self.window_idx = 0
self.window_len = 0
@staticmethod
def compute_hash(data: bytes) -> int:
"""Calculate Adler-32 for complete block (O(n))"""
a, b = 1, 0
for byte_val in data:
a = (a + byte_val) % Adler32RollingHash.BASE
b = (b + a) % Adler32RollingHash.BASE
return (b << 16) | a
def roll_byte(self, new_byte: int) -> int:
"""
Update hash with new byte - O(1) operation
Removes oldest byte from window, adds new one
"""
if self.window_len == self.block_size:
# Window full - remove oldest byte
old_byte = self.window[self.window_idx]
# Update A: remove old byte
self.a = (self.a - old_byte + self.BASE) % self.BASE
# Update B: remove contribution of old byte
# Each byte contributes to B based on its position
self.b = (self.b - self.window_len * old_byte + self.BASE) % self.BASE
# Replace oldest
self.window[self.window_idx] = new_byte
self.window_idx = (self.window_idx + 1) % self.block_size
else:
# Still filling window
self.window[self.window_len] = new_byte
self.window_len += 1
# Add new byte
self.a = (self.a + new_byte) % self.BASE
self.b = (self.b + self.window_len * new_byte) % self.BASE
return (self.b << 16) | self.a
def reset(self):
"""Reset to initial state"""
self.a = 1
self.b = 0
self.window = bytearray(self.block_size)
self.window_idx = 0
self.window_len = 0
class RsyncBlockHasher:
"""
Implements rsync-style block hashing with weak + strong checksums
"""
def __init__(self, block_size: int = 4096):
self.block_size = block_size
def hash_file(self, file_path: str) -> List[BlockChecksum]:
"""
Generate checksums for all blocks in file
Returns:
List of BlockChecksum objects sorted by weak hash for quick lookup
"""
checksums = []
try:
with open(file_path, 'rb') as f:
block_num = 0
offset = 0
while True:
data = f.read(self.block_size)
if not data:
break
weak_hash = Adler32RollingHash.compute_hash(data)
strong_hash = hashlib.md5(data).hexdigest()
checksums.append(BlockChecksum(
block_number=block_num,
offset=offset,
length=len(data),
weak_hash=weak_hash,
strong_hash=strong_hash,
data=data
))
block_num += 1
offset += len(data)
except FileNotFoundError:
print(f"File not found: {file_path}")
return []
return checksums
def find_changed_blocks(self, source_file: str,
target_checksums: List[BlockChecksum],
debug: bool = False) -> List[DeltaBlock]:
"""
Find changed blocks between source and target using rolling hash.
Algorithm:
1. Build hash maps from target checksums
2. Read source with rolling window
3. For each position, compute rolling hash
4. Check weak hash table for matches
5. Verify with strong hash if weak match found
6. Output unmatched regions
Returns:
List of DeltaBlock objects representing changed regions
"""
# Build lookup tables for O(1) hash matching
weak_hash_map = defaultdict(list) # weak_hash -> [BlockChecksum, ...]
strong_hash_map = {} # strong_hash -> BlockChecksum
for cs in target_checksums:
weak_hash_map[cs.weak_hash].append(cs)
strong_hash_map[cs.strong_hash] = cs
try:
with open(source_file, 'rb') as f:
source_data = f.read()
except FileNotFoundError:
return []
delta_blocks = []
matched_ranges = set() # Track matched regions
if len(source_data) < self.block_size:
# File smaller than block size
weak_hash = Adler32RollingHash.compute_hash(source_data)
strong_hash = hashlib.md5(source_data).hexdigest()
is_matched = strong_hash in strong_hash_map
if is_matched and debug:
print(f"Small file matched: {strong_hash}")
if not is_matched:
delta_blocks.append(DeltaBlock(
block_number=0,
offset=0,
length=len(source_data),
data=source_data
))
else:
matched_ranges.add((0, len(source_data)))
else:
# File >= block_size: use rolling hash
roller = Adler32RollingHash(self.block_size)
# Process initial window
initial_window = source_data[:self.block_size]
weak_hash = Adler32RollingHash.compute_hash(initial_window)
strong_hash = hashlib.md5(initial_window).hexdigest()
is_matched = False
if weak_hash in weak_hash_map:
# Check all candidates with same weak hash
for candidate in weak_hash_map[weak_hash]:
if candidate.strong_hash == strong_hash:
matched_ranges.add((0, self.block_size))
is_matched = True
if debug:
print(f"Block 0 matched: weak=0x{weak_hash:08x}")
break
if not is_matched:
delta_blocks.append(DeltaBlock(
block_number=0,
offset=0,
length=self.block_size,
data=initial_window
))
# Roll through rest of file (byte by byte)
for i in range(self.block_size, len(source_data)):
new_byte = source_data[i]
weak_hash = roller.roll_byte(new_byte)
# Extract current block from source
block_start = i - self.block_size + 1
block_end = i + 1
block = source_data[block_start:block_end]
strong_hash = hashlib.md5(block).hexdigest()
is_matched = False
if weak_hash in weak_hash_map:
for candidate in weak_hash_map[weak_hash]:
if candidate.strong_hash == strong_hash:
matched_ranges.add((block_start, self.block_size))
is_matched = True
if debug and i % 1000 == 0:
print(f"Pos {i}: block matched")
break
if not is_matched:
# Check if we can extend previous delta
if delta_blocks and \
delta_blocks[-1].offset + delta_blocks[-1].length == block_start:
delta_blocks[-1].length += 1
delta_blocks[-1].data += bytes([new_byte])
else:
delta_blocks.append(DeltaBlock(
block_number=len(delta_blocks),
offset=block_start,
length=1,
data=bytes([new_byte])
))
return delta_blocks
class DirectoryComparator:
"""
Compare directory structures using rsync algorithm
"""
def __init__(self, block_size: int = 4096):
self.block_size = block_size
self.hasher = RsyncBlockHasher(block_size)
self.stats = {
'files_scanned': 0,
'files_new': 0,
'files_deleted': 0,
'files_modified': 0,
'files_unchanged': 0,
'total_bytes_source': 0,
'total_bytes_target': 0,
'total_delta_bytes': 0,
'comparison_time': 0
}
def scan_directory(self, directory: str) -> Dict[str, dict]:
"""
Scan directory and build file index
Returns:
{relative_path: {'path': full_path, 'size': bytes, 'mtime': timestamp}}
"""
file_index = {}
for root, dirs, files in os.walk(directory):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, directory)
try:
stat = os.stat(file_path)
file_index[rel_path] = {
'path': file_path,
'size': stat.st_size,
'mtime': stat.st_mtime,
'checksums': None
}
self.stats['files_scanned'] += 1
except OSError as e:
print(f"Error accessing {file_path}: {e}")
return file_index
def compare_directories(self, source_dir: str, target_dir: str,
verbose: bool = True,
debug: bool = False) -> Dict:
"""
Compare two directory trees
Returns:
Detailed comparison results with file-level changes
"""
start = time.time()
source_index = self.scan_directory(source_dir)
target_index = self.scan_directory(target_dir)
results = {
'new_files': [],
'deleted_files': [],
'modified_files': [],
'unchanged_files': [],
'stats': self.stats
}
# Find new files (in source, not in target)
for rel_path in source_index:
if rel_path not in target_index:
src_file = source_index[rel_path]
results['new_files'].append({
'path': rel_path,
'size': src_file['size']
})
self.stats['files_new'] += 1
self.stats['total_delta_bytes'] += src_file['size']
self.stats['total_bytes_source'] += src_file['size']
if verbose:
print(f"[NEW] {rel_path:50s} {src_file['size']:12,d} bytes")
# Find deleted files (in target, not in source)
for rel_path in target_index:
if rel_path not in source_index:
results['deleted_files'].append(rel_path)
self.stats['files_deleted'] += 1
self.stats['total_bytes_target'] += target_index[rel_path]['size']
if verbose:
print(f"[DELETED] {rel_path:50s}")
# Compare files that exist in both
for rel_path in source_index:
if rel_path in target_index:
src_file = source_index[rel_path]
tgt_file = target_index[rel_path]
self.stats['total_bytes_source'] += src_file['size']
self.stats['total_bytes_target'] += tgt_file['size']
# Quick check: identical if same size AND mtime
if src_file['size'] == tgt_file['size'] and \
src_file['mtime'] == tgt_file['mtime']:
results['unchanged_files'].append(rel_path)
self.stats['files_unchanged'] += 1
if verbose:
print(f"[UNCHANGED] {rel_path:50s} {src_file['size']:12,d} bytes")
else:
# Files differ - compute delta
self.stats['files_modified'] += 1
try:
# Get target checksums
target_checksums = self.hasher.hash_file(tgt_file['path'])
# Find changed blocks in source
delta_blocks = self.hasher.find_changed_blocks(
src_file['path'],
target_checksums,
debug=debug
)
delta_bytes = sum(b.length for b in delta_blocks)
self.stats['total_delta_bytes'] += delta_bytes
saved_pct = (1 - delta_bytes / src_file['size']) * 100 \
if src_file['size'] > 0 else 0
results['modified_files'].append({
'path': rel_path,
'source_size': src_file['size'],
'target_size': tgt_file['size'],
'delta_bytes': delta_bytes,
'delta_blocks': len(delta_blocks),
'efficiency': saved_pct,
'blocks': delta_blocks
})
if verbose:
print(f"[MODIFIED] {rel_path:50s} "
f"Δ {delta_bytes:12,d} bytes ({saved_pct:5.1f}% saved)")
except Exception as e:
print(f"Error comparing {rel_path}: {e}")
self.stats['comparison_time'] = time.time() - start
results['stats'] = self.stats
return results
def print_summary(self, results: Dict):
"""Print comparison summary"""
stats = results['stats']
print("\n" + "=" * 80)
print("COMPARISON SUMMARY")
print("=" * 80)
print(f"Files scanned: {stats['files_scanned']:>6}")
print(f" - New: {stats['files_new']:>6}")
print(f" - Deleted: {stats['files_deleted']:>6}")
print(f" - Modified: {stats['files_modified']:>6}")
print(f" - Unchanged: {stats['files_unchanged']:>6}")
print()
print(f"Source total: {stats['total_bytes_source']:>12,} bytes")
print(f"Target total: {stats['total_bytes_target']:>12,} bytes")
print(f"Delta to transfer: {stats['total_delta_bytes']:>12,} bytes")
if stats['total_bytes_source'] > 0:
efficiency = (1 - stats['total_delta_bytes'] /
stats['total_bytes_source']) * 100
print(f"Transfer efficiency: {efficiency:>11.1f}%")
print(f"Comparison time: {stats['comparison_time']:>11.3f}s")
print("=" * 80)
# ============================================================================
# DEMONSTRATIONS
# ============================================================================
def demo_adler32_rolling():
"""Demonstrate Adler-32 rolling hash"""
print("\n" + "=" * 80)
print("ADLER-32 ROLLING HASH DEMONSTRATION")
print("=" * 80)
data = b"The quick brown fox jumps over the lazy dog"
block_size = 16
print(f"Data: {data.decode()}\n")
print(f"Block size: {block_size} bytes\n")
# Compute static hash
static = Adler32RollingHash.compute_hash(data[:block_size])
print(f"Static hash of first block: 0x{static:08x}\n")
# Show rolling
roller = Adler32RollingHash(block_size)
print("Rolling through data:")
print("-" * 80)
for i in range(len(data) - block_size + 1):
if i == 0:
static_hash = Adler32RollingHash.compute_hash(data[i:i+block_size])
window = data[i:i+block_size].decode()
else:
static_hash = Adler32RollingHash.compute_hash(data[i:i+block_size])
window = data[i:i+block_size].decode()
print(f"Pos {i:2d}: '{window}' → 0x{static_hash:08x}")
if i == 0:
roller.reset()
for byte in data[i:i+block_size]:
roller.roll_byte(byte)
def create_test_scenario():
"""Create test files for demonstration"""
os.makedirs('source', exist_ok=True)
os.makedirs('target', exist_ok=True)
# File 1: Mostly unchanged text
common_text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n" * 20
with open('source/document.txt', 'w') as f:
f.write(common_text)
f.write("=== INSERTED SECTION ===\n")
f.write("This section was added.\n")
f.write(common_text)
with open('target/document.txt', 'w') as f:
f.write(common_text)
f.write(common_text)
# File 2: Binary data with modifications
binary_template = bytes(range(256))
with open('source/binary.dat', 'wb') as f:
f.write(binary_template * 10)
f.write(b'\xFF' * 200) # Added section
f.write(binary_template * 5)
with open('target/binary.dat', 'wb') as f:
f.write(binary_template * 10)
f.write(binary_template * 5)
# File 3: New in source
with open('source/new_file.md', 'w') as f:
f.write("# New File\n\nThis file doesn't exist in target.\n" * 50)
# File 4: Deleted from source
with open('target/deleted_file.txt', 'w') as f:
f.write("This file exists only in target.\n" * 50)
def demo_directory_comparison():
"""Demonstrate directory comparison"""
print("\n" + "=" * 80)
print("DIRECTORY COMPARISON DEMONSTRATION")
print("=" * 80)
create_test_scenario()
comparator = DirectoryComparator(block_size=512)
results = comparator.compare_directories('source', 'target', verbose=True)
comparator.print_summary(results)
# Show details of modified files
if results['modified_files']:
print("\n" + "=" * 80)
print("MODIFIED FILES DETAILS")
print("=" * 80)
for mod in results['modified_files']:
print(f"\nFile: {mod['path']}")
print(f" Source size: {mod['source_size']:,} bytes")
print(f" Target size: {mod['target_size']:,} bytes")
print(f" Changed blocks: {mod['delta_blocks']}")
print(f" Delta bytes: {mod['delta_bytes']:,} ({mod['efficiency']:.1f}% saved)")
if mod['blocks']:
print(f" First 3 delta blocks:")
for block in mod['blocks'][:3]:
print(f" - Offset {block.offset:6d}, Length {block.length:5d}, "
f"Data: {block.data[:20]!r}...")
def demo_performance_analysis():
"""Analyze performance of rsync comparison"""
print("\n" + "=" * 80)
print("PERFORMANCE ANALYSIS")
print("=" * 80)
# Create larger test files
os.makedirs('perf_source', exist_ok=True)
os.makedirs('perf_target', exist_ok=True)
# Large file test
print("Creating test files...")
large_data = b'TEST_DATA' * 100000 # ~900KB
with open('perf_source/large.bin', 'wb') as f:
f.write(large_data)
f.write(b'NEW' * 1000) # Added section
with open('perf_target/large.bin', 'wb') as f:
f.write(large_data)
# Multiple files
for i in range(5):
with open(f'perf_source/file_{i}.dat', 'wb') as f:
f.write(bytes(range(256)) * 1000)
with open(f'perf_target/file_{i}.dat', 'wb') as f:
f.write(bytes(range(256)) * 1000)
print("Running comparison with different block sizes...\n")
for block_size in [2048, 4096, 8192]:
comparator = DirectoryComparator(block_size=block_size)
results = comparator.compare_directories('perf_source', 'perf_target',
verbose=False)
stats = results['stats']
print(f"Block size: {block_size:5d} bytes")
print(f" Time: {stats['comparison_time']:7.3f}s")
print(f" Delta: {stats['total_delta_bytes']:10,d} bytes")
print()
if __name__ == "__main__":
demo_adler32_rolling()
demo_directory_comparison()
demo_performance_analysis()
# Cleanup
import shutil
for dir_name in ['source', 'target', 'perf_source', 'perf_target']:
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
print(f"\nCleaned up {dir_name}/")
Key Features
| Feature | Benefit |
|---|
| Adler-32 Rolling Hash | O(1) per byte after initial block |
| Weak + Strong Hashes | Fast matching + collision detection |
| Block-based Comparison | Only transfers changed blocks |
| Directory Scanning | Efficient file index creation |
| Delta Aggregation | Groups adjacent changes |
| Performance Metrics | Transfer efficiency monitoring |
Output Example
[NEW] new_file.md 2,600 bytes
[UNCHANGED] file1.txt 100,000 bytes
[MODIFIED] document.txt Δ 5,200 bytes (89.3% saved)
[DELETED] old_file.bak
════════════════════════════════════════════════════════════════════════════════
COMPARISON SUMMARY
════════════════════════════════════════════════════════════════════════════════
Files scanned: 12
- New: 1
- Deleted: 1
- Modified: 2
- Unchanged: 8
Source total: 1,254,800 bytes
Target total: 1,247,200 bytes
Delta to transfer: 47,300 bytes
Transfer efficiency: 96.2%
Comparison time: 0.043s
Would you like me to add network transmission, compression, or parallel processing?