zipora 3.1.2

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

use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId, Throughput};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use zipora::memory::{
    AdaptiveFiveLevelPool, ConcurrencyLevel, FiveLevelPoolConfig,
    NoLockingPool, MutexBasedPool, LockFreePool, ThreadLocalPool, FixedCapacityPool,
};

/// Benchmark configuration for consistent testing
struct BenchConfig {
    iterations: usize,
    allocation_size: usize,
    thread_count: usize,
}

impl BenchConfig {
    fn small() -> Self {
        Self {
            iterations: 1000,
            allocation_size: 64,
            thread_count: 1,
        }
    }

    fn medium() -> Self {
        Self {
            iterations: 10000,
            allocation_size: 512,
            thread_count: 4,
        }
    }

    fn large() -> Self {
        Self {
            iterations: 100000,
            allocation_size: 4096,
            thread_count: 8,
        }
    }
}

/// Benchmark Level 1: No Locking (single-threaded)
fn bench_no_locking_pool(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_1_no_locking");
    
    for config in [BenchConfig::small(), BenchConfig::medium(), BenchConfig::large()] {
        group.throughput(Throughput::Elements(config.iterations as u64));
        
        group.bench_with_input(
            BenchmarkId::new("alloc_free", format!("{}x{}", config.iterations, config.allocation_size)),
            &config,
            |b, config| {
                b.iter(|| {
                    let pool_config = FiveLevelPoolConfig::performance_optimized();
                    let mut pool = NoLockingPool::new(pool_config).unwrap();
                    
                    let mut offsets = Vec::with_capacity(config.iterations);
                    
                    // Allocation phase
                    for _ in 0..config.iterations {
                        let offset = pool.alloc(black_box(config.allocation_size)).unwrap();
                        offsets.push(offset);
                    }
                    
                    // Deallocation phase
                    for offset in offsets {
                        pool.free(offset, config.allocation_size).unwrap();
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark Level 2: Mutex-based locking
fn bench_mutex_based_pool(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_2_mutex_based");
    
    for config in [BenchConfig::small(), BenchConfig::medium()] {
        group.throughput(Throughput::Elements((config.iterations * config.thread_count) as u64));
        
        group.bench_with_input(
            BenchmarkId::new("concurrent_alloc_free", 
                format!("{}threads_{}x{}", config.thread_count, config.iterations, config.allocation_size)),
            &config,
            |b, config| {
                b.iter(|| {
                    let pool_config = FiveLevelPoolConfig::performance_optimized();
                    let pool = Arc::new(MutexBasedPool::new(pool_config).unwrap());
                    
                    let handles: Vec<_> = (0..config.thread_count)
                        .map(|_| {
                            let pool = Arc::clone(&pool);
                            let iterations = config.iterations;
                            let allocation_size = config.allocation_size;
                            
                            thread::spawn(move || {
                                let mut offsets = Vec::with_capacity(iterations);
                                
                                // Allocation phase
                                for _ in 0..iterations {
                                    let offset = pool.alloc(black_box(allocation_size)).unwrap();
                                    offsets.push(offset);
                                }
                                
                                // Deallocation phase
                                for offset in offsets {
                                    pool.free(offset, allocation_size).unwrap();
                                }
                            })
                        })
                        .collect();
                    
                    for handle in handles {
                        handle.join().unwrap();
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark Level 3: Lock-free programming
fn bench_lock_free_pool(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_3_lock_free");
    
    for config in [BenchConfig::small(), BenchConfig::medium(), BenchConfig::large()] {
        group.throughput(Throughput::Elements((config.iterations * config.thread_count) as u64));
        
        group.bench_with_input(
            BenchmarkId::new("concurrent_alloc_free", 
                format!("{}threads_{}x{}", config.thread_count, config.iterations, config.allocation_size)),
            &config,
            |b, config| {
                b.iter(|| {
                    let pool_config = FiveLevelPoolConfig::performance_optimized();
                    let pool = Arc::new(LockFreePool::new(pool_config).unwrap());
                    
                    let handles: Vec<_> = (0..config.thread_count)
                        .map(|_| {
                            let pool = Arc::clone(&pool);
                            let iterations = config.iterations;
                            let allocation_size = config.allocation_size;
                            
                            thread::spawn(move || {
                                let mut offsets = Vec::with_capacity(iterations);
                                
                                // Allocation phase
                                for _ in 0..iterations {
                                    let offset = pool.alloc(black_box(allocation_size)).unwrap();
                                    offsets.push(offset);
                                }
                                
                                // Deallocation phase
                                for offset in offsets {
                                    pool.free(offset, allocation_size).unwrap();
                                }
                            })
                        })
                        .collect();
                    
                    for handle in handles {
                        handle.join().unwrap();
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark Level 4: Thread-local caching
fn bench_thread_local_pool(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_4_thread_local");
    
    for config in [BenchConfig::small(), BenchConfig::medium()] {
        group.throughput(Throughput::Elements((config.iterations * config.thread_count) as u64));
        
        group.bench_with_input(
            BenchmarkId::new("concurrent_alloc_free", 
                format!("{}threads_{}x{}", config.thread_count, config.iterations, config.allocation_size)),
            &config,
            |b, config| {
                b.iter(|| {
                    let pool_config = FiveLevelPoolConfig::performance_optimized();
                    let pool = Arc::new(ThreadLocalPool::new(pool_config).unwrap());
                    
                    let handles: Vec<_> = (0..config.thread_count)
                        .map(|_| {
                            let pool = Arc::clone(&pool);
                            let iterations = config.iterations;
                            let allocation_size = config.allocation_size;
                            
                            thread::spawn(move || {
                                let mut offsets = Vec::with_capacity(iterations);
                                
                                // Allocation phase
                                for _ in 0..iterations {
                                    let offset = pool.alloc(black_box(allocation_size)).unwrap();
                                    offsets.push(offset);
                                }
                                
                                // Deallocation phase
                                for offset in offsets {
                                    pool.free(offset, allocation_size).unwrap();
                                }
                            })
                        })
                        .collect();
                    
                    for handle in handles {
                        handle.join().unwrap();
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark Level 5: Fixed capacity
fn bench_fixed_capacity_pool(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_5_fixed_capacity");
    
    for config in [BenchConfig::small(), BenchConfig::medium()] {
        group.throughput(Throughput::Elements(config.iterations as u64));
        
        group.bench_with_input(
            BenchmarkId::new("bounded_alloc_free", format!("{}x{}", config.iterations, config.allocation_size)),
            &config,
            |b, config| {
                b.iter(|| {
                    let mut pool_config = FiveLevelPoolConfig::performance_optimized();
                    pool_config.fixed_capacity = Some(16 * 1024 * 1024); // 16MB limit
                    let mut pool = FixedCapacityPool::new(pool_config).unwrap();
                    
                    let mut offsets = Vec::with_capacity(config.iterations);
                    
                    // Allocation phase
                    for _ in 0..config.iterations {
                        let offset = pool.alloc(black_box(config.allocation_size)).unwrap();
                        offsets.push(offset);
                    }
                    
                    // Deallocation phase
                    for offset in offsets {
                        pool.free(offset, config.allocation_size).unwrap();
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark adaptive selection mechanism
fn bench_adaptive_selection(c: &mut Criterion) {
    let mut group = c.benchmark_group("adaptive_selection");
    
    // Test different scenarios where adaptive selection should choose different levels
    let scenarios = [
        ("single_thread_small", BenchConfig::small()),
        ("multi_thread_medium", BenchConfig::medium()),
        ("high_concurrency_large", BenchConfig::large()),
    ];
    
    for (scenario_name, config) in scenarios {
        group.throughput(Throughput::Elements((config.iterations * config.thread_count) as u64));
        
        group.bench_with_input(
            BenchmarkId::new("adaptive_alloc_free", scenario_name),
            &config,
            |b, config| {
                b.iter(|| {
                    let pool_config = FiveLevelPoolConfig::performance_optimized();
                    let mut pool = AdaptiveFiveLevelPool::new(pool_config).unwrap();
                    
                    if config.thread_count == 1 {
                        // Single-threaded benchmark
                        let mut offsets = Vec::with_capacity(config.iterations);
                        
                        for _ in 0..config.iterations {
                            let offset = pool.alloc(black_box(config.allocation_size)).unwrap();
                            offsets.push(offset);
                        }
                        
                        for offset in offsets {
                            pool.free(offset, config.allocation_size).unwrap();
                        }
                    } else {
                        // Multi-threaded benchmark
                        let handle = pool.get_handle().unwrap();
                        let handles: Vec<_> = (0..config.thread_count)
                            .map(|_| {
                                let handle = handle.clone();
                                let iterations = config.iterations;
                                let allocation_size = config.allocation_size;
                                
                                thread::spawn(move || {
                                    let mut offsets = Vec::with_capacity(iterations);
                                    
                                    for _ in 0..iterations {
                                        let offset = handle.alloc(black_box(allocation_size)).unwrap();
                                        offsets.push(offset);
                                    }
                                    
                                    for offset in offsets {
                                        handle.free(offset, allocation_size).unwrap();
                                    }
                                })
                            })
                            .collect();
                        
                        for handle in handles {
                            handle.join().unwrap();
                        }
                    }
                });
            },
        );
    }
    
    group.finish();
}

/// Benchmark level comparison
fn bench_level_comparison(c: &mut Criterion) {
    let mut group = c.benchmark_group("level_comparison");
    group.throughput(Throughput::Elements(10000));
    
    let config = BenchConfig::medium();
    
    // Single-threaded comparison
    group.bench_function("level1_no_locking", |b| {
        b.iter(|| {
            let pool_config = FiveLevelPoolConfig::performance_optimized();
            let mut pool = AdaptiveFiveLevelPool::with_level(pool_config, ConcurrencyLevel::SingleThread).unwrap();
            
            let mut offsets = Vec::with_capacity(config.iterations);
            
            for _ in 0..config.iterations {
                let offset = pool.alloc(black_box(config.allocation_size)).unwrap();
                offsets.push(offset);
            }
            
            for offset in offsets {
                pool.free(offset, config.allocation_size).unwrap();
            }
        });
    });
    
    // Multi-threaded comparison (4 threads)
    let thread_count = 4;
    
    for (level_name, level) in [
        ("level2_mutex", ConcurrencyLevel::MultiThreadMutex),
        ("level3_lockfree", ConcurrencyLevel::MultiThreadLockFree),
        ("level4_threadlocal", ConcurrencyLevel::ThreadLocal),
    ] {
        group.bench_function(level_name, |b| {
            b.iter(|| {
                let pool_config = FiveLevelPoolConfig::performance_optimized();
                let pool = AdaptiveFiveLevelPool::with_level(pool_config, level).unwrap();
                let handle = pool.get_handle().unwrap();
                
                let handles: Vec<_> = (0..thread_count)
                    .map(|_| {
                        let handle = handle.clone();
                        let iterations = config.iterations / thread_count;
                        let allocation_size = config.allocation_size;
                        
                        thread::spawn(move || {
                            let mut offsets = Vec::with_capacity(iterations);
                            
                            for _ in 0..iterations {
                                let offset = handle.alloc(black_box(allocation_size)).unwrap();
                                offsets.push(offset);
                            }
                            
                            for offset in offsets {
                                handle.free(offset, allocation_size).unwrap();
                            }
                        })
                    })
                    .collect();
                
                for handle in handles {
                    handle.join().unwrap();
                }
            });
        });
    }
    
    group.finish();
}

/// Benchmark memory fragmentation behavior
fn bench_fragmentation_patterns(c: &mut Criterion) {
    let mut group = c.benchmark_group("fragmentation_patterns");
    
    // Test different allocation patterns that can cause fragmentation
    let patterns = [
        ("sequential", false),
        ("interleaved", true),
    ];
    
    for (pattern_name, interleaved) in patterns {
        group.bench_function(pattern_name, |b| {
            b.iter(|| {
                let pool_config = FiveLevelPoolConfig::memory_optimized();
                let mut pool = NoLockingPool::new(pool_config).unwrap();
                
                let iterations = 1000;
                let mut offsets = Vec::with_capacity(iterations);
                
                if interleaved {
                    // Interleaved allocation/deallocation pattern
                    for i in 0..iterations {
                        let size = if i % 3 == 0 { 64 } else if i % 3 == 1 { 128 } else { 256 };
                        let offset = pool.alloc(black_box(size)).unwrap();
                        offsets.push((offset, size));
                        
                        // Free every 4th allocation to create fragmentation
                        if i % 4 == 3 && !offsets.is_empty() {
                            let (free_offset, free_size) = offsets.remove(offsets.len() / 2);
                            pool.free(free_offset, free_size).unwrap();
                        }
                    }
                } else {
                    // Sequential allocation pattern
                    for i in 0..iterations {
                        let size = 64 + (i % 192); // Variable sizes 64-255
                        let offset = pool.alloc(black_box(size)).unwrap();
                        offsets.push((offset, size));
                    }
                }
                
                // Free remaining allocations
                for (offset, size) in offsets {
                    pool.free(offset, size).unwrap();
                }
            });
        });
    }
    
    group.finish();
}

/// Benchmark memory alignment behavior
fn bench_alignment_patterns(c: &mut Criterion) {
    let mut group = c.benchmark_group("alignment_patterns");
    
    let alignments = [8, 16, 32, 64];
    
    for alignment in alignments {
        group.bench_function(format!("align_{}", alignment), |b| {
            b.iter(|| {
                let mut pool_config = FiveLevelPoolConfig::performance_optimized();
                pool_config.alignment = alignment;
                let mut pool = NoLockingPool::new(pool_config).unwrap();
                
                let iterations = 1000;
                let mut offsets = Vec::with_capacity(iterations);
                
                for _ in 0..iterations {
                    let offset = pool.alloc(black_box(64)).unwrap();
                    offsets.push(offset);
                }
                
                for offset in offsets {
                    pool.free(offset, 64).unwrap();
                }
            });
        });
    }
    
    group.finish();
}

criterion_group!(
    benches,
    bench_no_locking_pool,
    bench_mutex_based_pool,
    bench_lock_free_pool,
    bench_thread_local_pool,
    bench_fixed_capacity_pool,
    bench_adaptive_selection,
    bench_level_comparison,
    bench_fragmentation_patterns,
    bench_alignment_patterns
);

criterion_main!(benches);