From 1dc427977174b3002abd5c1bd7618abb8204d53e Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Tue, 3 Mar 2026 16:37:16 +0100 Subject: [PATCH] Add support for collecting objects from a pool This is similar to [ThreadLocal](https://docs.rs/thread_local/latest/thread_local/struct.ThreadLocal.html#impl-IntoIterator-for-ThreadLocal%3CT%3E) and is useful, for example, when objects in the pool are writers that need to be flushed at the end. --- src/lib.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2579371..770bf78 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,10 +27,15 @@ //! # use std::io::Read; //! # let mut some_file = std::io::empty(); //! let pool: Pool> = Pool::new(32, || Vec::with_capacity(4096)); -//! let mut reusable_buff = pool.try_pull().unwrap(); // returns None when the pool is saturated -//! reusable_buff.clear(); // clear the buff before using -//! some_file.read_to_end(&mut reusable_buff).ok(); -//! // reusable_buff is automatically returned to the pool when it goes out of scope +//! +//! { +//! let mut reusable_buff = pool.try_pull().unwrap(); // returns None when the pool is saturated +//! reusable_buff.clear(); // clear the buff before using +//! some_file.read_to_end(&mut reusable_buff).ok(); +//! // reusable_buff is automatically returned to the pool when it goes out of scope +//! } +//! +//! assert_eq!(pool.into_iter().count(), 32); //! ``` //! Pull from pool and `detach()` //! ``` @@ -38,11 +43,16 @@ //! let pool: Pool> = Pool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.try_pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using -//! let (pool, reusable_buff) = reusable_buff.detach(); -//! let mut s = String::from_utf8(reusable_buff).unwrap(); -//! s.push_str("hello, world!"); -//! pool.attach(s.into_bytes()); // reattach the buffer before reusable goes out of scope -//! // reusable_buff is automatically returned to the pool when it goes out of scope +//! +//! { +//! let (pool, reusable_buff) = reusable_buff.detach(); +//! let mut s = String::from_utf8(reusable_buff).unwrap(); +//! s.push_str("hello, world!"); +//! pool.attach(s.into_bytes()); // reattach the buffer before reusable goes out of scope +//! // reusable_buff is automatically returned to the pool when it goes out of scope +//! } +//! +//! assert_eq!(pool.into_iter().count(), 32); //! ``` //! //! ## Using Across Threads @@ -172,6 +182,15 @@ impl FromIterator for Pool { } } +impl IntoIterator for Pool { + type Item = T; + type IntoIter = as IntoIterator>::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.objects.into_inner().into_iter() + } +} + pub struct Reusable<'a, T> { pool: &'a Pool, data: ManuallyDrop,