1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Regular pool

use std::{
    collections::VecDeque,
    future::Future,
    mem::ManuallyDrop,
    ops::{Deref, DerefMut},
    pin::Pin,
    task::{Context, Poll},
};

use futures_channel::oneshot::{Receiver, Sender};
use pin_project_lite::pin_project;

use crate::internal::{try_recv_from_borrowed, try_recv_from_borrowed_and_panic_if_lost, poll_all_borrowed_and_push_back_ready};

/// An item that is borrowed from the [`Pool`]
///
/// Dropping this item will return it to the pool.
pub struct PooledItem<T> {
    /// The item borrowed from the pool
    item: ManuallyDrop<T>,

    /// Sender that places the item back into the pool
    sender: ManuallyDrop<Sender<T>>,
}

impl<T: std::fmt::Debug> std::fmt::Debug for PooledItem<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PooledItem").field("item", &self.item).finish()
    }
}

impl<T> Deref for PooledItem<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.item
    }
}

impl<T> DerefMut for PooledItem<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.item
    }
}

impl<T> Drop for PooledItem<T> {
    fn drop(&mut self) {
        // # SAFETY:
        //
        // This is the only place where the ownerships of the item and sender
        // are taken and then transferred back to the pool, and thus the only
        // unsafe access to the memory.
        unsafe {
            let item = ManuallyDrop::take(&mut self.item);
            let sender = ManuallyDrop::take(&mut self.sender);

            if sender.send(item).is_err() {
                cfg_log! {
                    log::error!("PooledItem was dropped without being returned to pool. The pool might have been dropped.");
                }

                cfg_tracing! {
                    tracing::error!("PooledItem was dropped without being returned to pool. The pool might have been dropped.");
                }
            }
        }
    }
}

impl<T> PooledItem<T> {
    fn new(item: T, sender: Sender<T>) -> Self {
        Self {
            item: ManuallyDrop::new(item),
            sender: ManuallyDrop::new(sender),
        }
    }

    /// Get a reference to the item
    pub fn item(&self) -> &T {
        &self.item
    }

    /// Get a mutable reference to the item
    pub fn item_mut(&mut self) -> &mut T {
        &mut self.item
    }
}

/// A pool of generic items
///
/// Internally it maintains two lists: one of ready items and one of borrowed
/// 
/// # Examples
///
/// Non-async [`Pool`] example:
///
/// ```rust
/// use piscina::Pool;
///
/// let mut pool = Pool::new();
/// pool.put(1);
/// pool.put(2);
///
/// let item1 = pool.try_get();
/// assert!(item1.is_some());
///
/// let item2 = pool.blocking_get();
///
/// let none = pool.try_get();
/// assert!(none.is_none());
///
/// drop(item1); // Return the item to the pool by dropping it
/// let item3 = pool.try_get();
/// assert!(item3.is_some());
/// ```
///
/// Async [`Pool`] example:
///
/// ```rust
/// use piscina::Pool;
///
/// futures::executor::block_on(async {
///     let mut pool = Pool::new();
///     pool.put(1);
///     pool.put(2);
///
///     let item1 = pool.get().await;
///     let item2 = pool.get().await;
///
///     let none = pool.try_get();
///     assert!(none.is_none());
///
///     drop(item1); // Return the item to the pool by dropping it
///     let item3 = pool.get().await;
/// });
/// ```
#[derive(Debug, Default)]
pub struct Pool<T> {
    /// List of ready items
    ready: VecDeque<T>,

    /// List of borrowed items
    borrowed: Vec<Receiver<T>>,
}

impl<T> Pool<T> {
    /// Creates an empty pool
    pub fn new() -> Self {
        Self {
            ready: VecDeque::new(),
            borrowed: Vec::new(),
        }
    }

    /// Creates an empty pool with the specified capacity for both the ready and borrowed lists.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            ready: VecDeque::with_capacity(capacity),
            borrowed: Vec::with_capacity(capacity),
        }
    }

    /// Returns the number of all items, whether ready or borrowed.
    pub fn len(&self) -> usize {
        self.ready.len() + self.borrowed.len()
    }

    /// Returns `true` if the pool contains no items.
    pub fn is_empty(&self) -> bool {
        self.ready.is_empty() && self.borrowed.is_empty()
    }

    /// Shrinks the capacity of both the ready and borrowed lists as much as
    /// possible.
    pub fn shrink_to_fit(&mut self) {
        self.ready.shrink_to_fit();
        self.borrowed.shrink_to_fit();
    }

    /// Puts an item into the pool
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// ```
    pub fn put(&mut self, item: T) {
        self.ready.push_back(item);
    }

    /// Tries to get an item from the pool. Returns `None` if there is no item immediately available.
    ///
    /// Please note that if the sender is dropped before the item is returned to the pool, the
    /// item will be lost and this will be reflected on the pool's length.
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// let item = pool.try_get();
    /// assert!(item.is_some());
    /// ```
    pub fn try_get(&mut self) -> Option<PooledItem<T>> {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;
        try_recv_from_borrowed(ready, borrowed);
        match self.ready.pop_front() {
            Some(item) => {
                let (tx, rx) = futures_channel::oneshot::channel();
                self.borrowed.push(rx);
                Some(PooledItem::new(item, tx))
            }
            None => None,
        }
    }

    /// Gets an item from the pool. If there is no item immediately available, this will wait
    /// in a blocking manner until an item is available.
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// let item = pool.blocking_get();
    /// ```
    ///
    /// # Panic
    ///
    /// This will panic if the sender is dropped before the item is returned to the pool, which
    /// should never happen.
    pub fn blocking_get(&mut self) -> PooledItem<T> {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;

        loop {
            try_recv_from_borrowed_and_panic_if_lost(ready, borrowed);

            match ready.pop_front() {
                Some(item) => {
                    let (tx, rx) = futures_channel::oneshot::channel();
                    borrowed.push(rx);
                    return PooledItem::new(item, tx);
                }
                None => std::thread::yield_now(),
            }
        }
    }

    /// Gets an item from the pool. If there is no item immediately available, the future
    /// will `.await` until one is available.
    ///
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// futures::executor::block_on(async {
    ///     let item = pool.get().await;
    /// });
    /// ```
    /// 
    /// # Panic
    ///
    /// This future will panic if any sender is dropped before the item is returned to the pool,
    /// which should never happen.
    pub fn get(&mut self) -> Get<'_, T> {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;
        Get { ready, borrowed }
    }

    /// Tries to pop an item from the pool. Returns `None` if there is no item immediately available.
    /// 
    /// Please note that if the sender is dropped before the item is returned to the pool, the
    /// item will be lost and this will be reflected on the pool's length.
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// assert_eq!(pool.len(), 1);
    /// 
    /// let item = pool.try_pop();
    /// assert!(item.is_some());
    /// assert_eq!(pool.len(), 0);
    /// ```
    pub fn try_pop(&mut self) -> Option<T> {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;
        try_recv_from_borrowed(ready, borrowed);
        self.ready.pop_front()
    }

    /// Pops an item from the pool. If there is no item immediately available, this will wait
    /// in a blocking manner until an item is available.
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// assert_eq!(pool.len(), 1);
    /// let item = pool.blocking_pop();
    /// assert_eq!(pool.len(), 0);
    /// ```
    /// 
    /// # Panic
    /// 
    /// This will panic if the sender is dropped before the item is returned to the pool, which
    /// should never happen.
    pub fn blocking_pop(&mut self) -> T {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;

        loop {
            try_recv_from_borrowed_and_panic_if_lost(ready, borrowed);

            match ready.pop_front() {
                Some(item) => return item,
                None => std::thread::yield_now(),
            }
        }
    }

    /// Pops an item from the pool. If there is no item immediately available, this will wait
    /// in a blocking manner until an item is available.
    /// 
    /// # Example
    /// 
    /// ```
    /// use piscina::Pool;
    /// 
    /// let mut pool = Pool::new();
    /// pool.put(1);
    /// assert_eq!(pool.len(), 1);
    /// futures::executor::block_on(async {
    ///    let item = pool.pop().await;
    ///    assert_eq!(pool.len(), 0);
    /// });
    /// ```
    /// 
    /// # Panic
    /// 
    /// This will panic if the sender is dropped before the item is returned to the pool, which
    /// should never happen.
    pub fn pop(&mut self) -> Pop<'_, T> {
        let ready = &mut self.ready;
        let borrowed = &mut self.borrowed;
        Pop { ready, borrowed }
    }
}

pin_project! {
    /// A future that resolves to a [`PooledItem`]
    ///
    /// # Panic
    ///
    /// This future will panic if the sender is dropped before the item is
    /// returned to the pool, which should never happen.
    pub struct Get<'a, T> {
        #[pin]
        ready: &'a mut VecDeque<T>,

        #[pin]
        borrowed: &'a mut Vec<Receiver<T>>,
    }
}

impl<'a, T> Future for Get<'a, T> {
    type Output = PooledItem<T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        let ready = &mut this.ready;
        let borrowed = &mut this.borrowed;

        poll_all_borrowed_and_push_back_ready(**ready, borrowed, cx);

        match ready.pop_front() {
            Some(item) => {
                let (tx, rx) = futures_channel::oneshot::channel();
                borrowed.push(rx);
                Poll::Ready(PooledItem::new(item, tx))
            }
            None => Poll::Pending,
        }
    }
}

pin_project! {
    /// A future that resolves to an item removed from the pool.
    /// 
    /// # Panic
    /// 
    /// This future will panic if the sender is dropped before the item is
    /// returned to the pool, which should never happen.
    #[derive(Debug)]
    pub struct Pop<'a, T> {
        #[pin]
        ready: &'a mut VecDeque<T>,

        #[pin]
        borrowed: &'a mut Vec<Receiver<T>>,
    }
}

impl<'a, T> Future for Pop<'a, T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        let ready = &mut this.ready;
        let borrowed = &mut this.borrowed;

        poll_all_borrowed_and_push_back_ready(**ready, borrowed, cx);

        match ready.pop_front() {
            Some(item) => Poll::Ready(item),
            None => Poll::Pending,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::*;

    #[test]
    fn create_pool() {
        let pool = Pool::<i32>::new();
        assert_eq!(pool.len(), 0);
    }

    #[test]
    fn create_pool_with_capacity() {
        let pool = Pool::<i32>::with_capacity(10);
        assert_eq!(pool.len(), 0);
    }

    #[test]
    fn pool_len_does_not_change_after_borrowing_item() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_eq!(pool.len(), 1);

        let item = assert_some!(pool.try_get());
        assert_eq!(pool.len(), 1);

        drop(item);
        assert_eq!(pool.len(), 1);
    }

    #[test]
    fn try_get_from_empty_pool_returns_none() {
        let mut pool = Pool::<i32>::new();
        assert_none!(pool.try_get());
    }

    #[test]
    fn try_get_from_non_empty_pool_returns_some() {
        let mut pool = Pool::<i32>::new();
        pool.put(1);
        assert_some!(pool.try_get());
    }

    #[test]
    fn try_get_from_exhausted_pool_returns_none() {
        let mut pool = Pool::new();
        pool.put(1);
        let _item = assert_some!(pool.try_get());
        assert_none!(pool.try_get());
    }

    #[test]
    fn try_get_after_dropping_borrowed_item_returns_some() {
        let mut pool = Pool::new();
        pool.put(1);
        let item = assert_some!(pool.try_get());
        drop(item);
        assert_some!(pool.try_get());
    }

    #[test]
    fn try_get_after_dropping_borrowed_item_and_putting_new_item_returns_some() {
        let mut pool = Pool::new();
        assert_none!(pool.try_get());

        pool.put(1);
        let item = assert_some!(pool.try_get());
        assert_none!(pool.try_get());

        drop(item);
        assert_some!(pool.try_get());

        pool.put(2);
        assert_some!(pool.try_get());
    }

    #[test]
    fn blocking_get_from_non_empty_pool_returns_item() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_eq!(*pool.blocking_get(), 1);
    }

    #[test]
    fn try_pop_from_empty_pool_returns_none() {
        let mut pool = Pool::<i32>::new();
        assert_none!(pool.try_pop());
    }

    #[test]
    fn try_pop_reduce_len_by_one() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_eq!(pool.len(), 1);
        assert_some!(pool.try_pop());
        assert_eq!(pool.len(), 0);
    }

    #[futures_test::test]
    async fn poll_get_from_empty_pool_returns_pending() {
        let mut pool = Pool::<i32>::new();
        assert_pending!(pool.get());
    }

    #[futures_test::test]
    async fn poll_get_from_pool_of_one_item_returns_ready() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_ready!(pool.get());
    }

    #[futures_test::test]
    async fn poll_get_from_exhausted_pool_returns_pending() {
        let mut pool = Pool::new();
        pool.put(1);
        let _item = assert_ready!(pool.get());
        assert_pending!(pool.get());
    }

    #[futures_test::test]
    async fn poll_get_after_dropping_borrowed_item_returns_ready() {
        let mut pool = Pool::new();
        pool.put(1);
        let item = assert_ready!(pool.get());
        drop(item);
        assert_ready!(pool.get());
    }

    #[futures_test::test]
    async fn poll_get_after_dropping_borrowed_item_and_putting_new_item_returns_ready() {
        let mut pool = Pool::new();
        assert_pending!(pool.get());

        pool.put(1);
        let item = assert_ready!(pool.get());
        assert_pending!(pool.get());

        drop(item);
        assert_ready!(pool.get());

        pool.put(2);
        assert_ready!(pool.get());
    }

    #[futures_test::test]
    async fn poll_pop_from_empty_pool_returns_pending() {
        let mut pool = Pool::<i32>::new();
        assert_pending!(pool.pop());
    }

    #[futures_test::test]
    async fn poll_pop_reduce_len_by_one() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_eq!(pool.len(), 1);
        assert_ready!(pool.pop());
        assert_eq!(pool.len(), 0);
    }

    #[futures_test::test]
    async fn poll_pop_from_pool_of_one_item_returns_ready() {
        let mut pool = Pool::new();
        pool.put(1);
        assert_ready!(pool.pop());
    }

    #[futures_test::test]
    async fn poll_pop_from_exhausted_pool_returns_pending() {
        let mut pool = Pool::new();
        pool.put(1);
        let _item = assert_ready!(pool.pop());
        assert_pending!(pool.pop());
    }

    #[futures_test::test]
    async fn poll_pop_after_dropping_borrowed_item_returns_ready() {
        let mut pool = Pool::new();
        pool.put(1);
        let item = assert_ready!(pool.get());
        drop(item);
        assert_ready!(pool.pop());
    }

    #[futures_test::test]
    async fn poll_pop_after_dropping_removed_item_returns_pending() {
        let mut pool = Pool::new();
        pool.put(1);
        let item = assert_ready!(pool.pop());
        drop(item);
        assert_pending!(pool.pop());
    }
}