[−][src]Crate object_pool
A thread-safe object pool with automatic return and attach/detach semantics
The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects
Common use case is when using buffer to read IO.
You would create a Pool of size n, containing Vecfile.read_to_end(buff)
Warning
Objects in the pool are not automatically reset, they are returned but NOT reset
You may want to call object.reset()
or object.clear()
or any other equivalent for the object you are using after pulling from the pool
Examples
Creating a Pool
The general pool creation looks like this
let pool: Pool<T> = Pool::new(capacity, || T::new());
Creating a pool with 32 Vec<u8>
with capacity of 4096
let pool: Pool<Vec<u8>> = Pool::new(32, || Vec::with_capacity(4096);
Using a Pool
Basic usage for pulling from the pool
let pool: Pool<Vec<u8>> = Pool::new(32, || Vec::with_capacity(4096); let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated reusable_buff.clear(); //clear the buff before using some_file.read_to_end(reusable_buff.deref_mut()); //reusable_buff is automatically returned to the pool when it goes out of scope
Pull from poll and detach()
let pool: Pool<Vec<u8>> = Pool::new(32, || Vec::with_capacity(4096); let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated reusable_buff.clear(); //clear the buff before using let s = String::from(reusable_buff.detach()); s.push_str("hello, world!"); reusable_buff.attach(s.into_bytes()); //need to reattach the buffer before reusable goes out of scope //reusable_buff is automatically returned to the pool when it goes out of scope
Structs
Pool | |
Reusable |