pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
Documentation
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Unified Zero-Copy String Pool Implementation
//!
//! This module provides a high-performance string pool that stores all strings in contiguous
//! memory buffers, eliminating fragmentation and enabling true zero-copy string operations.
//!
//! Key features:
//! - Contiguous memory storage using ZeroCopyView<u8>
//! - Offset-based string indexing for O(1) access
//! - Cache-aware memory allocation and layout
//! - Zero-copy string views and operations
//! - Memory-mapped support for large string datasets
//! - Thread-safe concurrent access

use crate::core::error::{Error, Result};
use crate::storage::zero_copy::{ZeroCopyView, ZeroCopyManager, CacheLevel, MemoryMappedView};
use std::sync::{Arc, RwLock, Mutex};
use std::collections::HashMap;
use std::str;
use std::ops::Range;

/// Unified string pool that stores all strings in contiguous memory buffers
#[derive(Debug)]
pub struct UnifiedStringPool {
    /// Buffer manager for cache-aware allocation
    manager: Arc<ZeroCopyManager>,
    /// Primary string buffer storing all string data
    buffer: Arc<RwLock<ZeroCopyView<u8>>>,
    /// String metadata (offsets and lengths)
    strings: Arc<RwLock<Vec<StringMetadata>>>,
    /// Hash table for string deduplication (hash -> string_id)
    dedup_index: Arc<RwLock<HashMap<u64, u32>>>,
    /// Current buffer capacity and usage
    buffer_info: Arc<Mutex<BufferInfo>>,
    /// Pool configuration
    config: UnifiedStringPoolConfig,
}

/// Metadata for a string in the unified pool
#[derive(Debug, Clone, Copy)]
pub struct StringMetadata {
    /// Offset in the buffer where string starts
    pub offset: u32,
    /// Length of the string in bytes
    pub length: u32,
    /// Hash of the string for deduplication
    pub hash: u64,
    /// Reference count for memory management
    pub ref_count: u32,
}

/// Buffer information for the unified pool
#[derive(Debug)]
struct BufferInfo {
    /// Current position in the buffer
    current_pos: usize,
    /// Total capacity of the buffer
    capacity: usize,
    /// Number of strings stored
    string_count: usize,
    /// Total bytes used
    bytes_used: usize,
    /// Fragmentation ratio (0.0 = no fragmentation, 1.0 = high fragmentation)
    fragmentation_ratio: f64,
}

/// Configuration for the unified string pool
#[derive(Debug, Clone)]
pub struct UnifiedStringPoolConfig {
    /// Initial buffer size in bytes
    pub initial_buffer_size: usize,
    /// Maximum buffer size before switching to memory mapping
    pub max_buffer_size: usize,
    /// Enable string deduplication
    pub enable_deduplication: bool,
    /// Cache level for buffer allocation
    pub cache_level: CacheLevel,
    /// Compaction threshold (0.0-1.0)
    pub compaction_threshold: f64,
    /// Enable memory mapping for large pools
    pub enable_memory_mapping: bool,
}

impl Default for UnifiedStringPoolConfig {
    fn default() -> Self {
        Self {
            initial_buffer_size: 1024 * 1024,    // 1MB initial buffer
            max_buffer_size: 64 * 1024 * 1024,   // 64MB max before memory mapping
            enable_deduplication: true,
            cache_level: CacheLevel::L3,
            compaction_threshold: 0.3,
            enable_memory_mapping: true,
        }
    }
}

/// Zero-copy string view that references data in the unified pool
#[derive(Debug, Clone)]
pub struct UnifiedStringView {
    /// Metadata for the string
    metadata: StringMetadata,
    /// Pool reference for data access
    pool_ref: Arc<UnifiedStringPool>,
}

impl UnifiedStringView {
    /// Get the string as a String (allocates)
    pub fn as_str(&self) -> Result<String> {
        let buffer = self.pool_ref.buffer.read()
            .map_err(|_| Error::InvalidOperation("Failed to acquire buffer lock".to_string()))?;
        
        let start = self.metadata.offset as usize;
        let end = start + self.metadata.length as usize;
        
        if end > buffer.len() {
            return Err(Error::InvalidOperation("String extends beyond buffer".to_string()));
        }
        
        let data = &buffer.as_slice()[start..end];
        let s = str::from_utf8(data)
            .map_err(|e| Error::InvalidOperation(format!("Invalid UTF-8: {}", e)))?;
        
        Ok(s.to_string())
    }
    
    /// Get the string as bytes (allocates)
    pub fn as_bytes(&self) -> Result<Vec<u8>> {
        let buffer = self.pool_ref.buffer.read()
            .map_err(|_| Error::InvalidOperation("Failed to acquire buffer lock".to_string()))?;
        
        let start = self.metadata.offset as usize;
        let end = start + self.metadata.length as usize;
        
        if end > buffer.len() {
            return Err(Error::InvalidOperation("String extends beyond buffer".to_string()));
        }
        
        Ok(buffer.as_slice()[start..end].to_vec())
    }
    
    /// Get the length of the string
    pub fn len(&self) -> usize {
        self.metadata.length as usize
    }
    
    /// Check if the string is empty
    pub fn is_empty(&self) -> bool {
        self.metadata.length == 0
    }
    
    /// Get metadata for the string
    pub fn metadata(&self) -> StringMetadata {
        self.metadata
    }
    
    /// Create a substring view (zero-copy metadata, allocates on access)
    pub fn substring(&self, range: Range<usize>) -> Result<UnifiedStringView> {
        if range.start > self.len() || range.end > self.len() || range.start > range.end {
            return Err(Error::InvalidOperation("Invalid substring range".to_string()));
        }
        
        let sub_metadata = StringMetadata {
            offset: self.metadata.offset + range.start as u32,
            length: (range.end - range.start) as u32,
            hash: 0, // Will be computed if needed
            ref_count: 1,
        };
        
        Ok(UnifiedStringView {
            metadata: sub_metadata,
            pool_ref: Arc::clone(&self.pool_ref),
        })
    }
}

impl std::fmt::Display for UnifiedStringView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str().unwrap_or_else(|_| "<invalid UTF-8>".to_string()))
    }
}

impl UnifiedStringPool {
    /// Create a new unified string pool
    pub fn new(config: UnifiedStringPoolConfig) -> Result<Self> {
        let manager = Arc::new(ZeroCopyManager::new()?);
        
        // Allocate initial buffer
        let buffer = manager.create_view(vec![0u8; config.initial_buffer_size])?;
        
        let buffer_info = BufferInfo {
            current_pos: 0,
            capacity: config.initial_buffer_size,
            string_count: 0,
            bytes_used: 0,
            fragmentation_ratio: 0.0,
        };
        
        Ok(Self {
            manager,
            buffer: Arc::new(RwLock::new(buffer)),
            strings: Arc::new(RwLock::new(Vec::new())),
            dedup_index: Arc::new(RwLock::new(HashMap::new())),
            buffer_info: Arc::new(Mutex::new(buffer_info)),
            config,
        })
    }
    
    /// Create a new unified string pool with default configuration
    pub fn with_default_config() -> Result<Self> {
        Self::new(UnifiedStringPoolConfig::default())
    }
    
    /// Add a string to the pool and return its ID
    pub fn add_string(&self, s: &str) -> Result<u32> {
        let bytes = s.as_bytes();
        let hash = self.hash_string(s);
        
        // Check for existing string if deduplication is enabled
        if self.config.enable_deduplication {
            let dedup_index = self.dedup_index.read()
                .map_err(|_| Error::InvalidOperation("Failed to acquire dedup index lock".to_string()))?;
            
            if let Some(&existing_id) = dedup_index.get(&hash) {
                self.increment_ref_count(existing_id)?;
                return Ok(existing_id);
            }
        }
        
        // Add new string to pool
        self.add_new_string(bytes, hash)
    }
    
    /// Add multiple strings to the pool efficiently
    pub fn add_strings(&self, strings: &[String]) -> Result<Vec<u32>> {
        let mut result = Vec::with_capacity(strings.len());
        
        for s in strings {
            result.push(self.add_string(s)?);
        }
        
        Ok(result)
    }
    
    /// Get a zero-copy view of a string by ID
    pub fn get_string(&self, string_id: u32) -> Result<UnifiedStringView> {
        let strings = self.strings.read()
            .map_err(|_| Error::InvalidOperation("Failed to acquire strings lock".to_string()))?;
        
        let metadata = strings.get(string_id as usize)
            .ok_or_else(|| Error::InvalidOperation(format!("String ID {} not found", string_id)))?
            .clone();
        
        Ok(UnifiedStringView {
            metadata,
            pool_ref: Arc::new(self.clone()),
        })
    }
    
    /// Get multiple strings by their IDs
    pub fn get_strings(&self, string_ids: &[u32]) -> Result<Vec<UnifiedStringView>> {
        let mut result = Vec::with_capacity(string_ids.len());
        
        for &id in string_ids {
            result.push(self.get_string(id)?);
        }
        
        Ok(result)
    }
    
    /// Get string as a regular String (with allocation)
    pub fn get_string_owned(&self, string_id: u32) -> Result<String> {
        let view = self.get_string(string_id)?;
        Ok(view.as_str()?.to_string())
    }
    
    /// Compact the pool to reduce fragmentation
    pub fn compact(&self) -> Result<()> {
        let buffer_info = self.buffer_info.lock()
            .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
        
        if buffer_info.fragmentation_ratio < self.config.compaction_threshold {
            return Ok(()); // No compaction needed
        }
        
        drop(buffer_info);
        
        // Create new compacted buffer
        self.create_compacted_buffer()
    }
    
    /// Get pool statistics
    pub fn stats(&self) -> Result<UnifiedStringPoolStats> {
        let buffer_info = self.buffer_info.lock()
            .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
        
        let strings = self.strings.read()
            .map_err(|_| Error::InvalidOperation("Failed to acquire strings lock".to_string()))?;
        
        let dedup_index = self.dedup_index.read()
            .map_err(|_| Error::InvalidOperation("Failed to acquire dedup index lock".to_string()))?;
        
        Ok(UnifiedStringPoolStats {
            total_strings: strings.len(),
            unique_strings: dedup_index.len(),
            total_bytes: buffer_info.bytes_used,
            buffer_capacity: buffer_info.capacity,
            fragmentation_ratio: buffer_info.fragmentation_ratio,
            deduplication_ratio: if strings.len() > 0 {
                1.0 - (dedup_index.len() as f64 / strings.len() as f64)
            } else {
                0.0
            },
            memory_efficiency: if buffer_info.capacity > 0 {
                buffer_info.bytes_used as f64 / buffer_info.capacity as f64
            } else {
                0.0
            },
        })
    }
    
    /// Private method to add a new string to the pool
    fn add_new_string(&self, bytes: &[u8], hash: u64) -> Result<u32> {
        let mut buffer_info = self.buffer_info.lock()
            .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
        
        // Check if we need to expand the buffer
        if buffer_info.current_pos + bytes.len() > buffer_info.capacity {
            drop(buffer_info);
            self.expand_buffer(bytes.len())?;
            buffer_info = self.buffer_info.lock()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
        }
        
        let offset = buffer_info.current_pos as u32;
        
        // Copy string data to buffer
        {
            let mut buffer = self.buffer.write()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer write lock".to_string()))?;
            
            unsafe {
                let dest = &mut buffer.as_mut_slice()[buffer_info.current_pos..buffer_info.current_pos + bytes.len()];
                dest.copy_from_slice(bytes);
            }
        }
        
        // Create metadata
        let metadata = StringMetadata {
            offset,
            length: bytes.len() as u32,
            hash,
            ref_count: 1,
        };
        
        // Add to strings vector
        let string_id = {
            let mut strings = self.strings.write()
                .map_err(|_| Error::InvalidOperation("Failed to acquire strings write lock".to_string()))?;
            
            let id = strings.len() as u32;
            strings.push(metadata);
            id
        };
        
        // Add to deduplication index if enabled
        if self.config.enable_deduplication {
            let mut dedup_index = self.dedup_index.write()
                .map_err(|_| Error::InvalidOperation("Failed to acquire dedup index write lock".to_string()))?;
            
            dedup_index.insert(hash, string_id);
        }
        
        // Update buffer info
        buffer_info.current_pos += bytes.len();
        buffer_info.bytes_used += bytes.len();
        buffer_info.string_count += 1;
        
        Ok(string_id)
    }
    
    /// Expand the buffer capacity
    fn expand_buffer(&self, min_additional_size: usize) -> Result<()> {
        let new_capacity = {
            let buffer_info = self.buffer_info.lock()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
            
            let current_capacity = buffer_info.capacity;
            let required_capacity = buffer_info.current_pos + min_additional_size;
            
            // Double the capacity or ensure we have enough space
            (current_capacity * 2).max(required_capacity)
        };
        
        // Check if we should switch to memory mapping
        if new_capacity > self.config.max_buffer_size && self.config.enable_memory_mapping {
            return self.switch_to_memory_mapping(new_capacity);
        }
        
        // Create new larger buffer
        let new_buffer = self.manager.create_view(vec![0u8; new_capacity])?;
        
        // Copy existing data
        {
            let old_buffer = self.buffer.read()
                .map_err(|_| Error::InvalidOperation("Failed to acquire old buffer lock".to_string()))?;
            
            let buffer_info = self.buffer_info.lock()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
            
            unsafe {
                let src = old_buffer.as_slice();
                let dest = &new_buffer.as_slice()[..buffer_info.current_pos];
                // Copy would be: dest.copy_from_slice(&src[..buffer_info.current_pos]);
                // But we need mutable access, so we'll do this in the write section
            }
        }
        
        {
            let mut buffer = self.buffer.write()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer write lock".to_string()))?;
            
            let buffer_info = self.buffer_info.lock()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
            
            unsafe {
                let src = buffer.as_slice();
                std::ptr::copy_nonoverlapping(
                    src.as_ptr(),
                    new_buffer.as_slice().as_ptr() as *mut u8,
                    buffer_info.current_pos
                );
            }
            
            *buffer = new_buffer;
        }
        
        // Update buffer info
        {
            let mut buffer_info = self.buffer_info.lock()
                .map_err(|_| Error::InvalidOperation("Failed to acquire buffer info lock".to_string()))?;
            
            buffer_info.capacity = new_capacity;
        }
        
        Ok(())
    }
    
    /// Switch to memory mapping for very large string pools
    fn switch_to_memory_mapping(&self, _required_capacity: usize) -> Result<()> {
        // For now, return an error. This would be implemented for very large datasets
        Err(Error::NotImplemented("Memory mapping for large string pools".to_string()))
    }
    
    /// Create a compacted version of the buffer
    fn create_compacted_buffer(&self) -> Result<()> {
        // This would implement defragmentation by creating a new buffer
        // and copying only active strings in contiguous order
        Err(Error::NotImplemented("Buffer compaction".to_string()))
    }
    
    /// Increment reference count for a string
    fn increment_ref_count(&self, string_id: u32) -> Result<()> {
        let mut strings = self.strings.write()
            .map_err(|_| Error::InvalidOperation("Failed to acquire strings write lock".to_string()))?;
        
        if let Some(metadata) = strings.get_mut(string_id as usize) {
            metadata.ref_count += 1;
        }
        
        Ok(())
    }
    
    /// Hash a string for deduplication
    fn hash_string(&self, s: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        
        let mut hasher = DefaultHasher::new();
        s.hash(&mut hasher);
        hasher.finish()
    }
}

// Implement Clone manually to avoid requiring T: Clone
impl Clone for UnifiedStringPool {
    fn clone(&self) -> Self {
        Self {
            manager: Arc::clone(&self.manager),
            buffer: Arc::clone(&self.buffer),
            strings: Arc::clone(&self.strings),
            dedup_index: Arc::clone(&self.dedup_index),
            buffer_info: Arc::clone(&self.buffer_info),
            config: self.config.clone(),
        }
    }
}

/// Statistics for the unified string pool
#[derive(Debug, Clone)]
pub struct UnifiedStringPoolStats {
    /// Total number of strings (including duplicates)
    pub total_strings: usize,
    /// Number of unique strings
    pub unique_strings: usize,
    /// Total bytes used for string data
    pub total_bytes: usize,
    /// Total buffer capacity
    pub buffer_capacity: usize,
    /// Fragmentation ratio (0.0 = no fragmentation)
    pub fragmentation_ratio: f64,
    /// Deduplication ratio (0.0 = no deduplication, 1.0 = all duplicates)
    pub deduplication_ratio: f64,
    /// Memory efficiency ratio (used/capacity)
    pub memory_efficiency: f64,
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_unified_string_pool_creation() {
        let pool = UnifiedStringPool::with_default_config().expect("operation should succeed");
        let stats = pool.stats().expect("operation should succeed");
        
        assert_eq!(stats.total_strings, 0);
        assert_eq!(stats.unique_strings, 0);
        assert!(stats.buffer_capacity > 0);
    }
    
    #[test]
    fn test_string_addition_and_retrieval() {
        let pool = UnifiedStringPool::with_default_config().expect("operation should succeed");
        
        let id1 = pool.add_string("hello").expect("operation should succeed");
        let id2 = pool.add_string("world").expect("operation should succeed");
        let id3 = pool.add_string("hello").expect("operation should succeed"); // Duplicate
        
        assert_ne!(id1, id2);
        assert_eq!(id1, id3); // Should be deduplicated
        
        let view1 = pool.get_string(id1).expect("operation should succeed");
        let view2 = pool.get_string(id2).expect("operation should succeed");
        
        assert_eq!(view1.as_str().expect("operation should succeed"), "hello");
        assert_eq!(view2.as_str().expect("operation should succeed"), "world");
        
        let stats = pool.stats().expect("operation should succeed");
        assert_eq!(stats.total_strings, 2); // Only unique strings counted
    }
    
    #[test]
    fn test_multiple_string_operations() {
        let pool = UnifiedStringPool::with_default_config().expect("operation should succeed");
        
        let strings = vec![
            "apple".to_string(),
            "banana".to_string(),
            "cherry".to_string(),
            "apple".to_string(), // Duplicate
        ];
        
        let ids = pool.add_strings(&strings).expect("operation should succeed");
        assert_eq!(ids.len(), 4);
        assert_eq!(ids[0], ids[3]); // Duplicates should have same ID
        
        let views = pool.get_strings(&ids).expect("operation should succeed");
        assert_eq!(views.len(), 4);
        assert_eq!(views[0].as_str().expect("operation should succeed"), "apple");
        assert_eq!(views[1].as_str().expect("operation should succeed"), "banana");
        assert_eq!(views[2].as_str().expect("operation should succeed"), "cherry");
        assert_eq!(views[3].as_str().expect("operation should succeed"), "apple");
    }
    
    #[test]
    fn test_zero_copy_substring() {
        let pool = UnifiedStringPool::with_default_config().expect("operation should succeed");
        
        let id = pool.add_string("hello world").expect("operation should succeed");
        let view = pool.get_string(id).expect("operation should succeed");
        
        let substring = view.substring(0..5).expect("operation should succeed");
        assert_eq!(substring.as_str().expect("operation should succeed"), "hello");
        
        let substring2 = view.substring(6..11).expect("operation should succeed");
        assert_eq!(substring2.as_str().expect("operation should succeed"), "world");
    }
    
    #[test]
    fn test_pool_statistics() {
        let pool = UnifiedStringPool::with_default_config().expect("operation should succeed");
        
        pool.add_string("test").expect("operation should succeed");
        pool.add_string("data").expect("operation should succeed");
        pool.add_string("test").expect("operation should succeed"); // Duplicate
        
        let stats = pool.stats().expect("operation should succeed");
        assert_eq!(stats.total_strings, 2); // 2 unique strings
        assert_eq!(stats.unique_strings, 2);
        assert!(stats.total_bytes > 0);
        assert!(stats.deduplication_ratio > 0.0); // Should have some deduplication
    }
    
    #[test]
    fn test_buffer_expansion() {
        let mut config = UnifiedStringPoolConfig::default();
        config.initial_buffer_size = 16; // Very small buffer to force expansion
        
        let pool = UnifiedStringPool::new(config).expect("operation should succeed");
        
        // Add strings that will exceed initial buffer size
        for i in 0..10 {
            let s = format!("this is a longer string {}", i);
            pool.add_string(&s).expect("operation should succeed");
        }
        
        let stats = pool.stats().expect("operation should succeed");
        assert!(stats.buffer_capacity > 16); // Buffer should have expanded
        assert_eq!(stats.total_strings, 10);
    }
}