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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::fmt::{Debug, Error, Formatter};
use std::mem::MaybeUninit;

use crate::counter::Counter;
use crate::pointer::Pointer;
use crate::refbox::RefBox;
use crate::stack::Stack;
use crate::types::{ElementPointer, PoolPointer};

unsafe fn init_box<A>(ref_box: *mut RefBox<A>, pool: Pool<A>) {
    let count_ptr: *mut _ = &mut (*(ref_box)).count;
    let pool_ptr: *mut _ = &mut (*(ref_box)).pool;
    count_ptr.write(Default::default());
    pool_ptr.write(pool);
}

/// A pool of preallocated memory sized to match type `A`.
///
/// In order to use it to allocate objects, pass it to
/// [`PoolRef::new()`][PoolRef::new] or [`PoolRef::default()`][PoolRef::default].
///
/// # Example
///
/// ```rust
/// # use refpool::{Pool, PoolRef};
/// let mut pool: Pool<usize> = Pool::new(1024);
/// let pool_ref = PoolRef::new(&mut pool, 31337);
/// assert_eq!(31337, *pool_ref);
/// ```
///
/// [PoolRef::new]: struct.PoolRef.html#method.new
/// [PoolRef::default]: struct.PoolRef.html#method.default

pub struct Pool<A> {
    inner: PoolPointer<A>,
}

impl<A> Pool<A> {
    /// Construct a new pool with a given max size and return a handle to it.
    ///
    /// Values constructed via the pool will be returned to the pool when
    /// dropped, up to `max_size`. When the pool is full, values will be dropped
    /// in the regular way.
    ///
    /// If `max_size` is `0`, meaning the pool can never hold any dropped
    /// values, this method will give you back a null handle without allocating
    /// a pool. You can still use this to construct `PoolRef` values, they'll
    /// just allocate in the old fashioned way without using a pool. It is
    /// therefore advisable to use a zero size pool as a null value instead of
    /// `Option<Pool>`, which eliminates the need for unwrapping the `Option`
    /// value.
    pub fn new(max_size: usize) -> Self {
        if max_size == 0 {
            Self {
                inner: PoolPointer::null(),
            }
        } else {
            Box::new(PoolInner::new(max_size)).into_ref()
        }
    }

    pub(crate) fn push(&self, value: ElementPointer<A>) {
        debug_assert!(self.inner.get_ptr_checked().is_some());
        unsafe { (*self.inner.get_ptr()).push(value) }
    }

    pub(crate) fn pop(&self) -> Box<MaybeUninit<RefBox<A>>> {
        let mut obj = if let Some(inner) = self.inner.get_ptr_checked() {
            unsafe { (*inner).pop() }
        } else {
            None
        }
        .unwrap_or_else(|| Box::new(MaybeUninit::uninit()));
        unsafe { init_box(obj.as_mut_ptr(), self.clone()) };
        obj
    }

    fn deref(&self) -> Option<&PoolInner<A>> {
        self.inner.get_ptr_checked().map(|p| unsafe { &*p })
    }

    /// Get the maximum size of the pool.
    pub fn get_max_size(&self) -> usize {
        self.deref().map(|p| p.get_max_size()).unwrap_or(0)
    }

    /// Get the current size of the pool.
    pub fn get_pool_size(&self) -> usize {
        self.deref().map(|p| p.get_pool_size()).unwrap_or(0)
    }

    /// Test if the pool is currently full.
    pub fn is_full(&self) -> bool {
        self.deref()
            .map(|p| p.get_pool_size() >= p.get_max_size())
            .unwrap_or(true)
    }

    /// Fill the pool with empty allocations.
    ///
    /// This operation will pre-allocate `self.get_max_size() -
    /// self.get_pool_size()` memory chunks, without initialisation, and put
    /// them in the pool.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use refpool::{Pool, PoolRef};
    /// let pool: Pool<usize> = Pool::new(1024);
    /// assert_eq!(0, pool.get_pool_size());
    /// pool.fill();
    /// assert_eq!(1024, pool.get_pool_size());
    /// ```
    pub fn fill(&self) {
        if let Some(inner) = self.deref() {
            while inner.get_max_size() > inner.get_pool_size() {
                let chunk = unsafe {
                    std::alloc::alloc(std::alloc::Layout::from_size_align_unchecked(
                        std::mem::size_of::<RefBox<A>>(),
                        std::mem::align_of::<RefBox<A>>(),
                    ))
                };
                self.push(ElementPointer::wrap(chunk.cast()));
            }
        }
    }

    /// Convert a pool handle for type `A` into a handle for type `B`.
    ///
    /// The types `A` and `B` must have the same size and alignment, as
    /// per [`std::mem::size_of`][size_of] and
    /// [`std::mem::align_of`][align_of], or this method will panic.
    ///
    /// This lets you use the same pool to construct values of different
    /// types, as long as they are of the same size and alignment, so
    /// they can reuse each others' memory allocations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use refpool::{Pool, PoolRef};
    /// # use std::convert::TryInto;
    /// let u64_pool: Pool<u64> = Pool::new(1024);
    /// let u64_number = PoolRef::new(&u64_pool, 1337);
    ///
    /// let i64_pool: Pool<i64> = u64_pool.cast();
    /// let i64_number = PoolRef::new(&i64_pool, -1337);
    /// # assert_eq!(i64_number.abs().try_into(), Ok(*u64_number));
    /// ```
    ///
    /// [size_of]: https://doc.rust-lang.org/std/mem/fn.size_of.html
    /// [align_of]: https://doc.rust-lang.org/std/mem/fn.align_of.html
    pub fn cast<B>(&self) -> Pool<B> {
        assert!(std::mem::size_of::<A>() == std::mem::size_of::<B>());
        assert!(std::mem::align_of::<A>() == std::mem::align_of::<B>());

        if let Some(ptr) = self.inner.get_ptr_checked() {
            let inner: *mut PoolInner<B> = ptr.cast();
            unsafe { (*inner).make_ref() }
        } else {
            Pool::new(0)
        }
    }
}

impl<A> Clone for Pool<A> {
    fn clone(&self) -> Self {
        if let Some(inner) = self.inner.get_ptr_checked() {
            unsafe { (*inner).make_ref() }
        } else {
            Self::new(0)
        }
    }
}

impl<A> Drop for Pool<A> {
    fn drop(&mut self) {
        if let Some(ptr) = self.inner.get_ptr_checked() {
            if unsafe { (*ptr).dec() } == 1 {
                std::mem::drop(unsafe { Box::from_raw(ptr) });
            }
        }
    }
}

impl<A> Debug for Pool<A> {
    /// Debug implementation for `Pool`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use refpool::Pool;
    /// let mut pool: Pool<usize> = Pool::new(256);
    /// assert!(format!("{:?}", pool).starts_with("Pool[0/256]:0x"));
    /// pool.fill();
    /// assert!(format!("{:?}", pool).starts_with("Pool[256/256]:0x"));
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(
            f,
            "Pool[{}/{}]:{:p}",
            self.get_pool_size(),
            self.get_max_size(),
            self.inner
        )
    }
}

pub(crate) struct PoolInner<A> {
    count: usize,
    max_size: usize,
    stack: Vec<ElementPointer<A>>,
}

impl<A> PoolInner<A> {
    fn new(max_size: usize) -> Self {
        Self {
            count: Default::default(),
            max_size,
            stack: Stack::stack_new(max_size),
        }
    }

    fn into_ref(mut self: Box<Self>) -> Pool<A> {
        self.inc();
        Pool {
            inner: PoolPointer::wrap(Box::into_raw(self)),
        }
    }

    fn make_ref(&mut self) -> Pool<A> {
        self.inc();
        Pool {
            inner: PoolPointer::wrap(self),
        }
    }

    /// Get the maximum size of the pool.
    fn get_max_size(&self) -> usize {
        self.max_size
    }

    /// Get the current size of the pool.
    fn get_pool_size(&self) -> usize {
        self.stack.stack_len()
    }

    #[inline(always)]
    fn inc(&mut self) {
        self.count.inc();
    }

    #[inline(always)]
    fn dec(&mut self) -> usize {
        self.count.dec()
    }

    fn pop(&mut self) -> Option<Box<MaybeUninit<RefBox<A>>>> {
        self.stack.stack_pop().map(|value_ptr| {
            let box_ptr = value_ptr.cast::<MaybeUninit<RefBox<A>>>();
            unsafe { Box::from_raw(box_ptr.as_ptr()) }
        })
    }

    fn push(&mut self, handle: ElementPointer<A>) {
        self.stack.stack_push(handle);
    }
}

impl<A> Drop for PoolInner<A> {
    fn drop(&mut self) {
        while let Some(chunk) = self.stack.stack_pop() {
            unsafe {
                std::alloc::dealloc(
                    chunk.as_ptr().cast(),
                    std::alloc::Layout::from_size_align_unchecked(
                        std::mem::size_of::<RefBox<A>>(),
                        std::mem::align_of::<RefBox<A>>(),
                    ),
                );
            }
        }
    }
}