clicktype-batch 0.2.0

Async batching system for ClickType with backpressure and metrics
Documentation
//! Reusable buffer for batch serialization

use std::io::{self, Write};

/// Reusable batch buffer
pub struct BatchBuffer {
    inner: Vec<u8>,
}

impl BatchBuffer {
    /// Create a new buffer with specified capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            inner: Vec::with_capacity(capacity),
        }
    }

    /// Get the current buffer length
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Get current capacity
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Check if buffer is empty
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get buffer contents as slice
    pub fn as_slice(&self) -> &[u8] {
        &self.inner
    }

    /// Clear the buffer.
    ///
    /// If capacity exceeds `shrink_threshold`, the internal buffer is dropped
    /// and a new one is allocated with `initial_capacity`.
    /// Otherwise, it just clears the vector (keeping capacity).
    pub fn smart_clear(&mut self, shrink_threshold: usize, initial_capacity: usize) {
        if self.inner.capacity() > shrink_threshold {
            // Drop the large buffer and allocate a new smaller one
            self.inner = Vec::with_capacity(initial_capacity);
        } else {
            // Keep capacity, just reset length
            self.inner.clear();
        }
    }

    /// Clear the buffer (retains capacity)
    pub fn clear(&mut self) {
        self.inner.clear();
    }
}

impl Write for BatchBuffer {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}