Trait ObjectPool

Source
pub trait ObjectPool: Sized {
    // Required method
    fn pool<'a>() -> &'a Pool<Self>;

    // Provided method
    fn new() -> Reusable<Self> { ... }
}
Expand description

Allows for the creation of objects that can be reused. This is useful for objects that are expensive to create, but are used frequently. This trait can be derived using the #[derive(ObjectPool)] attribute macro (for more information, see the documentation for the ObjectPool trait)

The new objects will be created using a generator function, which can be specified using the #[generator(function_name)] attribute macro on the struct. If no generator is specified, the trait will use the Default trait to create new objects.

§Example

Example without a generator:

use derivable_object_pool::prelude::*;

#[derive(Default, ObjectPool)]
struct Test {
    a: i32,
    b: f64,
}

fn main() {
    let obj = Test::new();
    drop(obj); // obj is returned to the pool
    let obj2 = Test::new(); // obj2 is the same object as obj
}

Example with a generator:


use derivable_object_pool::prelude::*;

#[derive(ObjectPool)]
#[generator(Test::new_item)]
struct Test {
    a: i32,
    b: f64,
}

impl Test {
    fn new_item() -> Self {
        Self {
            a: 1,
            b: 1.0,
        }
    }
}

fn main() {
    let obj = Test::new();
    drop(obj); // obj is returned to the pool
    let obj2 = Test::new(); // obj2 is the same object as obj
}

Required Methods§

Source

fn pool<'a>() -> &'a Pool<Self>

Returns a reference to the pool for this type of object. This allows you to interact with the pool directly, if you need to.

§Example
use derivable_object_pool::prelude::*;

#[derive(Default, ObjectPool)]
struct Test;

fn main() {
    let pool = Test::pool();
    assert_eq!(pool.len(), 0);
    let obj = Test::new();
    drop(obj);
    assert_eq!(pool.len(), 1);
    pool.clear();
    assert_eq!(pool.len(), 0);
}

Provided Methods§

Source

fn new() -> Reusable<Self>

Creates a new object. If there are any objects in the pool, one of them will be returned. Otherwise, a new object will be created using the generator function.

§Example
use derivable_object_pool::prelude::*;

#[derive(Default, ObjectPool)]
struct Test(i32);

fn main() {
    let mut obj = Test::new();
    assert_eq!(obj.0, 0);
    obj.0 = 1;
    drop(obj);
    let obj = Test::new();
    assert_eq!(obj.0, 1);
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§