zipora 3.0.0

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
//! Core LRU cache data structures with thread-safe access

use super::*;
use crate::error::Result;
use crate::memory::SecureMemoryPool;
use std::sync::atomic::{AtomicU64, AtomicU32, AtomicU16, AtomicU8, Ordering};
use std::sync::{Arc, RwLock, Mutex};
use std::ptr::NonNull;

/// Cache node representing a cached page with dual linked-list participation
#[repr(align(64))] // Cache line aligned for performance
#[derive(Debug)]
pub struct CacheNode {
    /// Combined file ID (32-bit) + page ID (32-bit) for efficient hashing
    pub fi_offset: AtomicU64,
    
    /// Previous node in file-specific list
    pub fi_prev: AtomicU32,
    
    /// Next node in file-specific list
    pub fi_next: AtomicU32,
    
    /// Previous node in LRU list
    pub lru_prev: AtomicU32,
    
    /// Next node in LRU list
    pub lru_next: AtomicU32,
    
    /// Reference count for thread safety
    pub ref_count: AtomicU16,
    
    /// Loading status flag (0 = not loaded, 1 = loaded)
    pub is_loaded: AtomicU8,
    
    /// Hash collision chain link
    pub hash_link: AtomicU32,
    
    /// Page data pointer (points into page memory pool)
    pub page_data: AtomicU64, // Store as u64 for atomic access
    
    /// Last access timestamp for LRU ordering
    pub last_access: AtomicU64,
    
    /// Access frequency counter for LFU hints
    pub access_count: AtomicU32,
    
    /// Padding to ensure cache line alignment
    _padding: [u8; 8],
}

impl CacheNode {
    /// Create a new uninitialized cache node
    pub fn new() -> Self {
        Self {
            fi_offset: AtomicU64::new(u64::MAX),
            fi_prev: AtomicU32::new(INVALID_NODE),
            fi_next: AtomicU32::new(INVALID_NODE),
            lru_prev: AtomicU32::new(INVALID_NODE),
            lru_next: AtomicU32::new(INVALID_NODE),
            ref_count: AtomicU16::new(0),
            is_loaded: AtomicU8::new(0),
            hash_link: AtomicU32::new(INVALID_NODE),
            page_data: AtomicU64::new(0),
            last_access: AtomicU64::new(0),
            access_count: AtomicU32::new(0),
            _padding: [0; 8],
        }
    }
    
    /// Initialize node with file ID and page ID
    pub fn initialize(&self, file_id: FileId, page_id: PageId, page_ptr: *mut u8) {
        let fi_offset = ((file_id as u64) << 32) | (page_id as u64);
        self.fi_offset.store(fi_offset, Ordering::Relaxed);
        self.page_data.store(page_ptr as u64, Ordering::Relaxed);
        self.is_loaded.store(0, Ordering::Relaxed);
        self.ref_count.store(0, Ordering::Relaxed);
        self.access_count.store(0, Ordering::Relaxed);
        self.update_last_access();
    }
    
    /// Reset node to uninitialized state
    pub fn reset(&self) {
        self.fi_offset.store(u64::MAX, Ordering::Relaxed);
        self.fi_prev.store(INVALID_NODE, Ordering::Relaxed);
        self.fi_next.store(INVALID_NODE, Ordering::Relaxed);
        self.lru_prev.store(INVALID_NODE, Ordering::Relaxed);
        self.lru_next.store(INVALID_NODE, Ordering::Relaxed);
        self.ref_count.store(0, Ordering::Relaxed);
        self.is_loaded.store(0, Ordering::Relaxed);
        self.hash_link.store(INVALID_NODE, Ordering::Relaxed);
        self.page_data.store(0, Ordering::Relaxed);
        self.last_access.store(0, Ordering::Relaxed);
        self.access_count.store(0, Ordering::Relaxed);
    }
    
    /// Get file ID from packed fi_offset
    pub fn file_id(&self) -> FileId {
        let fi_offset = self.fi_offset.load(Ordering::Relaxed);
        (fi_offset >> 32) as FileId
    }
    
    /// Get page ID from packed fi_offset
    pub fn page_id(&self) -> PageId {
        let fi_offset = self.fi_offset.load(Ordering::Relaxed);
        fi_offset as PageId
    }
    
    /// Get combined file-page key
    pub fn fi_offset_key(&self) -> u64 {
        self.fi_offset.load(Ordering::Relaxed)
    }
    
    /// Check if node matches file and page
    pub fn matches(&self, file_id: FileId, page_id: PageId) -> bool {
        let expected = ((file_id as u64) << 32) | (page_id as u64);
        self.fi_offset.load(Ordering::Relaxed) == expected
    }
    
    /// Get page data pointer
    pub fn page_data_ptr(&self) -> *mut u8 {
        self.page_data.load(Ordering::Relaxed) as *mut u8
    }
    
    /// Check if page is loaded
    pub fn is_page_loaded(&self) -> bool {
        self.is_loaded.load(Ordering::Relaxed) != 0
    }
    
    /// Mark page as loaded
    pub fn mark_loaded(&self) {
        self.is_loaded.store(1, Ordering::Release);
    }
    
    /// Increment reference count
    pub fn inc_ref(&self) -> u16 {
        self.ref_count.fetch_add(1, Ordering::Relaxed)
    }
    
    /// Decrement reference count
    pub fn dec_ref(&self) -> u16 {
        self.ref_count.fetch_sub(1, Ordering::Relaxed) - 1
    }
    
    /// Get current reference count
    pub fn ref_count(&self) -> u16 {
        self.ref_count.load(Ordering::Relaxed)
    }
    
    /// Update last access timestamp
    pub fn update_last_access(&self) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u64;
        self.last_access.store(now, Ordering::Relaxed);
        self.access_count.fetch_add(1, Ordering::Relaxed);
    }
    
    /// Get last access timestamp
    pub fn last_access_time(&self) -> u64 {
        self.last_access.load(Ordering::Relaxed)
    }
    
    /// Get access count
    pub fn access_frequency(&self) -> u32 {
        self.access_count.load(Ordering::Relaxed)
    }
}

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

/// LRU linked list operations for cache nodes
pub struct LruList {
    /// Head node index (most recently used)
    head: AtomicU32,
    
    /// Tail node index (least recently used)
    tail: AtomicU32,
    
    /// Number of nodes in list
    count: AtomicU32,
}

impl LruList {
    /// Create new empty LRU list
    pub fn new() -> Self {
        Self {
            head: AtomicU32::new(INVALID_NODE),
            tail: AtomicU32::new(INVALID_NODE),
            count: AtomicU32::new(0),
        }
    }
    
    /// Insert node at head (most recently used)
    pub fn insert_head(&self, nodes: &[CacheNode], node_idx: NodeIndex) {
        let old_head = self.head.load(Ordering::Relaxed);
        
        nodes[node_idx as usize].lru_prev.store(INVALID_NODE, Ordering::Relaxed);
        nodes[node_idx as usize].lru_next.store(old_head, Ordering::Relaxed);
        
        if old_head != INVALID_NODE {
            nodes[old_head as usize].lru_prev.store(node_idx, Ordering::Relaxed);
        } else {
            // First node, also set as tail
            self.tail.store(node_idx, Ordering::Relaxed);
        }
        
        self.head.store(node_idx, Ordering::Relaxed);
        self.count.fetch_add(1, Ordering::Relaxed);
    }
    
    /// Remove node from list
    pub fn remove(&self, nodes: &[CacheNode], node_idx: NodeIndex) {
        let prev = nodes[node_idx as usize].lru_prev.load(Ordering::Relaxed);
        let next = nodes[node_idx as usize].lru_next.load(Ordering::Relaxed);
        
        if prev != INVALID_NODE {
            nodes[prev as usize].lru_next.store(next, Ordering::Relaxed);
        } else {
            // Removing head
            self.head.store(next, Ordering::Relaxed);
        }
        
        if next != INVALID_NODE {
            nodes[next as usize].lru_prev.store(prev, Ordering::Relaxed);
        } else {
            // Removing tail
            self.tail.store(prev, Ordering::Relaxed);
        }
        
        nodes[node_idx as usize].lru_prev.store(INVALID_NODE, Ordering::Relaxed);
        nodes[node_idx as usize].lru_next.store(INVALID_NODE, Ordering::Relaxed);
        
        self.count.fetch_sub(1, Ordering::Relaxed);
    }
    
    /// Move node to head (mark as most recently used)
    pub fn move_to_head(&self, nodes: &[CacheNode], node_idx: NodeIndex) {
        // Remove from current position
        self.remove(nodes, node_idx);
        // Insert at head
        self.insert_head(nodes, node_idx);
    }
    
    /// Get least recently used node (tail)
    pub fn get_lru_node(&self) -> NodeIndex {
        self.tail.load(Ordering::Relaxed)
    }
    
    /// Get most recently used node (head)
    pub fn get_mru_node(&self) -> NodeIndex {
        self.head.load(Ordering::Relaxed)
    }
    
    /// Get number of nodes in list
    pub fn count(&self) -> u32 {
        self.count.load(Ordering::Relaxed)
    }
    
    /// Check if list is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.count() == 0
    }
}

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

/// Hash table for fast page lookups
pub struct HashTable {
    /// Hash buckets (array of node indices)
    buckets: Vec<AtomicU32>,
    
    /// Hash table size (power of 2)
    size: usize,
    
    /// Mask for efficient modulo operation
    mask: u64,
    
    /// Collision statistics
    collisions: AtomicU64,
    
    /// Maximum probe distance encountered
    max_probe_distance: AtomicU32,
}

impl HashTable {
    /// Create new hash table with given size
    pub fn new(size: usize) -> Self {
        assert!(size.is_power_of_two(), "Hash table size must be power of 2");
        
        let mut buckets = Vec::with_capacity(size);
        buckets.resize_with(size, || AtomicU32::new(INVALID_NODE));
        
        Self {
            buckets,
            size,
            mask: (size - 1) as u64,
            collisions: AtomicU64::new(0),
            max_probe_distance: AtomicU32::new(0),
        }
    }
    
    /// Get hash bucket index for file-page combination
    #[inline]
    pub fn hash_index(&self, file_id: FileId, page_id: PageId) -> usize {
        let hash = hash_file_page(file_id, page_id);
        (hash & self.mask) as usize
    }
    
    /// Find node in hash table
    pub fn find(&self, nodes: &[CacheNode], file_id: FileId, page_id: PageId) -> Option<NodeIndex> {
        let bucket_idx = self.hash_index(file_id, page_id);
        let mut current = self.buckets[bucket_idx].load(Ordering::Relaxed);
        let mut probe_distance = 0;
        
        while current != INVALID_NODE {
            // Prefetch next node for better cache performance
            if current < nodes.len() as u32 {
                prefetch_hint(&nodes[current as usize] as *const _ as *const u8);
            }
            
            if nodes[current as usize].matches(file_id, page_id) {
                return Some(current);
            }
            
            current = nodes[current as usize].hash_link.load(Ordering::Relaxed);
            probe_distance += 1;
            
            // Update max probe distance statistics
            let current_max = self.max_probe_distance.load(Ordering::Relaxed);
            if probe_distance > current_max {
                let _ = self.max_probe_distance.compare_exchange_weak(
                    current_max, probe_distance, Ordering::Relaxed, Ordering::Relaxed
                );
            }
        }
        
        None
    }
    
    /// Insert node into hash table
    pub fn insert(&self, nodes: &[CacheNode], node_idx: NodeIndex, file_id: FileId, page_id: PageId) {
        let bucket_idx = self.hash_index(file_id, page_id);
        let old_head = self.buckets[bucket_idx].load(Ordering::Relaxed);
        
        // Link new node to old chain
        nodes[node_idx as usize].hash_link.store(old_head, Ordering::Relaxed);
        
        // Update bucket to point to new node
        self.buckets[bucket_idx].store(node_idx, Ordering::Relaxed);
        
        // Update collision statistics
        if old_head != INVALID_NODE {
            self.collisions.fetch_add(1, Ordering::Relaxed);
        }
    }
    
    /// Remove node from hash table
    pub fn remove(&self, nodes: &[CacheNode], node_idx: NodeIndex, file_id: FileId, page_id: PageId) {
        let bucket_idx = self.hash_index(file_id, page_id);
        let current = self.buckets[bucket_idx].load(Ordering::Relaxed);
        
        if current == node_idx {
            // Removing head of chain
            let next = nodes[node_idx as usize].hash_link.load(Ordering::Relaxed);
            self.buckets[bucket_idx].store(next, Ordering::Relaxed);
        } else {
            // Find and remove from middle of chain
            let mut prev = current;
            while prev != INVALID_NODE {
                let next = nodes[prev as usize].hash_link.load(Ordering::Relaxed);
                if next == node_idx {
                    let next_next = nodes[node_idx as usize].hash_link.load(Ordering::Relaxed);
                    nodes[prev as usize].hash_link.store(next_next, Ordering::Relaxed);
                    break;
                }
                prev = next;
            }
        }
        
        // Clear hash link
        nodes[node_idx as usize].hash_link.store(INVALID_NODE, Ordering::Relaxed);
    }
    
    /// Get collision count
    pub fn collision_count(&self) -> u64 {
        self.collisions.load(Ordering::Relaxed)
    }
    
    /// Get maximum probe distance
    pub fn max_probe_distance(&self) -> u32 {
        self.max_probe_distance.load(Ordering::Relaxed)
    }
    
    /// Get load factor
    pub fn load_factor(&self, total_nodes: usize) -> f64 {
        total_nodes as f64 / self.size as f64
    }
    
    /// Get hash table size
    #[inline]
    pub fn size(&self) -> usize {
        self.size
    }
}

/// File management for cache operations
#[derive(Debug)]
pub struct FileInfo {
    /// File descriptor or handle
    pub fd: i32,
    
    /// Head of file-specific page list
    pub head_page: AtomicU32,
    
    /// File size in bytes
    pub file_size: AtomicU64,
    
    /// File status flags
    pub status: AtomicU32,
    
    /// Number of cached pages for this file
    pub cached_pages: AtomicU32,
}

impl FileInfo {
    pub fn new(fd: i32) -> Self {
        Self {
            fd,
            head_page: AtomicU32::new(INVALID_NODE),
            file_size: AtomicU64::new(0),
            status: AtomicU32::new(0),
            cached_pages: AtomicU32::new(0),
        }
    }
    
    pub fn is_open(&self) -> bool {
        self.fd >= 0
    }
    
    pub fn mark_closed(&self) {
        self.status.store(1, Ordering::Relaxed); // 1 = closed
    }
    
    pub fn is_closed(&self) -> bool {
        self.status.load(Ordering::Relaxed) != 0
    }
}