Crate indexed_pool

Source
Expand description

A thread-safe indexed 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. This pool implementation allows to index different object pools of the same type as subpools. For example you could use this to pool SSH connection objects, indexed by ipaddress:port.

This pool is bound to sizes to avoid to keep allocations in control. There are 2 different sizes that can be setup at creation time, max_pool_indexes and max_single_pool_size, the former controlling how many indexes the pool can contain and the latter controlling the max size of the subpool of a single index.

On top of that indexes have an expiration time expressed as a duration.

§Examples

§Creating a Pool

The default pool creation looks like this, with 32 indexes with a capacity of 8 elements expiring after 5 minutes from creation :

use indexed_pool::Pool;

let pool: Pool<String> = Pool::default();

Example pool with 64 Vec<u8> with capacity of 64 elements each expiring after 10 seconds:

use std::time::Duration;
use indexed_pool::Pool;

let pool: Pool<u8> = Pool::new(64, 64, Duration::from_secs(10));

§Using a Pool

Basic usage for pulling from the pool

use indexed_pool::Pool;

struct Obj {
    size: usize,
}

let pool: Pool<Obj> = Pool::default();
let obj = pool.pull("item1", || Obj{size: 1});
assert_eq!(obj.size, 1);
let obj2 = pool.pull("item1", || Obj{size: 1});
assert_eq!(obj.size, 1);

Pull from pool and detach()

use indexed_pool::Pool;

struct Obj {
    size: usize,
}

let pool: Pool<Obj> = Pool::default();
let obj = pool.pull("item1", || Obj{size: 1});
assert_eq!(obj.size, 1);
let obj2 = pool.pull("item1", || Obj{size: 1});
assert_eq!(obj.size, 1);
let (pool, obj) = obj.detach();
assert_eq!(obj.size, 1);
pool.attach("item1", obj);

§Using Across Threads

You simply wrap the pool in a std::sync::Arc

use std::sync::Arc;
use indexed_pool::Pool;

let pool: Arc<Pool<String>> = Arc::new(Pool::default());

§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 that you are using, after pulling from the pool

Structs§