3 unstable releases

0.2.2 Mar 2, 2020
0.2.1 Mar 2, 2020
0.2.0 Mar 2, 2020
0.1.1 Feb 27, 2020
0.1.0 Feb 27, 2020

#1144 in Concurrency

Download history 19599/week @ 2024-07-21 19824/week @ 2024-07-28 25790/week @ 2024-08-04 28505/week @ 2024-08-11 28518/week @ 2024-08-18 39514/week @ 2024-08-25 26923/week @ 2024-09-01 32439/week @ 2024-09-08 31206/week @ 2024-09-15 35209/week @ 2024-09-22 36878/week @ 2024-09-29 22460/week @ 2024-10-06 37862/week @ 2024-10-13 34256/week @ 2024-10-20 21032/week @ 2024-10-27 20741/week @ 2024-11-03

113,909 downloads per month
Used in 2 crates

MIT license

14KB
315 lines

dynamic-pool

Build Status License Documentation Cargo

A lock-free, thread-safe, dynamically-sized object pool.

This pool begins with an initial capacity and will continue creating new objects on request when none are available. pooled objects are returned to the pool on destruction (with an extra provision to optionally "reset" the state of an object for re-use).

If, during an attempted return, a pool already has maximum_capacity objects in the pool, the pool will throw away that object.

Basic Usage

Add this to your Cargo.toml:

[dependencies]
dynamic-pool = "0.1"

Next, do some pooling:

use dynamic_pool::{DynamicPool, DynamicReset};

#[derive(Default)]
struct Person {
    name: String,
    age: u16,
}

impl DynamicReset for Person {
    fn reset(&mut self) {
        self.name.clear();
        self.age = 0;
    }
}

fn main() {
    // Creates a new pool that will hold at most 10 items, starting with 1 item by default.
    let pool = DynamicPool::new(1, 10, Person::default);
    // Assert we have one item in the pool.
    assert_eq!(pool.available(), 1);

    // Take an item from the pool.
    let mut person = pool.take();
    person.name = "jake".into();
    person.age = 99;

    // Assert the pool is empty since we took the person above.
    assert_eq!(pool.available(), 0);
    // Dropping returns the item to the pool.
    drop(person);
    // We now have stuff available in the pool to take.
    assert_eq!(pool.available(), 1);

    // Take person from the pool again, it should be reset.
    let person = pool.take();
    assert_eq!(person.name, "");
    assert_eq!(person.age, 0);

    // Nothing is in the queue.
    assert_eq!(pool.available(), 0);
    // try_take returns an Option. Since the pool is empty, nothing will be created.
    assert!(pool.try_take().is_none());
    // Dropping again returns the person to the pool.
    drop(person);
    // We have stuff in the pool now!
    assert_eq!(pool.available(), 1);

    // try_take would succeed here!
    let person = pool.try_take().unwrap();

    // We can also then detach the `person` from the pool, meaning it won't get
    // recycled.
    let person = person.detach();
    // We can then drop that person, and see that it's not returned to the pool.
    drop(person);
    assert_eq!(pool.available(), 0);
}

License

Licensed under the MIT license.

Dependencies

~215KB