A pre-allocated buffer pool for Rust.
bytes-pool provides a fixed-size pool of pre-allocated buffers. Buffers are
allocated from the pool and automatically returned when dropped. This is useful
for high-performance applications where allocation overhead matters.
- Thread-safe pool access
- Zero-allocation buffer recycling
- Implements
BufMutfor ergonomic writes - Automatic buffer return on drop
Add this to your Cargo.toml:
[dependencies]
bytes-pool = "0.1"use bytes::BufMut;
use bytes_pool::Pool;
// Create a pool with 10 buffers of 1024 bytes each
let pool = Pool::new(1024, 10);
// Allocate a buffer
let mut buf = pool.alloc().unwrap();
// Write data using BufMut
buf.put_slice(b"hello world");
// Access the data
assert_eq!(&buf[..], b"hello world");
// Buffer is automatically returned to the pool when dropped
drop(buf);
assert_eq!(pool.available(), 10);When all buffers are in use, alloc() returns an error:
use bytes_pool::Pool;
let pool = Pool::new(1024, 1);
let buf1 = pool.alloc().unwrap();
let result = pool.alloc(); // Returns Err(AllocError)
assert!(result.is_err());- Buffer size must be a power of 2
- Buffer count must be greater than 0
This project is licensed under the MIT License - see the LICENSE file for details.