cesiumdb 0.1.0

Blazing fast, persistent key-value store for Rust
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Buffer pool for reusable I/O buffers
//!
//! This module provides a thread-safe pool of reusable buffers to minimize
//! allocations during compaction and I/O operations.

use std::sync::{
    Arc,
    atomic::{
        AtomicU64,
        AtomicUsize,
        Ordering,
    },
};

use bytes::{
    Bytes,
    BytesMut,
};
use crossbeam_queue::SegQueue;

/// Default buffer size (64 KB)
pub const DEFAULT_BUFFER_SIZE: usize = 64 * 1024;

/// Maximum number of buffers to keep in the pool
pub const DEFAULT_MAX_POOLED: usize = 128;

/// A reusable buffer
///
/// When dropped, the buffer is returned to the pool if there's space.
pub struct PooledBuffer {
    /// The actual buffer data
    data: BytesMut,

    /// Reference to the pool (for returning on drop)
    pool: Arc<BufferPoolInner>,
}

impl PooledBuffer {
    /// Returns a mutable reference to the BytesMut
    #[inline]
    pub fn as_mut(&mut self) -> &mut BytesMut {
        &mut self.data
    }

    /// Returns an immutable slice of the buffer
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        &self.data
    }

    /// Returns the buffer capacity
    #[inline]
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Returns the buffer length
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns whether the buffer is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Clears the buffer (sets length to 0, keeps capacity)
    #[inline]
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Freezes the buffer into an immutable Bytes
    pub fn freeze(mut self) -> Bytes {
        // Take the data before drop runs
        let mut data = BytesMut::new();
        std::mem::swap(&mut data, &mut self.data);

        // Prevent the drop from returning to pool
        std::mem::forget(self);

        data.freeze()
    }

    /// Resizes the buffer to the given length
    #[inline]
    pub fn resize(&mut self, new_len: usize, value: u8) {
        self.data.resize(new_len, value);
    }

    /// Extends the buffer with data
    #[inline]
    pub fn extend_from_slice(&mut self, data: &[u8]) {
        self.data.extend_from_slice(data);
    }
}

impl Drop for PooledBuffer {
    fn drop(&mut self) {
        // Try to return the buffer to the pool
        if self.pool.pooled_count() < self.pool.max_pooled {
            // Clear the buffer before returning to pool
            self.data.clear();

            // Take ownership of the BytesMut
            let mut buffer = BytesMut::new();
            std::mem::swap(&mut buffer, &mut self.data);

            // Return to pool
            self.pool.return_buffer(buffer);
        }
        // Otherwise, drop the buffer (releases memory)
    }
}

impl std::ops::Deref for PooledBuffer {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl std::ops::DerefMut for PooledBuffer {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl AsRef<[u8]> for PooledBuffer {
    fn as_ref(&self) -> &[u8] {
        &self.data
    }
}

impl AsMut<[u8]> for PooledBuffer {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}

/// Inner buffer pool implementation
struct BufferPoolInner {
    /// Queue of available buffers
    buffers: SegQueue<BytesMut>,

    /// Buffer size for new allocations
    buffer_size: usize,

    /// Maximum number of buffers to keep pooled
    max_pooled: usize,

    /// Current number of pooled buffers
    pooled_count: AtomicUsize,

    /// Total number of buffers allocated
    total_allocated: AtomicU64,

    /// Number of times a buffer was reused from pool
    reuse_count: AtomicU64,

    /// Number of times we had to allocate a new buffer
    allocation_count: AtomicU64,
}

impl BufferPoolInner {
    fn new(buffer_size: usize, max_pooled: usize) -> Self {
        Self {
            buffers: SegQueue::new(),
            buffer_size,
            max_pooled,
            pooled_count: AtomicUsize::new(0),
            total_allocated: AtomicU64::new(0),
            reuse_count: AtomicU64::new(0),
            allocation_count: AtomicU64::new(0),
        }
    }

    fn get_buffer(&self) -> BytesMut {
        if let Some(buffer) = self.buffers.pop() {
            self.pooled_count.fetch_sub(1, Ordering::Relaxed);
            self.reuse_count.fetch_add(1, Ordering::Relaxed);
            buffer
        } else {
            // Allocate new buffer
            self.allocation_count.fetch_add(1, Ordering::Relaxed);
            self.total_allocated.fetch_add(1, Ordering::Relaxed);
            BytesMut::with_capacity(self.buffer_size)
        }
    }

    fn return_buffer(&self, buffer: BytesMut) {
        self.buffers.push(buffer);
        self.pooled_count.fetch_add(1, Ordering::Relaxed);
    }

    fn pooled_count(&self) -> usize {
        self.pooled_count.load(Ordering::Relaxed)
    }
}

/// Thread-safe buffer pool
///
/// The pool maintains a collection of reusable BytesMut buffers to minimize
/// allocation overhead during I/O operations.
#[derive(Clone)]
pub struct BufferPool {
    inner: Arc<BufferPoolInner>,
}

impl BufferPool {
    /// Creates a new buffer pool with default settings
    pub fn new() -> Self {
        Self::with_config(DEFAULT_BUFFER_SIZE, DEFAULT_MAX_POOLED)
    }

    /// Creates a new buffer pool with custom configuration
    ///
    /// # Arguments
    /// * `buffer_size` - Size of each buffer in bytes
    /// * `max_pooled` - Maximum number of buffers to keep in the pool
    pub fn with_config(buffer_size: usize, max_pooled: usize) -> Self {
        Self {
            inner: Arc::new(BufferPoolInner::new(buffer_size, max_pooled)),
        }
    }

    /// Gets a buffer from the pool
    ///
    /// If a buffer is available in the pool, it will be reused.
    /// Otherwise, a new buffer will be allocated.
    pub fn get(&self) -> PooledBuffer {
        let data = self.inner.get_buffer();

        PooledBuffer {
            data,
            pool: self.inner.clone(),
        }
    }

    /// Returns statistics about the buffer pool
    pub fn stats(&self) -> BufferPoolStats {
        BufferPoolStats {
            pooled: self.inner.pooled_count(),
            total_allocated: self.inner.total_allocated.load(Ordering::Relaxed),
            reuse_count: self.inner.reuse_count.load(Ordering::Relaxed),
            allocation_count: self.inner.allocation_count.load(Ordering::Relaxed),
            buffer_size: self.inner.buffer_size,
            max_pooled: self.inner.max_pooled,
        }
    }

    /// Returns the buffer size
    pub fn buffer_size(&self) -> usize {
        self.inner.buffer_size
    }

    /// Returns the maximum number of pooled buffers
    pub fn max_pooled(&self) -> usize {
        self.inner.max_pooled
    }

    /// Returns the current number of pooled buffers
    pub fn pooled_count(&self) -> usize {
        self.inner.pooled_count()
    }

    /// Calculates the reuse ratio (0.0 to 1.0)
    ///
    /// Higher values indicate better buffer reuse.
    pub fn reuse_ratio(&self) -> f64 {
        let reused = self.inner.reuse_count.load(Ordering::Relaxed);
        let allocated = self.inner.allocation_count.load(Ordering::Relaxed);
        let total = reused + allocated;

        if total == 0 {
            0.0
        } else {
            reused as f64 / total as f64
        }
    }
}

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

/// Statistics about the buffer pool
#[derive(Debug, Clone, Copy)]
pub struct BufferPoolStats {
    /// Number of buffers currently in the pool
    pub pooled: usize,

    /// Total number of buffers allocated
    pub total_allocated: u64,

    /// Number of times a buffer was reused
    pub reuse_count: u64,

    /// Number of times a new buffer was allocated
    pub allocation_count: u64,

    /// Size of each buffer
    pub buffer_size: usize,

    /// Maximum buffers kept in pool
    pub max_pooled: usize,
}

impl std::fmt::Display for BufferPoolStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let total_gets = self.reuse_count + self.allocation_count;
        let reuse_ratio = if total_gets == 0 {
            0.0
        } else {
            self.reuse_count as f64 / total_gets as f64 * 100.0
        };

        write!(
            f,
            "BufferPool: {} pooled, {} total allocated, {:.1}% reuse ratio",
            self.pooled, self.total_allocated, reuse_ratio
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pool_creation() {
        let pool = BufferPool::new();
        assert_eq!(pool.buffer_size(), DEFAULT_BUFFER_SIZE);
        assert_eq!(pool.max_pooled(), DEFAULT_MAX_POOLED);
        assert_eq!(pool.pooled_count(), 0);
    }

    #[test]
    fn test_buffer_allocation() {
        let pool = BufferPool::new();
        let buffer = pool.get();

        assert_eq!(buffer.capacity(), DEFAULT_BUFFER_SIZE);
        assert_eq!(buffer.len(), 0);
        assert!(buffer.is_empty());
    }

    #[test]
    fn test_buffer_return_to_pool() {
        let pool = BufferPool::new();

        {
            let _buffer = pool.get();
            assert_eq!(pool.pooled_count(), 0); // Buffer is in use
        } // Buffer dropped, returned to pool

        assert_eq!(pool.pooled_count(), 1); // Buffer returned
    }

    #[test]
    fn test_buffer_reuse() {
        let pool = BufferPool::new();

        // Get and return a buffer
        {
            let _buffer = pool.get();
        }

        assert_eq!(pool.pooled_count(), 1);

        // Get another buffer - should reuse the pooled one
        let buffer = pool.get();
        assert_eq!(pool.pooled_count(), 0);

        let stats = pool.stats();
        assert_eq!(stats.allocation_count, 1); // Only one allocation
        assert_eq!(stats.reuse_count, 1); // One reuse
    }

    #[test]
    fn test_max_pooled_limit() {
        let pool = BufferPool::with_config(1024, 2); // Max 2 buffers

        // Allocate 5 buffers and hold them
        let buffers: Vec<_> = (0..5).map(|_| pool.get()).collect();

        // Drop all buffers
        drop(buffers);

        // Should only keep 2 in pool
        assert_eq!(pool.pooled_count(), 2);
    }

    #[test]
    fn test_buffer_operations() {
        let pool = BufferPool::new();
        let mut buffer = pool.get();

        // Test resize
        buffer.resize(10, 0xff);
        assert_eq!(buffer.len(), 10);
        assert_eq!(buffer[0], 0xff);

        // Test clear
        buffer.clear();
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.capacity(), DEFAULT_BUFFER_SIZE);
    }

    #[test]
    fn test_buffer_extend() {
        let pool = BufferPool::new();
        let mut buffer = pool.get();

        buffer.extend_from_slice(b"hello");
        assert_eq!(buffer.len(), 5);
        assert_eq!(&buffer[..], b"hello");

        buffer.extend_from_slice(b" world");
        assert_eq!(buffer.len(), 11);
        assert_eq!(&buffer[..], b"hello world");
    }

    #[test]
    fn test_buffer_freeze() {
        let pool = BufferPool::new();
        let mut buffer = pool.get();

        buffer.extend_from_slice(b"test data");

        // Freeze into Bytes
        let bytes = buffer.freeze();
        assert_eq!(&bytes[..], b"test data");

        // Buffer should not be returned to pool after freeze
        assert_eq!(pool.pooled_count(), 0);
    }

    #[test]
    fn test_reuse_ratio() {
        let pool = BufferPool::new();

        // First get - allocation
        {
            let _buffer = pool.get();
        }

        // Second get - reuse
        {
            let _buffer = pool.get();
        }

        // Should be 50% reuse (1 alloc, 1 reuse)
        let ratio = pool.reuse_ratio();
        assert!((ratio - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_concurrent_access() {
        use std::thread;

        let pool = BufferPool::new();
        let pool_clone = pool.clone();

        // Spawn threads that get and release buffers
        let mut handles = vec![];
        for _ in 0..4 {
            let p = pool.clone();
            handles.push(thread::spawn(move || {
                for _ in 0..100 {
                    let mut buffer = p.get();
                    buffer.resize(1024, 0);
                    // Buffer dropped and returned
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        // Check that buffers were reused
        let stats = pool_clone.stats();
        assert!(stats.reuse_count > 0);
        assert!(stats.allocation_count < 400); // Should have reused many buffers
    }

    #[test]
    fn test_custom_buffer_size() {
        let pool = BufferPool::with_config(1024, 10);

        let buffer = pool.get();
        assert_eq!(buffer.capacity(), 1024);

        let stats = pool.stats();
        assert_eq!(stats.buffer_size, 1024);
    }

    #[test]
    fn test_stats_display() {
        let pool = BufferPool::new();

        {
            let _b1 = pool.get();
        }
        {
            let _b2 = pool.get();
        }

        let stats = pool.stats();
        let display = format!("{}", stats);
        assert!(display.contains("BufferPool"));
        assert!(display.contains("50.0%")); // 50% reuse ratio
    }

    #[test]
    fn test_bytes_mut_as_mut() {
        let pool = BufferPool::new();
        let mut buffer = pool.get();

        // Test mutable access via as_mut()
        buffer.as_mut().extend_from_slice(b"data");
        assert_eq!(buffer.len(), 4);
    }
}