Get a buffer from the pool or allocate a new one
(&self)
| 156 | |
| 157 | /// Get a buffer from the pool or allocate a new one |
| 158 | pub fn get_buffer(&self) -> PooledBytesMut { |
| 159 | let mut inner = self.inner.lock(); |
| 160 | |
| 161 | // Try to reuse a buffer from the pool |
| 162 | if let Some(mut pooled_buffer) = inner.buffers.pop_front() { |
| 163 | pooled_buffer.reset(); |
| 164 | |
| 165 | inner.stats.buffers_reused += 1; |
| 166 | inner.stats.total_bytes_reused += pooled_buffer.buffer.capacity() as u64; |
| 167 | |
| 168 | if self.config.enable_monitoring { |
| 169 | debug!("Reused buffer from pool: capacity={}B, pool_size={}", |
| 170 | pooled_buffer.buffer.capacity(), inner.buffers.len()); |
| 171 | } |
| 172 | |
| 173 | PooledBytesMut::new(pooled_buffer.buffer, Arc::clone(&self.inner), self.config.clone()) |
| 174 | } else { |
| 175 | // Allocate a new buffer |
| 176 | let buffer = BytesMut::with_capacity(self.config.initial_buffer_capacity); |
| 177 | |
| 178 | inner.stats.buffers_allocated += 1; |
| 179 | inner.stats.total_bytes_allocated += buffer.capacity() as u64; |
| 180 | |
| 181 | // Record allocation in global memory monitor (skip in tests) |
| 182 | #[cfg(not(test))] |
| 183 | global_memory_monitor().record_buffer_allocation(buffer.capacity() as u64); |
| 184 | |
| 185 | if self.config.enable_monitoring { |
| 186 | debug!("Allocated new buffer: capacity={}B", buffer.capacity()); |
| 187 | } |
| 188 | |
| 189 | PooledBytesMut::new(buffer, Arc::clone(&self.inner), self.config.clone()) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// Return a buffer to the pool for reuse |
| 194 | fn return_buffer(&self, buffer: BytesMut) { |