├── .gitignore ├── .travis.yml ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── ci ├── rustfmt.sh └── tests.sh ├── examples └── simple.rs └── src ├── lib.rs ├── pool.rs └── reset.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | cache: cargo 4 | 5 | branches: 6 | only: 7 | - master 8 | - staging 9 | - trying 10 | 11 | matrix: 12 | fast_finish: true 13 | include: 14 | # Run tests + checks against stable 15 | - rust: stable 16 | name: "dynamic-pool on stable" 17 | script: ./ci/tests.sh 18 | 19 | # Check formatting. 20 | - rust: stable 21 | name: "rustfmt" 22 | script: ./ci/rustfmt.sh 23 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "autocfg" 5 | version = "1.0.0" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "cfg-if" 10 | version = "0.1.10" 11 | source = "registry+https://github.com/rust-lang/crates.io-index" 12 | 13 | [[package]] 14 | name = "crossbeam-queue" 15 | version = "0.2.1" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | dependencies = [ 18 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 19 | "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", 20 | ] 21 | 22 | [[package]] 23 | name = "crossbeam-utils" 24 | version = "0.7.2" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | dependencies = [ 27 | "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", 28 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 29 | "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 30 | ] 31 | 32 | [[package]] 33 | name = "dynamic-pool" 34 | version = "0.2.2" 35 | dependencies = [ 36 | "crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 37 | ] 38 | 39 | [[package]] 40 | name = "lazy_static" 41 | version = "1.4.0" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | 44 | [metadata] 45 | "checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" 46 | "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 47 | "checksum crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" 48 | "checksum crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" 49 | "checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 50 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dynamic-pool" 3 | version = "0.2.2" 4 | authors = ["jake "] 5 | edition = "2018" 6 | license = "MIT" 7 | readme = "README.md" 8 | description = "a lock-free, thread-safe, dynamically-sized object pool." 9 | repository = "https://github.com/discordapp/dynamic-pool" 10 | homepage = "https://github.com/discordapp/dynamic-pool" 11 | documentation = "https://docs.rs/dynamic-pool" 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [dependencies] 16 | crossbeam-queue = "0.2" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Discord, Inc. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `dynamic-pool` 2 | 3 | [![Build Status](https://travis-ci.org/discordapp/dynamic-pool.svg?branch=master)](https://travis-ci.org/discordapp/dynamic-pool) 4 | [![License](https://img.shields.io/github/license/discordapp/dynamic-pool.svg)](LICENSE) 5 | [![Documentation](https://docs.rs/dynamic-pool/badge.svg)](https://docs.rs/dynamic-pool) 6 | [![Cargo](https://img.shields.io/crates/v/dynamic-pool.svg)](https://crates.io/crates/dynamic-pool) 7 | 8 | A lock-free, thread-safe, dynamically-sized object pool. 9 | 10 | This pool begins with an initial capacity and will continue creating new objects on request when none are available. 11 | pooled objects are returned to the pool on destruction (with an extra provision to optionally "reset" the state of 12 | an object for re-use). 13 | 14 | If, during an attempted return, a pool already has `maximum_capacity` objects in the pool, the pool will throw away 15 | that object. 16 | 17 | ## Basic Usage 18 | 19 | Add this to your `Cargo.toml`: 20 | 21 | ```toml 22 | [dependencies] 23 | dynamic-pool = "0.1" 24 | ``` 25 | 26 | Next, do some pooling: 27 | 28 | ```rust 29 | use dynamic_pool::{DynamicPool, DynamicReset}; 30 | 31 | #[derive(Default)] 32 | struct Person { 33 | name: String, 34 | age: u16, 35 | } 36 | 37 | impl DynamicReset for Person { 38 | fn reset(&mut self) { 39 | self.name.clear(); 40 | self.age = 0; 41 | } 42 | } 43 | 44 | fn main() { 45 | // Creates a new pool that will hold at most 10 items, starting with 1 item by default. 46 | let pool = DynamicPool::new(1, 10, Person::default); 47 | // Assert we have one item in the pool. 48 | assert_eq!(pool.available(), 1); 49 | 50 | // Take an item from the pool. 51 | let mut person = pool.take(); 52 | person.name = "jake".into(); 53 | person.age = 99; 54 | 55 | // Assert the pool is empty since we took the person above. 56 | assert_eq!(pool.available(), 0); 57 | // Dropping returns the item to the pool. 58 | drop(person); 59 | // We now have stuff available in the pool to take. 60 | assert_eq!(pool.available(), 1); 61 | 62 | // Take person from the pool again, it should be reset. 63 | let person = pool.take(); 64 | assert_eq!(person.name, ""); 65 | assert_eq!(person.age, 0); 66 | 67 | // Nothing is in the queue. 68 | assert_eq!(pool.available(), 0); 69 | // try_take returns an Option. Since the pool is empty, nothing will be created. 70 | assert!(pool.try_take().is_none()); 71 | // Dropping again returns the person to the pool. 72 | drop(person); 73 | // We have stuff in the pool now! 74 | assert_eq!(pool.available(), 1); 75 | 76 | // try_take would succeed here! 77 | let person = pool.try_take().unwrap(); 78 | 79 | // We can also then detach the `person` from the pool, meaning it won't get 80 | // recycled. 81 | let person = person.detach(); 82 | // We can then drop that person, and see that it's not returned to the pool. 83 | drop(person); 84 | assert_eq!(pool.available(), 0); 85 | } 86 | ``` 87 | 88 | ## License 89 | 90 | Licensed under the [MIT license](LICENSE). 91 | -------------------------------------------------------------------------------- /ci/rustfmt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd "$(dirname "$0")"/.. 4 | set -ex 5 | 6 | rustup component add rustfmt 7 | 8 | cargo fmt --all -- --check -------------------------------------------------------------------------------- /ci/tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd "$(dirname "$0")"/.. 4 | set -ex 5 | 6 | export RUSTFLAGS="-D warnings" 7 | 8 | cargo check --no-default-features 9 | cargo check --bins --examples --tests 10 | cargo test --all-features -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | use dynamic_pool::{DynamicPool, DynamicReset}; 2 | 3 | #[derive(Default)] 4 | struct Person { 5 | name: String, 6 | age: u16, 7 | } 8 | 9 | impl DynamicReset for Person { 10 | fn reset(&mut self) { 11 | self.name.clear(); 12 | self.age = 0; 13 | } 14 | } 15 | 16 | fn main() { 17 | // Creates a new pool that will hold at most 10 items, starting with 1 item by default. 18 | let pool = DynamicPool::new(1, 10, Person::default); 19 | // Assert we have one item in the pool. 20 | assert_eq!(pool.available(), 1); 21 | 22 | // Take an item from the pool. 23 | let mut person = pool.take(); 24 | person.name = "jake".into(); 25 | person.age = 99; 26 | 27 | // Assert the pool is empty since we took the person above. 28 | assert_eq!(pool.available(), 0); 29 | // Dropping returns the item to the pool. 30 | drop(person); 31 | // We now have stuff available in the pool to take. 32 | assert_eq!(pool.available(), 1); 33 | 34 | // Take person from the pool again, it should be reset. 35 | let person = pool.take(); 36 | assert_eq!(person.name, ""); 37 | assert_eq!(person.age, 0); 38 | 39 | // Nothing is in the queue. 40 | assert_eq!(pool.available(), 0); 41 | // try_take returns an Option. Since the pool is empty, nothing will be created. 42 | assert!(pool.try_take().is_none()); 43 | // Dropping again returns the person to the pool. 44 | drop(person); 45 | // We have stuff in the pool now! 46 | assert_eq!(pool.available(), 1); 47 | 48 | // try_take would succeed here! 49 | let person = pool.try_take().unwrap(); 50 | 51 | // We can also then detach the `person` from the pool, meaning it won't get 52 | // recycled. 53 | let person = person.detach(); 54 | // We can then drop that person, and see that it's not returned to the pool. 55 | drop(person); 56 | assert_eq!(pool.available(), 0); 57 | } 58 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod pool; 2 | mod reset; 3 | 4 | pub use self::pool::{DynamicPool, DynamicPoolItem}; 5 | pub use self::reset::DynamicReset; 6 | -------------------------------------------------------------------------------- /src/pool.rs: -------------------------------------------------------------------------------- 1 | use crossbeam_queue::ArrayQueue; 2 | use std::fmt::{Debug, Formatter}; 3 | use std::ops::{Deref, DerefMut}; 4 | use std::sync::{Arc, Weak}; 5 | 6 | use crate::DynamicReset; 7 | 8 | /// a lock-free, thread-safe, dynamically-sized object pool. 9 | /// 10 | /// this pool begins with an initial capacity and will continue creating new objects on request when none are available. 11 | /// pooled objects are returned to the pool on destruction (with an extra provision to optionally "reset" the state of 12 | /// an object for re-use). 13 | /// 14 | /// if, during an attempted return, a pool already has `maximum_capacity` objects in the pool, the pool will throw away 15 | /// that object. 16 | #[derive(Debug)] 17 | pub struct DynamicPool { 18 | data: Arc>, 19 | } 20 | 21 | impl DynamicPool { 22 | /// creates a new `DynamicPool`. this pool will create `initial_capacity` objects, and retain up to 23 | /// `maximum_capacity` objects. 24 | /// 25 | /// # panics. 26 | /// 27 | /// panics if `initial_capacity > maximum_capacity`. 28 | pub fn new T + Sync + Send + 'static>( 29 | initial_capacity: usize, 30 | maximum_capacity: usize, 31 | create: F, 32 | ) -> DynamicPool { 33 | assert![initial_capacity <= maximum_capacity]; 34 | 35 | let items = ArrayQueue::new(maximum_capacity); 36 | 37 | for x in (0..initial_capacity).map(|_| create()) { 38 | items 39 | .push(x) 40 | .expect("invariant: items.len() always less than initial_capacity."); 41 | } 42 | 43 | let data = PoolData { 44 | items, 45 | create: Box::new(create), 46 | }; 47 | let data = Arc::new(data); 48 | 49 | DynamicPool { data } 50 | } 51 | 52 | /// takes an item from the pool, creating one if none are available. 53 | pub fn take(&self) -> DynamicPoolItem { 54 | let object = self 55 | .data 56 | .items 57 | .pop() 58 | .unwrap_or_else(|_| (self.data.create)()); 59 | 60 | DynamicPoolItem { 61 | data: Arc::downgrade(&self.data), 62 | object: Some(object), 63 | } 64 | } 65 | 66 | /// attempts to take an item from the pool, returning `none` if none is available. will never allocate. 67 | pub fn try_take(&self) -> Option> { 68 | let object = self.data.items.pop().ok()?; 69 | let data = Arc::downgrade(&self.data); 70 | 71 | Some(DynamicPoolItem { 72 | data, 73 | object: Some(object), 74 | }) 75 | } 76 | 77 | /// returns the number of free objects in the pool. 78 | #[inline] 79 | pub fn available(&self) -> usize { 80 | self.data.items.len() 81 | } 82 | 83 | /// returns the number of objects currently in use. does not include objects that have been detached. 84 | #[inline] 85 | pub fn used(&self) -> usize { 86 | Arc::weak_count(&self.data) 87 | } 88 | 89 | #[inline] 90 | pub fn capacity(&self) -> usize { 91 | self.data.items.capacity() 92 | } 93 | } 94 | 95 | impl Clone for DynamicPool { 96 | fn clone(&self) -> Self { 97 | Self { 98 | data: self.data.clone(), 99 | } 100 | } 101 | } 102 | 103 | // data shared by a `DynamicPool`. 104 | struct PoolData { 105 | items: ArrayQueue, 106 | create: Box T + Sync + Send + 'static>, 107 | } 108 | 109 | impl Debug for PoolData { 110 | fn fmt(&self, formatter: &mut Formatter) -> Result<(), std::fmt::Error> { 111 | formatter 112 | .debug_struct("PoolData") 113 | .field("items", &self.items) 114 | .field("create", &"Box T>") 115 | .finish() 116 | } 117 | } 118 | 119 | /// an object, checked out from a dynamic pool object. 120 | #[derive(Debug)] 121 | pub struct DynamicPoolItem { 122 | data: Weak>, 123 | object: Option, 124 | } 125 | 126 | impl DynamicPoolItem { 127 | /// detaches this instance from the pool, returns T. 128 | pub fn detach(mut self) -> T { 129 | self.object 130 | .take() 131 | .expect("invariant: object is always `some`.") 132 | } 133 | } 134 | 135 | impl AsRef for DynamicPoolItem { 136 | fn as_ref(&self) -> &T { 137 | self.object 138 | .as_ref() 139 | .expect("invariant: object is always `some`.") 140 | } 141 | } 142 | 143 | impl Deref for DynamicPoolItem { 144 | type Target = T; 145 | 146 | fn deref(&self) -> &T { 147 | self.object 148 | .as_ref() 149 | .expect("invariant: object is always `some`.") 150 | } 151 | } 152 | 153 | impl DerefMut for DynamicPoolItem { 154 | fn deref_mut(&mut self) -> &mut T { 155 | self.object 156 | .as_mut() 157 | .expect("invariant: object is always `some`.") 158 | } 159 | } 160 | 161 | impl Drop for DynamicPoolItem { 162 | fn drop(&mut self) { 163 | if let Some(mut object) = self.object.take() { 164 | object.reset(); 165 | if let Some(pool) = self.data.upgrade() { 166 | pool.items.push(object).ok(); 167 | } 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/reset.rs: -------------------------------------------------------------------------------- 1 | pub trait DynamicReset { 2 | fn reset(&mut self); 3 | } 4 | 5 | impl DynamicReset for Option 6 | where 7 | T: DynamicReset, 8 | { 9 | fn reset(&mut self) { 10 | if let Some(x) = self { 11 | x.reset(); 12 | } 13 | } 14 | } 15 | 16 | impl DynamicReset for (T1, T2) 17 | where 18 | T1: DynamicReset, 19 | T2: DynamicReset, 20 | { 21 | fn reset(&mut self) { 22 | self.0.reset(); 23 | self.1.reset(); 24 | } 25 | } 26 | 27 | impl DynamicReset for (T1, T2, T3) 28 | where 29 | T1: DynamicReset, 30 | T2: DynamicReset, 31 | T3: DynamicReset, 32 | { 33 | fn reset(&mut self) { 34 | self.0.reset(); 35 | self.1.reset(); 36 | self.2.reset(); 37 | } 38 | } 39 | 40 | impl DynamicReset for (T1, T2, T3, T4) 41 | where 42 | T1: DynamicReset, 43 | T2: DynamicReset, 44 | T3: DynamicReset, 45 | T4: DynamicReset, 46 | { 47 | fn reset(&mut self) { 48 | self.0.reset(); 49 | self.1.reset(); 50 | self.2.reset(); 51 | self.3.reset(); 52 | } 53 | } 54 | 55 | impl DynamicReset for (T1, T2, T3, T4, T5) 56 | where 57 | T1: DynamicReset, 58 | T2: DynamicReset, 59 | T3: DynamicReset, 60 | T4: DynamicReset, 61 | T5: DynamicReset, 62 | { 63 | fn reset(&mut self) { 64 | self.0.reset(); 65 | self.1.reset(); 66 | self.2.reset(); 67 | self.3.reset(); 68 | self.4.reset(); 69 | } 70 | } 71 | 72 | impl DynamicReset for (T1, T2, T3, T4, T5, T6) 73 | where 74 | T1: DynamicReset, 75 | T2: DynamicReset, 76 | T3: DynamicReset, 77 | T4: DynamicReset, 78 | T5: DynamicReset, 79 | T6: DynamicReset, 80 | { 81 | fn reset(&mut self) { 82 | self.0.reset(); 83 | self.1.reset(); 84 | self.2.reset(); 85 | self.3.reset(); 86 | self.4.reset(); 87 | self.5.reset(); 88 | } 89 | } 90 | 91 | impl DynamicReset for (T1, T2, T3, T4, T5, T6, T7) 92 | where 93 | T1: DynamicReset, 94 | T2: DynamicReset, 95 | T3: DynamicReset, 96 | T4: DynamicReset, 97 | T5: DynamicReset, 98 | T6: DynamicReset, 99 | T7: DynamicReset, 100 | { 101 | fn reset(&mut self) { 102 | self.0.reset(); 103 | self.1.reset(); 104 | self.2.reset(); 105 | self.3.reset(); 106 | self.4.reset(); 107 | self.5.reset(); 108 | self.6.reset(); 109 | } 110 | } 111 | 112 | impl DynamicReset for (T1, T2, T3, T4, T5, T6, T7, T8) 113 | where 114 | T1: DynamicReset, 115 | T2: DynamicReset, 116 | T3: DynamicReset, 117 | T4: DynamicReset, 118 | T5: DynamicReset, 119 | T6: DynamicReset, 120 | T7: DynamicReset, 121 | T8: DynamicReset, 122 | { 123 | fn reset(&mut self) { 124 | self.0.reset(); 125 | self.1.reset(); 126 | self.2.reset(); 127 | self.3.reset(); 128 | self.4.reset(); 129 | self.5.reset(); 130 | self.6.reset(); 131 | self.7.reset(); 132 | } 133 | } 134 | 135 | impl DynamicReset for (T1, T2, T3, T4, T5, T6, T7, T8, T9) 136 | where 137 | T1: DynamicReset, 138 | T2: DynamicReset, 139 | T3: DynamicReset, 140 | T4: DynamicReset, 141 | T5: DynamicReset, 142 | T6: DynamicReset, 143 | T7: DynamicReset, 144 | T8: DynamicReset, 145 | T9: DynamicReset, 146 | { 147 | fn reset(&mut self) { 148 | self.0.reset(); 149 | self.1.reset(); 150 | self.2.reset(); 151 | self.3.reset(); 152 | self.4.reset(); 153 | self.5.reset(); 154 | self.6.reset(); 155 | self.7.reset(); 156 | self.8.reset(); 157 | } 158 | } 159 | 160 | impl DynamicReset 161 | for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) 162 | where 163 | T1: DynamicReset, 164 | T2: DynamicReset, 165 | T3: DynamicReset, 166 | T4: DynamicReset, 167 | T5: DynamicReset, 168 | T6: DynamicReset, 169 | T7: DynamicReset, 170 | T8: DynamicReset, 171 | T9: DynamicReset, 172 | T10: DynamicReset, 173 | { 174 | fn reset(&mut self) { 175 | self.0.reset(); 176 | self.1.reset(); 177 | self.2.reset(); 178 | self.3.reset(); 179 | self.4.reset(); 180 | self.5.reset(); 181 | self.6.reset(); 182 | self.7.reset(); 183 | self.8.reset(); 184 | self.9.reset(); 185 | } 186 | } 187 | --------------------------------------------------------------------------------