Skip to main content

regex_automata/util/
pool.rs

1// This module provides a relatively simple thread-safe pool of reusable
2// objects. For the most part, it's implemented by a stack represented by a
3// Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat
4// costly, in the case where a pool is accessed by the first thread that tried
5// to get a value, we bypass the mutex. Here are some benchmarks showing the
6// difference.
7//
8// 2022-10-15: These benchmarks are from the old regex crate and they aren't
9// easy to reproduce because some rely on older implementations of Pool that
10// are no longer around. I've left the results here for posterity, but any
11// enterprising individual should feel encouraged to re-litigate the way Pool
12// works. I am not at all certain it is the best approach.
13//
14// 1) misc::anchored_literal_long_non_match    21 (18571 MB/s)
15// 2) misc::anchored_literal_long_non_match   107 (3644 MB/s)
16// 3) misc::anchored_literal_long_non_match    45 (8666 MB/s)
17// 4) misc::anchored_literal_long_non_match    19 (20526 MB/s)
18//
19// (1) represents our baseline: the master branch at the time of writing when
20// using the 'thread_local' crate to implement the pool below.
21//
22// (2) represents a naive pool implemented completely via Mutex<Vec<T>>. There
23// is no special trick for bypassing the mutex.
24//
25// (3) is the same as (2), except it uses Mutex<Vec<Box<T>>>. It is twice as
26// fast because a Box<T> is much smaller than the T we use with a Pool in this
27// crate. So pushing and popping a Box<T> from a Vec is quite a bit faster
28// than for T.
29//
30// (4) is the same as (3), but with the trick for bypassing the mutex in the
31// case of the first-to-get thread.
32//
33// Why move off of thread_local? Even though (4) is a hair faster than (1)
34// above, this was not the main goal. The main goal was to move off of
35// thread_local and find a way to *simply* re-capture some of its speed for
36// regex's specific case. So again, why move off of it? The *primary* reason is
37// because of memory leaks. See https://github.com/rust-lang/regex/issues/362
38// for example. (Why do I want it to be simple? Well, I suppose what I mean is,
39// "use as much safe code as possible to minimize risk and be as sure as I can
40// be that it is correct.")
41//
42// My guess is that the thread_local design is probably not appropriate for
43// regex since its memory usage scales to the number of active threads that
44// have used a regex, where as the pool below scales to the number of threads
45// that simultaneously use a regex. While neither case permits contraction,
46// since we own the pool data structure below, we can add contraction if a
47// clear use case pops up in the wild. More pressingly though, it seems that
48// there are at least some use case patterns where one might have many threads
49// sitting around that might have used a regex at one point. While thread_local
50// does try to reuse space previously used by a thread that has since stopped,
51// its maximal memory usage still scales with the total number of active
52// threads. In contrast, the pool below scales with the total number of threads
53// *simultaneously* using the pool. The hope is that this uses less memory
54// overall. And if it doesn't, we can hopefully tune it somehow.
55//
56// It seems that these sort of conditions happen frequently
57// in FFI inside of other more "managed" languages. This was
58// mentioned in the issue linked above, and also mentioned here:
59// https://github.com/BurntSushi/rure-go/issues/3. And in particular, users
60// confirm that disabling the use of thread_local resolves the leak.
61//
62// There were other weaker reasons for moving off of thread_local as well.
63// Namely, at the time, I was looking to reduce dependencies. And for something
64// like regex, maintenance can be simpler when we own the full dependency tree.
65//
66// Note that I am not entirely happy with this pool. It has some subtle
67// implementation details and is overall still observable (even with the
68// thread owner optimization) in benchmarks. If someone wants to take a crack
69// at building something better, please file an issue. Even if it means a
70// different API. The API exposed by this pool is not the minimal thing that
71// something like a 'Regex' actually needs. It could adapt to, for example,
72// an API more like what is found in the 'thread_local' crate. However, we do
73// really need to support the no-std alloc-only context, or else the regex
74// crate wouldn't be able to support no-std alloc-only. However, I'm generally
75// okay with making the alloc-only context slower (as it is here), although I
76// do find it unfortunate.
77
78/*!
79A thread safe memory pool.
80
81The principal type in this module is a [`Pool`]. It main use case is for
82holding a thread safe collection of mutable scratch spaces (usually called
83`Cache` in this crate) that regex engines need to execute a search. This then
84permits sharing the same read-only regex object across multiple threads while
85having a quick way of reusing scratch space in a thread safe way. This avoids
86needing to re-create the scratch space for every search, which could wind up
87being quite expensive.
88*/
89
90/// A thread safe pool that works in an `alloc`-only context.
91///
92/// Getting a value out comes with a guard. When that guard is dropped, the
93/// value is automatically put back in the pool. The guard provides both a
94/// `Deref` and a `DerefMut` implementation for easy access to an underlying
95/// `T`.
96///
97/// A `Pool` impls `Sync` when `T` is `Send` (even if `T` is not `Sync`). This
98/// is possible because a pool is guaranteed to provide a value to exactly one
99/// thread at any time.
100///
101/// Currently, a pool never contracts in size. Its size is proportional to the
102/// maximum number of simultaneous uses. This may change in the future.
103///
104/// A `Pool` is a particularly useful data structure for this crate because
105/// many of the regex engines require a mutable "cache" in order to execute
106/// a search. Since regexes themselves tend to be global, the problem is then:
107/// how do you get a mutable cache to execute a search? You could:
108///
109/// 1. Use a `thread_local!`, which requires the standard library and requires
110/// that the regex pattern be statically known.
111/// 2. Use a `Pool`.
112/// 3. Make the cache an explicit dependency in your code and pass it around.
113/// 4. Put the cache state in a `Mutex`, but this means only one search can
114/// execute at a time.
115/// 5. Create a new cache for every search.
116///
117/// A `thread_local!` is perhaps the best choice if it works for your use case.
118/// Putting the cache in a mutex or creating a new cache for every search are
119/// perhaps the worst choices. Of the remaining two choices, whether you use
120/// this `Pool` or thread through a cache explicitly in your code is a matter
121/// of taste and depends on your code architecture.
122///
123/// # Warning: may use a spin lock
124///
125/// When this crate is compiled _without_ the `std` feature, then this type
126/// may used a spin lock internally. This can have subtle effects that may
127/// be undesirable. See [Spinlocks Considered Harmful][spinharm] for a more
128/// thorough treatment of this topic.
129///
130/// [spinharm]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
131///
132/// # Example
133///
134/// This example shows how to share a single hybrid regex among multiple
135/// threads, while also safely getting exclusive access to a hybrid's
136/// [`Cache`](crate::hybrid::regex::Cache) without preventing other searches
137/// from running while your thread uses the `Cache`.
138///
139/// ```
140/// use regex_automata::{
141///     hybrid::regex::{Cache, Regex},
142///     util::{lazy::Lazy, pool::Pool},
143///     Match,
144/// };
145///
146/// static RE: Lazy<Regex> =
147///     Lazy::new(|| Regex::new("foo[0-9]+bar").unwrap());
148/// static CACHE: Lazy<Pool<Cache>> =
149///     Lazy::new(|| Pool::new(|| RE.create_cache()));
150///
151/// let expected = Some(Match::must(0, 3..14));
152/// assert_eq!(expected, RE.find(&mut CACHE.get(), b"zzzfoo12345barzzz"));
153/// ```
154pub struct Pool<T, F = fn() -> T>(alloc::boxed::Box<inner::Pool<T, F>>);
155
156impl<T, F> Pool<T, F> {
157    /// Create a new pool. The given closure is used to create values in
158    /// the pool when necessary.
159    pub fn new(create: F) -> Pool<T, F> {
160        Pool(alloc::boxed::Box::new(inner::Pool::new(create)))
161    }
162
163    /// Create a new pool. The given closure is used to create values in
164    /// the pool when necessary.
165    ///
166    /// When the `std` feature is enabled, a `Pool` is thread-aware and spreads
167    /// its memory out across multiple cache lines. The number of cache lines
168    /// is determined by the `capacity` parameter passed here. By default, a
169    /// fixed reasonable number is used. A smaller number means less memory is
170    /// used, but a higher number means there may be less contention on this
171    /// pool in highly threaded environments doing a lot of searches using the
172    /// same `Regex` value.
173    ///
174    /// When `std` is not enabled, then the capacity parameter is ignored
175    /// because the underlying pool implementation is not thread-aware.
176    ///
177    /// The capacity must be at least 1. If it's less than 1, then it is
178    /// forced to be 1.
179    pub fn with_capacity(capacity: usize, create: F) -> Pool<T, F> {
180        Pool(alloc::boxed::Box::new(inner::Pool::with_capacity(
181            capacity, create,
182        )))
183    }
184
185    /// Create a new pool. The given closure is used to create values in
186    /// the pool when necessary.
187    ///
188    /// This is a convenience routine for calling `Pool::with_capacity` with
189    /// a number equivalent to the available parallelism for this environment.
190    ///
191    /// If `std` is not enabled or if the query for available parallelism
192    /// failed, then this is equivalent to calling `Pool::new`.
193    pub fn with_available_parallelism_capacity(create: F) -> Pool<T, F> {
194        #[cfg(feature = "std")]
195        {
196            use crate::util::lazy::Lazy;
197
198            static AVAILABLE_PARALLELISM: Lazy<Option<usize>> =
199                Lazy::new(|| {
200                    std::thread::available_parallelism().map(|n| n.get()).ok()
201                });
202            let &Some(n) = Lazy::get(&AVAILABLE_PARALLELISM) else {
203                return Pool::new(create);
204            };
205            Pool::with_capacity(n, create)
206        }
207        #[cfg(not(feature = "std"))]
208        {
209            Pool::new(create)
210        }
211    }
212}
213
214impl<T: Send, F: Fn() -> T> Pool<T, F> {
215    /// Get a value from the pool. The caller is guaranteed to have
216    /// exclusive access to the given value. Namely, it is guaranteed that
217    /// this will never return a value that was returned by another call to
218    /// `get` but was not put back into the pool.
219    ///
220    /// When the guard goes out of scope and its destructor is called, then
221    /// it will automatically be put back into the pool. Alternatively,
222    /// [`PoolGuard::put`] may be used to explicitly put it back in the pool
223    /// without relying on its destructor.
224    ///
225    /// Note that there is no guarantee provided about which value in the
226    /// pool is returned. That is, calling get, dropping the guard (causing
227    /// the value to go back into the pool) and then calling get again is
228    /// *not* guaranteed to return the same value received in the first `get`
229    /// call.
230    #[inline]
231    pub fn get(&self) -> PoolGuard<'_, T, F> {
232        PoolGuard(self.0.get())
233    }
234}
235
236impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
237    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
238        f.debug_tuple("Pool").field(&self.0).finish()
239    }
240}
241
242/// A guard that is returned when a caller requests a value from the pool.
243///
244/// The purpose of the guard is to use RAII to automatically put the value
245/// back in the pool once it's dropped.
246pub struct PoolGuard<'a, T: Send, F: Fn() -> T>(inner::PoolGuard<'a, T, F>);
247
248impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
249    /// Consumes this guard and puts it back into the pool.
250    ///
251    /// This circumvents the guard's `Drop` implementation. This can be useful
252    /// in circumstances where the automatic `Drop` results in poorer codegen,
253    /// such as calling non-inlined functions.
254    #[inline]
255    pub fn put(this: PoolGuard<'_, T, F>) {
256        inner::PoolGuard::put(this.0);
257    }
258}
259
260impl<'a, T: Send, F: Fn() -> T> core::ops::Deref for PoolGuard<'a, T, F> {
261    type Target = T;
262
263    #[inline]
264    fn deref(&self) -> &T {
265        self.0.value()
266    }
267}
268
269impl<'a, T: Send, F: Fn() -> T> core::ops::DerefMut for PoolGuard<'a, T, F> {
270    #[inline]
271    fn deref_mut(&mut self) -> &mut T {
272        self.0.value_mut()
273    }
274}
275
276impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
277    for PoolGuard<'a, T, F>
278{
279    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
280        f.debug_tuple("PoolGuard").field(&self.0).finish()
281    }
282}
283
284#[cfg(feature = "std")]
285mod inner {
286    use core::{
287        cell::UnsafeCell,
288        panic::{RefUnwindSafe, UnwindSafe},
289        sync::atomic::{AtomicUsize, Ordering},
290    };
291
292    use alloc::{boxed::Box, vec, vec::Vec};
293
294    use std::{sync::Mutex, thread_local};
295
296    /// An atomic counter used to allocate thread IDs.
297    ///
298    /// We specifically start our counter at 3 so that we can use the values
299    /// less than it as sentinels.
300    static COUNTER: AtomicUsize = AtomicUsize::new(3);
301
302    /// A thread ID indicating that there is no owner. This is the initial
303    /// state of a pool. Once a pool has an owner, there is no way to change
304    /// it.
305    static THREAD_ID_UNOWNED: usize = 0;
306
307    /// A thread ID indicating that the special owner value is in use and not
308    /// available. This state is useful for avoiding a case where the owner
309    /// of a pool calls `get` before putting the result of a previous `get`
310    /// call back into the pool.
311    static THREAD_ID_INUSE: usize = 1;
312
313    /// This sentinel is used to indicate that a guard has already been dropped
314    /// and should not be re-dropped. We use this because our drop code can be
315    /// called outside of Drop and thus there could be a bug in the internal
316    /// implementation that results in trying to put the same guard back into
317    /// the same pool multiple times, and *that* could result in UB if we
318    /// didn't mark the guard as already having been put back in the pool.
319    ///
320    /// So this isn't strictly necessary, but this let's us define some
321    /// routines as safe (like PoolGuard::put_imp) that we couldn't otherwise
322    /// do.
323    static THREAD_ID_DROPPED: usize = 2;
324
325    /// The number of stacks we use inside of the pool. These are only used for
326    /// non-owners. That is, these represent the "slow" path.
327    ///
328    /// In the original implementation of this pool, we only used a single
329    /// stack. While this might be okay for a couple threads, the prevalence of
330    /// 32, 64 and even 128 core CPUs has made it untenable. The contention
331    /// such an environment introduces when threads are doing a lot of searches
332    /// on short haystacks (a not uncommon use case) is palpable and leads to
333    /// huge slowdowns.
334    ///
335    /// This constant reflects a change from using one stack to the number of
336    /// stacks that this constant is set to. The stack for a particular thread
337    /// is simply chosen by `thread_id % MAX_POOL_STACKS`. The idea behind
338    /// this setup is that there should be a good chance that accesses to the
339    /// pool will be distributed over several stacks instead of all of them
340    /// converging to one.
341    ///
342    /// This is not a particularly smart or dynamic strategy. Fixing this to a
343    /// specific number has at least two downsides. First is that it will help,
344    /// say, an 8 core CPU more than it will a 128 core CPU. (But, crucially,
345    /// it will still help the 128 core case.) Second is that this may wind
346    /// up being a little wasteful with respect to memory usage. Namely, if a
347    /// regex is used on one thread and then moved to another thread, then it
348    /// could result in creating a new copy of the data in the pool even though
349    /// only one is actually needed.
350    ///
351    /// And that memory usage bit is why this is set to 8 and not, say, 64.
352    /// Keeping it at 8 limits, to an extent, how much unnecessary memory can
353    /// be allocated.
354    ///
355    /// In an ideal world, we'd be able to have something like this:
356    ///
357    /// * Grow the number of stacks as the number of concurrent callers
358    /// increases. I spent a little time trying this, but even just adding an
359    /// atomic addition/subtraction for each pop/push for tracking concurrent
360    /// callers led to a big perf hit. Since even more work would seemingly be
361    /// required than just an addition/subtraction, I abandoned this approach.
362    /// * The maximum amount of memory used should scale with respect to the
363    /// number of concurrent callers and *not* the total number of existing
364    /// threads. This is primarily why the `thread_local` crate isn't used, as
365    /// as some environments spin up a lot of threads. This led to multiple
366    /// reports of extremely high memory usage (often described as memory
367    /// leaks).
368    /// * Even more ideally, the pool should contract in size. That is, it
369    /// should grow with bursts and then shrink. But this is a pretty thorny
370    /// issue to tackle and it might be better to just not.
371    /// * It would be nice to explore the use of, say, a lock-free stack
372    /// instead of using a mutex to guard a `Vec` that is ultimately just
373    /// treated as a stack. The main thing preventing me from exploring this
374    /// is the ABA problem. The `crossbeam` crate has tools for dealing with
375    /// this sort of problem (via its epoch based memory reclamation strategy),
376    /// but I can't justify bringing in all of `crossbeam` as a dependency of
377    /// `regex` for this.
378    ///
379    /// See this issue for more context and discussion:
380    /// https://github.com/rust-lang/regex/issues/934
381    const MAX_POOL_STACKS: usize = 8;
382
383    thread_local!(
384        /// A thread local used to assign an ID to a thread.
385        static THREAD_ID: usize = {
386            let next = COUNTER.fetch_add(1, Ordering::Relaxed);
387            // SAFETY: We cannot permit the reuse of thread IDs since reusing a
388            // thread ID might result in more than one thread "owning" a pool,
389            // and thus, permit accessing a mutable value from multiple threads
390            // simultaneously without synchronization. The intent of this panic
391            // is to be a sanity check. It is not expected that the thread ID
392            // space will actually be exhausted in practice. Even on a 32-bit
393            // system, it would require spawning 2^32 threads (although they
394            // wouldn't all need to run simultaneously, so it is in theory
395            // possible).
396            //
397            // This checks that the counter never wraps around, since atomic
398            // addition wraps around on overflow.
399            if next == 0 {
400                panic!("regex: thread ID allocation space exhausted");
401            }
402            next
403        };
404    );
405
406    /// This puts each stack in the pool below into its own cache line. This is
407    /// an absolutely critical optimization that tends to have the most impact
408    /// in high contention workloads. Without forcing each mutex protected
409    /// into its own cache line, high contention exacerbates the performance
410    /// problem by causing "false sharing." By putting each mutex in its own
411    /// cache-line, we avoid the false sharing problem and the affects of
412    /// contention are greatly reduced.
413    #[derive(Debug)]
414    #[repr(C, align(64))]
415    struct CacheLine<T>(T);
416
417    /// A thread safe pool utilizing std-only features.
418    ///
419    /// The main difference between this and the simplistic alloc-only pool is
420    /// the use of std::sync::Mutex and an "owner thread" optimization that
421    /// makes accesses by the owner of a pool faster than all other threads.
422    /// This makes the common case of running a regex within a single thread
423    /// faster by avoiding mutex unlocking.
424    pub(super) struct Pool<T, F> {
425        /// A function to create more T values when stack is empty and a caller
426        /// has requested a T.
427        create: F,
428        /// Multiple stacks of T values to hand out. These are used when a Pool
429        /// is accessed by a thread that didn't create it.
430        ///
431        /// Conceptually this is `Mutex<Vec<Box<T>>>`, but sharded out to make
432        /// it scale better under high contention work-loads. We index into
433        /// this sequence via `thread_id % stacks.len()`.
434        stacks: Vec<CacheLine<Mutex<Vec<Box<T>>>>>,
435        /// The ID of the thread that owns this pool. The owner is the thread
436        /// that makes the first call to 'get'. When the owner calls 'get', it
437        /// gets 'owner_val' directly instead of returning a T from 'stack'.
438        /// See comments elsewhere for details, but this is intended to be an
439        /// optimization for the common case that makes getting a T faster.
440        ///
441        /// It is initialized to a value of zero (an impossible thread ID) as a
442        /// sentinel to indicate that it is unowned.
443        owner: AtomicUsize,
444        /// A value to return when the caller is in the same thread that
445        /// first called `Pool::get`.
446        ///
447        /// This is set to None when a Pool is first created, and set to Some
448        /// once the first thread calls Pool::get.
449        owner_val: UnsafeCell<Option<T>>,
450    }
451
452    // SAFETY: Since we want to use a Pool from multiple threads simultaneously
453    // behind an Arc, we need for it to be Sync. In cases where T is sync,
454    // Pool<T> would be Sync. However, since we use a Pool to store mutable
455    // scratch space, we wind up using a T that has interior mutability and is
456    // thus itself not Sync. So what we *really* want is for our Pool<T> to by
457    // Sync even when T is not Sync (but is at least Send).
458    //
459    // The only non-sync aspect of a Pool is its 'owner_val' field, which is
460    // used to implement faster access to a pool value in the common case of
461    // a pool being accessed in the same thread in which it was created. The
462    // 'stack' field is also shared, but a Mutex<T> where T: Send is already
463    // Sync. So we only need to worry about 'owner_val'.
464    //
465    // The key is to guarantee that 'owner_val' can only ever be accessed from
466    // one thread. In our implementation below, we guarantee this by only
467    // returning the 'owner_val' when the ID of the current thread matches the
468    // ID of the thread that first called 'Pool::get'. Since this can only ever
469    // be one thread, it follows that only one thread can access 'owner_val' at
470    // any point in time. Thus, it is safe to declare that Pool<T> is Sync when
471    // T is Send.
472    //
473    // If there is a way to achieve our performance goals using safe code, then
474    // I would very much welcome a patch. As it stands, the implementation
475    // below tries to balance safety with performance. The case where a Regex
476    // is used from multiple threads simultaneously will suffer a bit since
477    // getting a value out of the pool will require unlocking a mutex.
478    //
479    // We require `F: Send + Sync` because we call `F` at any point on demand,
480    // potentially from multiple threads simultaneously.
481    unsafe impl<T: Send, F: Send + Sync> Sync for Pool<T, F> {}
482
483    // If T is UnwindSafe, then since we provide exclusive access to any
484    // particular value in the pool, the pool should therefore also be
485    // considered UnwindSafe.
486    //
487    // We require `F: UnwindSafe + RefUnwindSafe` because we call `F` at any
488    // point on demand, so it needs to be unwind safe on both dimensions for
489    // the entire Pool to be unwind safe.
490    impl<T: UnwindSafe, F: UnwindSafe + RefUnwindSafe> UnwindSafe for Pool<T, F> {}
491
492    // If T is UnwindSafe, then since we provide exclusive access to any
493    // particular value in the pool, the pool should therefore also be
494    // considered RefUnwindSafe.
495    //
496    // We require `F: UnwindSafe + RefUnwindSafe` because we call `F` at any
497    // point on demand, so it needs to be unwind safe on both dimensions for
498    // the entire Pool to be unwind safe.
499    impl<T: UnwindSafe, F: UnwindSafe + RefUnwindSafe> RefUnwindSafe
500        for Pool<T, F>
501    {
502    }
503
504    impl<T, F> Pool<T, F> {
505        /// Create a new pool. The given closure is used to create values in
506        /// the pool when necessary.
507        pub(super) fn new(create: F) -> Pool<T, F> {
508            Pool::with_capacity(MAX_POOL_STACKS, create)
509        }
510
511        /// Create a new pool. The given closure is used to create values in
512        /// the pool when necessary.
513        ///
514        /// The given capacity is used to determine how many cache lines to
515        /// maintain. Each cache line contains a stack of cached entries.
516        ///
517        /// The capacity must be at least 1. If it's less than 1, then it is
518        /// forced to be 1.
519        pub(super) fn with_capacity(capacity: usize, create: F) -> Pool<T, F> {
520            // FIXME: Now that we require 1.65+, Mutex::new is available as
521            // const... So we can almost mark this function as const. But of
522            // course, we're creating a Vec of stacks below (we didn't when I
523            // originally wrote this code). It seems like the best way to work
524            // around this would be to use a `[Stack; MAX_POOL_STACKS]` instead
525            // of a `Vec<Stack>`. I refrained from making this change at time
526            // of writing (2023/10/08) because I was making a lot of other
527            // changes at the same time and wanted to do this more carefully.
528            // Namely, because of the cache line optimization, that `[Stack;
529            // MAX_POOL_STACKS]` would be quite big. It's unclear how bad (if
530            // at all) that would be.
531            //
532            // Another choice would be to lazily allocate the stacks, but...
533            // I'm not so sure about that. Seems like a fair bit of complexity?
534            //
535            // Maybe there's a simple solution I'm missing.
536            //
537            // ... OK, I tried to fix this. First, I did it by putting `stacks`
538            // in an `UnsafeCell` and using a `Once` to lazily initialize it.
539            // I benchmarked it and everything looked okay. I then made this
540            // function `const` and thought I was just about done. But the
541            // public pool type wraps its inner pool in a `Box` to keep its
542            // size down. Blech.
543            //
544            // So then I thought that I could push the box down into this
545            // type (and leave the non-std version unboxed) and use the same
546            // `UnsafeCell` technique to lazily initialize it. This has the
547            // downside of the `Once` now needing to get hit in the owner fast
548            // path, but maybe that's OK? However, I then realized that we can
549            // only lazily initialize `stacks`, `owner` and `owner_val`. The
550            // `create` function needs to be put somewhere outside of the box.
551            // So now the pool is a `Box`, `Once` and a function. Now we're
552            // starting to defeat the point of boxing in the first place. So I
553            // backed out that change too.
554            //
555            // Back to square one. I maybe we just don't make a pool's
556            // constructor const and live with it. It's probably not a huge
557            // deal.
558            let mut stacks = Vec::with_capacity(capacity.max(1));
559            for _ in 0..stacks.capacity() {
560                stacks.push(CacheLine(Mutex::new(vec![])));
561            }
562            let owner = AtomicUsize::new(THREAD_ID_UNOWNED);
563            let owner_val = UnsafeCell::new(None); // init'd on first access
564            Pool { create, stacks, owner, owner_val }
565        }
566    }
567
568    impl<T: Send, F: Fn() -> T> Pool<T, F> {
569        /// Get a value from the pool. This may block if another thread is also
570        /// attempting to retrieve a value from the pool.
571        #[inline]
572        pub(super) fn get(&self) -> PoolGuard<'_, T, F> {
573            // Our fast path checks if the caller is the thread that "owns"
574            // this pool. Or stated differently, whether it is the first thread
575            // that tried to extract a value from the pool. If it is, then we
576            // can return a T to the caller without going through a mutex.
577            //
578            // SAFETY: We must guarantee that only one thread gets access
579            // to this value. Since a thread is uniquely identified by the
580            // THREAD_ID thread local, it follows that if the caller's thread
581            // ID is equal to the owner, then only one thread may receive this
582            // value. This is also why we can get away with what looks like a
583            // racy load and a store. We know that if 'owner == caller', then
584            // only one thread can be here, so we don't need to worry about any
585            // other thread setting the owner to something else.
586            let caller = THREAD_ID.with(|id| *id);
587            let owner = self.owner.load(Ordering::Acquire);
588            if caller == owner {
589                // N.B. We could also do a CAS here instead of a load/store,
590                // but ad hoc benchmarking suggests it is slower. And a lot
591                // slower in the case where `get_slow` is common.
592                self.owner.store(THREAD_ID_INUSE, Ordering::Release);
593                return self.guard_owned(caller);
594            }
595            self.get_slow(caller, owner)
596        }
597
598        /// This is the "slow" version that goes through a mutex to pop an
599        /// allocated value off a stack to return to the caller. (Or, if the
600        /// stack is empty, a new value is created.)
601        ///
602        /// If the pool has no owner, then this will set the owner.
603        #[cold]
604        fn get_slow(
605            &self,
606            caller: usize,
607            owner: usize,
608        ) -> PoolGuard<'_, T, F> {
609            if owner == THREAD_ID_UNOWNED {
610                // This sentinel means this pool is not yet owned. We try to
611                // atomically set the owner. If we do, then this thread becomes
612                // the owner and we can return a guard that represents the
613                // special T for the owner.
614                //
615                // Note that we set the owner to a different sentinel that
616                // indicates that the owned value is in use. The owner ID will
617                // get updated to the actual ID of this thread once the guard
618                // returned by this function is put back into the pool.
619                let res = self.owner.compare_exchange(
620                    THREAD_ID_UNOWNED,
621                    THREAD_ID_INUSE,
622                    Ordering::AcqRel,
623                    Ordering::Acquire,
624                );
625                if res.is_ok() {
626                    // SAFETY: A successful CAS above implies this thread is
627                    // the owner and that this is the only such thread that
628                    // can reach here. Thus, there is no data race.
629                    unsafe {
630                        *self.owner_val.get() = Some((self.create)());
631                    }
632                    return self.guard_owned(caller);
633                }
634            }
635            let stack_id = caller % self.stacks.len();
636            // We try to acquire exclusive access to this thread's stack, and
637            // if so, grab a value from it if we can. We put this in a loop so
638            // that it's easy to tweak and experiment with a different number
639            // of tries. In the end, I couldn't see anything obviously better
640            // than one attempt in ad hoc testing.
641            for _ in 0..1 {
642                let mut stack = match self.stacks[stack_id].0.try_lock() {
643                    Err(_) => continue,
644                    Ok(stack) => stack,
645                };
646                if let Some(value) = stack.pop() {
647                    return self.guard_stack(value);
648                }
649                // Unlock the mutex guarding the stack before creating a fresh
650                // value since we no longer need the stack.
651                drop(stack);
652                let value = Box::new((self.create)());
653                return self.guard_stack(value);
654            }
655            // We're only here if we could get access to our stack, so just
656            // create a new value. This seems like it could be wasteful, but
657            // waiting for exclusive access to a stack when there's high
658            // contention is brutal for perf.
659            self.guard_stack_transient(Box::new((self.create)()))
660        }
661
662        /// Puts a value back into the pool. Callers don't need to call this.
663        /// Once the guard that's returned by 'get' is dropped, it is put back
664        /// into the pool automatically.
665        #[inline]
666        fn put_value(&self, value: Box<T>) {
667            let caller = THREAD_ID.with(|id| *id);
668            let stack_id = caller % self.stacks.len();
669            // As with trying to pop a value from this thread's stack, we
670            // merely attempt to get access to push this value back on the
671            // stack. If there's too much contention, we just give up and throw
672            // the value away.
673            //
674            // Interestingly, in ad hoc benchmarking, it is beneficial to
675            // attempt to push the value back more than once, unlike when
676            // popping the value. I don't have a good theory for why this is.
677            // I guess if we drop too many values then that winds up forcing
678            // the pop operation to create new fresh values and thus leads to
679            // less reuse. There's definitely a balancing act here.
680            for _ in 0..10 {
681                let mut stack = match self.stacks[stack_id].0.try_lock() {
682                    Err(_) => continue,
683                    Ok(stack) => stack,
684                };
685                stack.push(value);
686                return;
687            }
688        }
689
690        /// Create a guard that represents the special owned T.
691        #[inline]
692        fn guard_owned(&self, caller: usize) -> PoolGuard<'_, T, F> {
693            PoolGuard { pool: self, value: Err(caller), discard: false }
694        }
695
696        /// Create a guard that contains a value from the pool's stack.
697        #[inline]
698        fn guard_stack(&self, value: Box<T>) -> PoolGuard<'_, T, F> {
699            PoolGuard { pool: self, value: Ok(value), discard: false }
700        }
701
702        /// Create a guard that contains a value from the pool's stack with an
703        /// instruction to throw away the value instead of putting it back
704        /// into the pool.
705        #[inline]
706        fn guard_stack_transient(&self, value: Box<T>) -> PoolGuard<'_, T, F> {
707            PoolGuard { pool: self, value: Ok(value), discard: true }
708        }
709    }
710
711    impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
712        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
713            f.debug_struct("Pool")
714                .field("stacks", &self.stacks)
715                .field("owner", &self.owner)
716                .field("owner_val", &self.owner_val)
717                .finish()
718        }
719    }
720
721    /// A guard that is returned when a caller requests a value from the pool.
722    pub(super) struct PoolGuard<'a, T: Send, F: Fn() -> T> {
723        /// The pool that this guard is attached to.
724        pool: &'a Pool<T, F>,
725        /// This is Err when the guard represents the special "owned" value.
726        /// In which case, the value is retrieved from 'pool.owner_val'. And
727        /// in the special case of `Err(THREAD_ID_DROPPED)`, it means the
728        /// guard has been put back into the pool and should no longer be used.
729        value: Result<Box<T>, usize>,
730        /// When true, the value should be discarded instead of being pushed
731        /// back into the pool. We tend to use this under high contention, and
732        /// this allows us to avoid inflating the size of the pool. (Because
733        /// under contention, we tend to create more values instead of waiting
734        /// for access to a stack of existing values.)
735        discard: bool,
736    }
737
738    impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
739        /// Return the underlying value.
740        #[inline]
741        pub(super) fn value(&self) -> &T {
742            match self.value {
743                Ok(ref v) => v,
744                // SAFETY: This is safe because the only way a PoolGuard gets
745                // created for self.value=Err is when the current thread
746                // corresponds to the owning thread, of which there can only
747                // be one. Thus, we are guaranteed to be providing exclusive
748                // access here which makes this safe.
749                //
750                // Also, since 'owner_val' is guaranteed to be initialized
751                // before an owned PoolGuard is created, the unchecked unwrap
752                // is safe.
753                Err(id) => unsafe {
754                    // This assert is *not* necessary for safety, since we
755                    // should never be here if the guard had been put back into
756                    // the pool. This is a sanity check to make sure we didn't
757                    // break an internal invariant.
758                    debug_assert_ne!(THREAD_ID_DROPPED, id);
759                    (*self.pool.owner_val.get()).as_ref().unwrap_unchecked()
760                },
761            }
762        }
763
764        /// Return the underlying value as a mutable borrow.
765        #[inline]
766        pub(super) fn value_mut(&mut self) -> &mut T {
767            match self.value {
768                Ok(ref mut v) => v,
769                // SAFETY: This is safe because the only way a PoolGuard gets
770                // created for self.value=None is when the current thread
771                // corresponds to the owning thread, of which there can only
772                // be one. Thus, we are guaranteed to be providing exclusive
773                // access here which makes this safe.
774                //
775                // Also, since 'owner_val' is guaranteed to be initialized
776                // before an owned PoolGuard is created, the unwrap_unchecked
777                // is safe.
778                Err(id) => unsafe {
779                    // This assert is *not* necessary for safety, since we
780                    // should never be here if the guard had been put back into
781                    // the pool. This is a sanity check to make sure we didn't
782                    // break an internal invariant.
783                    debug_assert_ne!(THREAD_ID_DROPPED, id);
784                    (*self.pool.owner_val.get()).as_mut().unwrap_unchecked()
785                },
786            }
787        }
788
789        /// Consumes this guard and puts it back into the pool.
790        #[inline]
791        pub(super) fn put(this: PoolGuard<'_, T, F>) {
792            // Since this is effectively consuming the guard and putting the
793            // value back into the pool, there's no reason to run its Drop
794            // impl after doing this. I don't believe there is a correctness
795            // problem with doing so, but there's definitely a perf problem
796            // by redoing this work. So we avoid it.
797            let mut this = core::mem::ManuallyDrop::new(this);
798            this.put_imp();
799        }
800
801        /// Puts this guard back into the pool by only borrowing the guard as
802        /// mutable. This should be called at most once.
803        #[inline(always)]
804        fn put_imp(&mut self) {
805            match core::mem::replace(&mut self.value, Err(THREAD_ID_DROPPED)) {
806                Ok(value) => {
807                    // If we were told to discard this value then don't bother
808                    // trying to put it back into the pool. This occurs when
809                    // the pop operation failed to acquire a lock and we
810                    // decided to create a new value in lieu of contending for
811                    // the lock.
812                    if self.discard {
813                        return;
814                    }
815                    self.pool.put_value(value);
816                }
817                // If this guard has a value "owned" by the thread, then
818                // the Pool guarantees that this is the ONLY such guard.
819                // Therefore, in order to place it back into the pool and make
820                // it available, we need to change the owner back to the owning
821                // thread's ID. But note that we use the ID that was stored in
822                // the guard, since a guard can be moved to another thread and
823                // dropped. (A previous iteration of this code read from the
824                // THREAD_ID thread local, which uses the ID of the current
825                // thread which may not be the ID of the owning thread! This
826                // also avoids the TLS access, which is likely a hair faster.)
827                Err(owner) => {
828                    // If we hit this point, it implies 'put_imp' has been
829                    // called multiple times for the same guard which in turn
830                    // corresponds to a bug in this implementation.
831                    assert_ne!(THREAD_ID_DROPPED, owner);
832                    self.pool.owner.store(owner, Ordering::Release);
833                }
834            }
835        }
836    }
837
838    impl<'a, T: Send, F: Fn() -> T> Drop for PoolGuard<'a, T, F> {
839        #[inline]
840        fn drop(&mut self) {
841            self.put_imp();
842        }
843    }
844
845    impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
846        for PoolGuard<'a, T, F>
847    {
848        fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
849            f.debug_struct("PoolGuard")
850                .field("pool", &self.pool)
851                .field("value", &self.value)
852                .finish()
853        }
854    }
855}
856
857// FUTURE: We should consider using Mara Bos's nearly-lock-free version of this
858// here: https://gist.github.com/m-ou-se/5fdcbdf7dcf4585199ce2de697f367a4.
859//
860// One reason why I did things with a "mutex" below is that it isolates the
861// safety concerns to just the Mutex, where as the safety of Mara's pool is a
862// bit more sprawling. I also expect this code to not be used that much, and
863// so is unlikely to get as much real world usage with which to test it. That
864// means the "obviously correct" lever is an important one.
865//
866// The specific reason to use Mara's pool is that it is likely faster and also
867// less likely to hit problems with spin-locks, although it is not completely
868// impervious to them.
869//
870// The best solution to this problem, probably, is a truly lock free pool. That
871// could be done with a lock free linked list. The issue is the ABA problem. It
872// is difficult to avoid, and doing so is complex. BUT, the upshot of that is
873// that if we had a truly lock free pool, then we could also use it above in
874// the 'std' pool instead of a Mutex because it should be completely free the
875// problems that come from spin-locks.
876#[cfg(not(feature = "std"))]
877mod inner {
878    use core::{
879        cell::UnsafeCell,
880        panic::{RefUnwindSafe, UnwindSafe},
881        sync::atomic::{AtomicBool, Ordering},
882    };
883
884    use alloc::{boxed::Box, vec, vec::Vec};
885
886    /// A thread safe pool utilizing alloc-only features.
887    ///
888    /// Unlike the std version, it doesn't seem possible(?) to implement the
889    /// "thread owner" optimization because alloc-only doesn't have any concept
890    /// of threads. So the best we can do is just a normal stack. This will
891    /// increase latency in alloc-only environments.
892    pub(super) struct Pool<T, F> {
893        /// A stack of T values to hand out. These are used when a Pool is
894        /// accessed by a thread that didn't create it.
895        stack: Mutex<Vec<Box<T>>>,
896        /// A function to create more T values when stack is empty and a caller
897        /// has requested a T.
898        create: F,
899    }
900
901    // If T is UnwindSafe, then since we provide exclusive access to any
902    // particular value in the pool, it should therefore also be considered
903    // RefUnwindSafe.
904    impl<T: UnwindSafe, F: UnwindSafe> RefUnwindSafe for Pool<T, F> {}
905
906    impl<T, F> Pool<T, F> {
907        /// Create a new pool. The given closure is used to create values in
908        /// the pool when necessary.
909        pub(super) const fn new(create: F) -> Pool<T, F> {
910            Pool { stack: Mutex::new(vec![]), create }
911        }
912
913        /// This is a no-op since this pool implementation isn't thread-aware.
914        pub(super) const fn with_capacity(
915            _capacity: usize,
916            create: F,
917        ) -> Pool<T, F> {
918            Pool::new(create)
919        }
920    }
921
922    impl<T: Send, F: Fn() -> T> Pool<T, F> {
923        /// Get a value from the pool. This may block if another thread is also
924        /// attempting to retrieve a value from the pool.
925        #[inline]
926        pub(super) fn get(&self) -> PoolGuard<'_, T, F> {
927            let mut stack = self.stack.lock();
928            let value = match stack.pop() {
929                None => Box::new((self.create)()),
930                Some(value) => value,
931            };
932            PoolGuard { pool: self, value: Some(value) }
933        }
934
935        #[inline]
936        fn put(&self, guard: PoolGuard<'_, T, F>) {
937            let mut guard = core::mem::ManuallyDrop::new(guard);
938            if let Some(value) = guard.value.take() {
939                self.put_value(value);
940            }
941        }
942
943        /// Puts a value back into the pool. Callers don't need to call this.
944        /// Once the guard that's returned by 'get' is dropped, it is put back
945        /// into the pool automatically.
946        #[inline]
947        fn put_value(&self, value: Box<T>) {
948            let mut stack = self.stack.lock();
949            stack.push(value);
950        }
951    }
952
953    impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
954        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
955            f.debug_struct("Pool").field("stack", &self.stack).finish()
956        }
957    }
958
959    /// A guard that is returned when a caller requests a value from the pool.
960    pub(super) struct PoolGuard<'a, T: Send, F: Fn() -> T> {
961        /// The pool that this guard is attached to.
962        pool: &'a Pool<T, F>,
963        /// This is None after the guard has been put back into the pool.
964        value: Option<Box<T>>,
965    }
966
967    impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
968        /// Return the underlying value.
969        #[inline]
970        pub(super) fn value(&self) -> &T {
971            self.value.as_deref().unwrap()
972        }
973
974        /// Return the underlying value as a mutable borrow.
975        #[inline]
976        pub(super) fn value_mut(&mut self) -> &mut T {
977            self.value.as_deref_mut().unwrap()
978        }
979
980        /// Consumes this guard and puts it back into the pool.
981        #[inline]
982        pub(super) fn put(this: PoolGuard<'_, T, F>) {
983            // Since this is effectively consuming the guard and putting the
984            // value back into the pool, there's no reason to run its Drop
985            // impl after doing this. I don't believe there is a correctness
986            // problem with doing so, but there's definitely a perf problem
987            // by redoing this work. So we avoid it.
988            let mut this = core::mem::ManuallyDrop::new(this);
989            this.put_imp();
990        }
991
992        /// Puts this guard back into the pool by only borrowing the guard as
993        /// mutable. This should be called at most once.
994        #[inline(always)]
995        fn put_imp(&mut self) {
996            if let Some(value) = self.value.take() {
997                self.pool.put_value(value);
998            }
999        }
1000    }
1001
1002    impl<'a, T: Send, F: Fn() -> T> Drop for PoolGuard<'a, T, F> {
1003        #[inline]
1004        fn drop(&mut self) {
1005            self.put_imp();
1006        }
1007    }
1008
1009    impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
1010        for PoolGuard<'a, T, F>
1011    {
1012        fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1013            f.debug_struct("PoolGuard")
1014                .field("pool", &self.pool)
1015                .field("value", &self.value)
1016                .finish()
1017        }
1018    }
1019
1020    /// A spin-lock based mutex. Yes, I have read spinlocks considered
1021    /// harmful[1], and if there's a reasonable alternative choice, I'll
1022    /// happily take it.
1023    ///
1024    /// I suspect the most likely alternative here is a Treiber stack, but
1025    /// implementing one correctly in a way that avoids the ABA problem looks
1026    /// subtle enough that I'm not sure I want to attempt that. But otherwise,
1027    /// we only need a mutex in order to implement our pool, so if there's
1028    /// something simpler we can use that works for our `Pool` use case, then
1029    /// that would be great.
1030    ///
1031    /// Note that this mutex does not do poisoning.
1032    ///
1033    /// [1]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
1034    #[derive(Debug)]
1035    struct Mutex<T> {
1036        locked: AtomicBool,
1037        data: UnsafeCell<T>,
1038    }
1039
1040    // SAFETY: Since a Mutex guarantees exclusive access, as long as we can
1041    // send it across threads, it must also be Sync.
1042    unsafe impl<T: Send> Sync for Mutex<T> {}
1043
1044    impl<T> Mutex<T> {
1045        /// Create a new mutex for protecting access to the given value across
1046        /// multiple threads simultaneously.
1047        const fn new(value: T) -> Mutex<T> {
1048            Mutex {
1049                locked: AtomicBool::new(false),
1050                data: UnsafeCell::new(value),
1051            }
1052        }
1053
1054        /// Lock this mutex and return a guard providing exclusive access to
1055        /// `T`. This blocks if some other thread has already locked this
1056        /// mutex.
1057        #[inline]
1058        fn lock(&self) -> MutexGuard<'_, T> {
1059            while self
1060                .locked
1061                .compare_exchange(
1062                    false,
1063                    true,
1064                    Ordering::AcqRel,
1065                    Ordering::Acquire,
1066                )
1067                .is_err()
1068            {
1069                core::hint::spin_loop();
1070            }
1071            // SAFETY: The only way we're here is if we successfully set
1072            // 'locked' to true, which implies we must be the only thread here
1073            // and thus have exclusive access to 'data'.
1074            let data = unsafe { &mut *self.data.get() };
1075            MutexGuard { locked: &self.locked, data }
1076        }
1077    }
1078
1079    /// A guard that derefs to &T and &mut T. When it's dropped, the lock is
1080    /// released.
1081    #[derive(Debug)]
1082    struct MutexGuard<'a, T> {
1083        locked: &'a AtomicBool,
1084        data: &'a mut T,
1085    }
1086
1087    impl<'a, T> core::ops::Deref for MutexGuard<'a, T> {
1088        type Target = T;
1089
1090        #[inline]
1091        fn deref(&self) -> &T {
1092            self.data
1093        }
1094    }
1095
1096    impl<'a, T> core::ops::DerefMut for MutexGuard<'a, T> {
1097        #[inline]
1098        fn deref_mut(&mut self) -> &mut T {
1099            self.data
1100        }
1101    }
1102
1103    impl<'a, T> Drop for MutexGuard<'a, T> {
1104        #[inline]
1105        fn drop(&mut self) {
1106            // Drop means 'data' is no longer accessible, so we can unlock
1107            // the mutex.
1108            self.locked.store(false, Ordering::Release);
1109        }
1110    }
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115    use core::panic::{RefUnwindSafe, UnwindSafe};
1116
1117    use alloc::{boxed::Box, vec, vec::Vec};
1118
1119    use super::*;
1120
1121    #[test]
1122    fn oibits() {
1123        fn assert_oitbits<T: Send + Sync + UnwindSafe + RefUnwindSafe>() {}
1124        assert_oitbits::<Pool<Vec<u32>>>();
1125        assert_oitbits::<Pool<core::cell::RefCell<Vec<u32>>>>();
1126        assert_oitbits::<
1127            Pool<
1128                Vec<u32>,
1129                Box<
1130                    dyn Fn() -> Vec<u32>
1131                        + Send
1132                        + Sync
1133                        + UnwindSafe
1134                        + RefUnwindSafe,
1135                >,
1136            >,
1137        >();
1138    }
1139
1140    // Tests that Pool implements the "single owner" optimization. That is, the
1141    // thread that first accesses the pool gets its own copy, while all other
1142    // threads get distinct copies.
1143    #[cfg(feature = "std")]
1144    #[test]
1145    fn thread_owner_optimization() {
1146        use std::{cell::RefCell, sync::Arc, vec};
1147
1148        let pool: Arc<Pool<RefCell<Vec<char>>>> =
1149            Arc::new(Pool::new(|| RefCell::new(vec!['a'])));
1150        pool.get().borrow_mut().push('x');
1151
1152        let pool1 = pool.clone();
1153        let t1 = std::thread::spawn(move || {
1154            let guard = pool1.get();
1155            guard.borrow_mut().push('y');
1156        });
1157
1158        let pool2 = pool.clone();
1159        let t2 = std::thread::spawn(move || {
1160            let guard = pool2.get();
1161            guard.borrow_mut().push('z');
1162        });
1163
1164        t1.join().unwrap();
1165        t2.join().unwrap();
1166
1167        // If we didn't implement the single owner optimization, then one of
1168        // the threads above is likely to have mutated the [a, x] vec that
1169        // we stuffed in the pool before spawning the threads. But since
1170        // neither thread was first to access the pool, and because of the
1171        // optimization, we should be guaranteed that neither thread mutates
1172        // the special owned pool value.
1173        //
1174        // (Technically this is an implementation detail and not a contract of
1175        // Pool's API.)
1176        assert_eq!(vec!['a', 'x'], *pool.get().borrow());
1177    }
1178
1179    // This tests that if the "owner" of a pool asks for two values, then it
1180    // gets two distinct values and not the same one. This test failed in the
1181    // course of developing the pool, which in turn resulted in UB because it
1182    // permitted getting aliasing &mut borrows to the same place in memory.
1183    #[test]
1184    fn thread_owner_distinct() {
1185        let pool = Pool::new(|| vec!['a']);
1186
1187        {
1188            let mut g1 = pool.get();
1189            let v1 = &mut *g1;
1190            let mut g2 = pool.get();
1191            let v2 = &mut *g2;
1192            v1.push('b');
1193            v2.push('c');
1194            assert_eq!(&mut vec!['a', 'b'], v1);
1195            assert_eq!(&mut vec!['a', 'c'], v2);
1196        }
1197        // This isn't technically guaranteed, but we
1198        // expect to now get the "owned" value (the first
1199        // call to 'get()' above) now that it's back in
1200        // the pool.
1201        assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
1202    }
1203
1204    // This tests that we can share a guard with another thread, mutate the
1205    // underlying value and everything works. This failed in the course of
1206    // developing a pool since the pool permitted 'get()' to return the same
1207    // value to the owner thread, even before the previous value was put back
1208    // into the pool. This in turn resulted in this test producing a data race.
1209    #[cfg(feature = "std")]
1210    #[test]
1211    fn thread_owner_sync() {
1212        let pool = Pool::new(|| vec!['a']);
1213        {
1214            let mut g1 = pool.get();
1215            let mut g2 = pool.get();
1216            std::thread::scope(|s| {
1217                s.spawn(|| {
1218                    g1.push('b');
1219                });
1220                s.spawn(|| {
1221                    g2.push('c');
1222                });
1223            });
1224
1225            let v1 = &mut *g1;
1226            let v2 = &mut *g2;
1227            assert_eq!(&mut vec!['a', 'b'], v1);
1228            assert_eq!(&mut vec!['a', 'c'], v2);
1229        }
1230
1231        // This isn't technically guaranteed, but we
1232        // expect to now get the "owned" value (the first
1233        // call to 'get()' above) now that it's back in
1234        // the pool.
1235        assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
1236    }
1237
1238    // This tests that if we move a PoolGuard that is owned by the current
1239    // thread to another thread and drop it, then the thread owner doesn't
1240    // change. During development of the pool, this test failed because the
1241    // PoolGuard assumed it was dropped in the same thread from which it was
1242    // created, and thus used the current thread's ID as the owner, which could
1243    // be different than the actual owner of the pool.
1244    #[cfg(feature = "std")]
1245    #[test]
1246    fn thread_owner_send_drop() {
1247        let pool = Pool::new(|| vec!['a']);
1248        // Establishes this thread as the owner.
1249        {
1250            pool.get().push('b');
1251        }
1252        std::thread::scope(|s| {
1253            // Sanity check that we get the same value back.
1254            // (Not technically guaranteed.)
1255            let mut g = pool.get();
1256            assert_eq!(&vec!['a', 'b'], &*g);
1257            // Now push it to another thread and drop it.
1258            s.spawn(move || {
1259                g.push('c');
1260            })
1261            .join()
1262            .unwrap();
1263        });
1264        // Now check that we're still the owner. This is not technically
1265        // guaranteed by the API, but is true in practice given the thread
1266        // owner optimization.
1267        assert_eq!(&vec!['a', 'b', 'c'], &*pool.get());
1268    }
1269}