Crates.io | derivable-object-pool |
lib.rs | derivable-object-pool |
version | 0.1.1 |
source | src |
created_at | 2023-07-13 14:38:00.547354 |
updated_at | 2023-07-13 15:19:24.32905 |
description | A thread-safe derivable object pool collection with automatic reusage of objects. |
homepage | https://github.com/ferranSanchezLlado/derivable-object-pool.git |
repository | https://github.com/ferranSanchezLlado/derivable-object-pool.git |
max_upload_size | |
id | 915426 |
size | 31,165 |
This crate provides a trait that can be derived to implement an object pool
for a type with a single line of code. Allowing the user to forget about
the implementation details of the ObjectPool
and focus on the important parts of their code
This crate has the following features compared to other object pool crates:
#[derive(ObjectPool)]
attribute macro.ObjectPool::new
function to create objects from the pool, which will reuse objects from the pool
if possible. This items are wrapped in a Reusable
struct, which will be returned to the pool when dropped.Mutex
)
and can be used in a multi-threaded environment.ObjectPool::new
function to create objects from the pool.#[derive(ObjectPool)]
)
or just use the Default
trait to create new objects.Add the following to your Cargo.toml
file:
[dependencies]
derivable-object-pool = "0.1.1"
Without specifying any attributes, the pool will use the Default
trait to create new objects:
use derivable_object_pool::prelude::*;
#[derive(Default, ObjectPool)]
struct Test(i32);
fn main() {
let mut obj = Test::new();
obj.0 += 1;
assert_eq!(obj.0, 1);
drop(obj); // obj is returned to the pool
assert_eq!(Test::pool().len(), 1);
let mut obj = Test::new();
assert_eq!(Test::pool().len(), 0);
assert_eq!(obj.0, 1);
}
Or you can specify a custom generator function using the #[generator]
attribute:
use derivable_object_pool::prelude::*;
#[derive(ObjectPool)]
#[generator(Test::new_item)]
struct Test(i32);
impl Test {
fn new_item() -> Self {
Test(10)
}
}
fn main() {
let mut obj = Test::new();
obj.0 += 1;
assert_eq!(obj.0, 11);
drop(obj); // obj is returned to the pool
assert_eq!(Test::pool().len(), 1);
let mut obj = Test::new();
assert_eq!(Test::pool().len(), 0);
assert_eq!(obj.0, 11);
}
The documentation can be found here.
This project is licensed under the dual MIT/Apache-2.0 license. For more information, see LICENSE-APACHE and LICENSE-MIT.