Skip to main content

clicktype_batch/
buffer.rs

1//! Reusable buffer for batch serialization
2
3use std::io::{self, Write};
4
5/// Reusable batch buffer
6pub struct BatchBuffer {
7    inner: Vec<u8>,
8}
9
10impl BatchBuffer {
11    /// Create a new buffer with specified capacity
12    pub fn new(capacity: usize) -> Self {
13        Self {
14            inner: Vec::with_capacity(capacity),
15        }
16    }
17
18    /// Get the current buffer length
19    pub fn len(&self) -> usize {
20        self.inner.len()
21    }
22
23    /// Get current capacity
24    pub fn capacity(&self) -> usize {
25        self.inner.capacity()
26    }
27
28    /// Check if buffer is empty
29    pub fn is_empty(&self) -> bool {
30        self.inner.is_empty()
31    }
32
33    /// Get buffer contents as slice
34    pub fn as_slice(&self) -> &[u8] {
35        &self.inner
36    }
37
38    /// Clear the buffer.
39    ///
40    /// If capacity exceeds `shrink_threshold`, the internal buffer is dropped
41    /// and a new one is allocated with `initial_capacity`.
42    /// Otherwise, it just clears the vector (keeping capacity).
43    pub fn smart_clear(&mut self, shrink_threshold: usize, initial_capacity: usize) {
44        if self.inner.capacity() > shrink_threshold {
45            // Drop the large buffer and allocate a new smaller one
46            self.inner = Vec::with_capacity(initial_capacity);
47        } else {
48            // Keep capacity, just reset length
49            self.inner.clear();
50        }
51    }
52
53    /// Clear the buffer (retains capacity)
54    pub fn clear(&mut self) {
55        self.inner.clear();
56    }
57}
58
59impl Write for BatchBuffer {
60    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
61        self.inner.extend_from_slice(buf);
62        Ok(buf.len())
63    }
64
65    fn flush(&mut self) -> io::Result<()> {
66        Ok(())
67    }
68}