Skip to main content

rafka_core/
memory_pool.rs

1use std::sync::Arc;
2use tokio::sync::Mutex;
3use std::collections::VecDeque;
4
5/// Memory pool for reusing message objects to reduce allocations
6pub struct MessagePool<T> {
7    pool: Arc<Mutex<VecDeque<T>>>,
8    max_size: usize,
9}
10
11impl<T: Default + Send + Sync + 'static> MessagePool<T> {
12    pub fn new(max_size: usize) -> Self {
13        Self {
14            pool: Arc::new(Mutex::new(VecDeque::new())),
15            max_size,
16        }
17    }
18
19    /// Get a message from the pool or create a new one
20    pub async fn get(&self) -> PooledMessage<T> {
21        let mut pool = self.pool.lock().await;
22        
23        if let Some(message) = pool.pop_front() {
24            PooledMessage {
25                message: Some(message),
26                pool: self.clone(),
27            }
28        } else {
29            PooledMessage {
30                message: Some(T::default()),
31                pool: self.clone(),
32            }
33        }
34    }
35
36    /// Return a message to the pool
37    async fn return_message(&self, mut message: T) {
38        let mut pool = self.pool.lock().await;
39        
40        if pool.len() < self.max_size {
41            // Reset the message if it has a reset method
42            if let Some(resettable) = (&mut message as &mut dyn std::any::Any).downcast_mut::<OptimizedMessage>() {
43                resettable.reset();
44            }
45            
46            pool.push_back(message);
47        }
48        // If pool is full, just drop the message
49    }
50}
51
52impl<T: Send + Sync + 'static> Clone for MessagePool<T> {
53    fn clone(&self) -> Self {
54        Self {
55            pool: self.pool.clone(),
56            max_size: self.max_size,
57        }
58    }
59}
60
61/// Wrapper for pooled message that automatically returns to pool
62pub struct PooledMessage<T: Send + Sync + 'static> {
63    message: Option<T>,
64    pool: MessagePool<T>,
65}
66
67impl<T: Send + Sync + 'static> PooledMessage<T> {
68    pub fn get(&self) -> &T {
69        self.message.as_ref().unwrap()
70    }
71
72    pub fn get_mut(&mut self) -> &mut T {
73        self.message.as_mut().unwrap()
74    }
75}
76
77impl<T: Send + Sync + 'static> Drop for PooledMessage<T> {
78    fn drop(&mut self) {
79        if let Some(message) = self.message.take() {
80            let pool = self.pool.clone();
81            tokio::spawn(async move {
82                // Just drop the message for now - we'll implement proper pooling later
83                drop(message);
84            });
85        }
86    }
87}
88
89/// Trait for objects that can be reset for reuse
90pub trait Reset {
91    fn reset(&mut self);
92}
93
94/// Optimized message struct that can be pooled
95#[derive(Debug, Clone, Default)]
96pub struct OptimizedMessage {
97    pub id: String,
98    pub topic: String,
99    pub payload: Vec<u8>,
100    pub timestamp: u64,
101    pub partition: u32,
102    pub offset: i64,
103}
104
105impl OptimizedMessage {
106    pub fn new() -> Self {
107        Self {
108            id: String::with_capacity(36), // UUID length
109            topic: String::with_capacity(64),
110            payload: Vec::with_capacity(1024),
111            timestamp: 0,
112            partition: 0,
113            offset: 0,
114        }
115    }
116}
117
118impl Reset for OptimizedMessage {
119    fn reset(&mut self) {
120        self.id.clear();
121        self.topic.clear();
122        self.payload.clear();
123        self.timestamp = 0;
124        self.partition = 0;
125        self.offset = 0;
126    }
127}
128
129/// Factory function for creating message pools
130pub fn create_message_pool(max_size: usize) -> MessagePool<OptimizedMessage> {
131    MessagePool::new(max_size)
132}