array_pool 0.1.3

A simple, tiered caching array pool implementation in Rust.
Documentation
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
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};
use std::mem::swap;
use std::ops::{Deref, DerefMut};
use std::ptr::drop_in_place;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::thread;
use std::thread::ThreadId;

use crate::raw_buffer::RawBuffer;
use thread_local::ThreadLocal;

struct LocalBufferChain<T> {
    chunk_linked_list: Mutex<Vec<RawBuffer<T>>>,
    chunk_count: Arc<AtomicUsize>
}

struct BufferChain<T: Send>{
    chunk_size: usize,
    chunk_count: Arc<AtomicUsize>,
    chains: Mutex<BTreeMap<u64, Weak<LocalBufferChain<T>>>>,
    local_chain: ThreadLocal<Arc<LocalBufferChain<T>>>
}

/// Represent a borrowed array.
pub struct BorrowingSlice<T: Send>{
    array: RawBuffer<T>,
    chain: Arc<BufferChain<T>>,
    pub(crate) initialized: bool,
}

impl<T> Drop for LocalBufferChain<T>{
    fn drop(&mut self) {
        let locked = self.chunk_linked_list.lock().unwrap();
        let len = locked.len();
        self.chunk_count.fetch_sub(len, Ordering::SeqCst);
    }
}

impl<T> LocalBufferChain<T>{
    pub unsafe fn borrow(self: &Arc<Self>) -> Option<RawBuffer<T>>{
        let mut lock_guard = self.chunk_linked_list.lock().unwrap();
        if let Some(slice) = lock_guard.pop() {
            self.chunk_count.fetch_sub(1, Ordering::SeqCst);
            Some(slice)
        } else { None }
    }
}

/// Provides a resource pool that enables reusing instances of type `T`.
pub struct ArrayPool<T: Send> {
    empty_chain: Arc<BufferChain<T>>,
    chunk_map: BTreeMap<usize, Arc<BufferChain<T>>>
}

impl<T: Send> BufferChain<T>{
    /// Create a new buffer chain with specified power.
    pub fn new(size_power: u8) -> Arc<Self> {
        Arc::new(Self {
            chunk_size: 1usize << size_power,
            chunk_count: Arc::new(AtomicUsize::default()),
            chains: Mutex::new(BTreeMap::new()),
            local_chain: ThreadLocal::new(),
        })
    }

    fn new_array<F: FnMut() -> T>(&self, fabricator: &mut F) -> RawBuffer<T> {
        unsafe {
            let mut buffer = RawBuffer::<T>::new(self.chunk_size, false);
            let length = buffer.len();
            let reference = buffer.get_ref_mut();
            for i in 0..length{
                // Avoid dropping the old, invalid value
                std::ptr::write(&mut reference[i], fabricator());
            }

            buffer
        }
    }

    fn get_local(&self) -> &Arc<LocalBufferChain<T>> {
        let arc_count = self.chunk_count.clone();
        self.local_chain.get_or(move ||{
            let arc = Arc::new(LocalBufferChain {
                chunk_linked_list: Mutex::new(vec![]),
                chunk_count: arc_count,
            });
            let mut lock_guard = self.chains.lock().unwrap();
            let tid = thread::current().id();
            lock_guard.insert(unsafe { *(&tid as *const ThreadId as *const u64) }, Arc::downgrade(&arc));

            arc
        })
    }

    fn borrow_from_other_chains(&self) -> Option<RawBuffer<T>> {
        let mut lock_guard = self.chains.lock().unwrap();
        let mut remove_queue: Vec<u64> = Vec::new();
        let mut found: Option<RawBuffer<T>> = None;

        for (id, chain_weak) in lock_guard.iter() {
            if let Some(chain) = chain_weak.upgrade() {
                if let Some(cached) = unsafe{ chain.borrow() }{
                    found = Some(cached);
                    break;
                }
            } else {
                remove_queue.push(*id);
            }
        }

        for id in &remove_queue {
            lock_guard.remove(id);
        }

        found
    }

    /// Rent a new array.
    ///
    /// If none is available for renting, create a new one with each element
    /// initialized by `fabricator`.
    pub fn rent_with<F: FnMut() -> T>(self: &Arc<Self>, fabricator: &mut F) -> BorrowingSlice<T> {
        let local_chain = self.get_local();
        let array;
        if self.chunk_count.load(Ordering::Acquire) == 0 {
            array = self.new_array(fabricator);
        } else if let Some(cached) = unsafe{ local_chain.borrow() }{
            array = cached;
        } else if let Some(cached) = self.borrow_from_other_chains() {
            array = cached
        } else {
            array = self.new_array(fabricator);
        }
        BorrowingSlice{
            array,
            chain: self.clone(),
            initialized: true,
        }
    }

    /// Create a new uninitialized array. Zero the array if needed.
    pub(crate) unsafe fn new_uninitialized(&self, zeroed: bool) -> RawBuffer<T> {
        RawBuffer::new(self.chunk_size, zeroed)
    }

    /// Rent a new array.
    ///
    /// If none is available for renting, create a new one without initialize it,
    /// zero if needed.
    pub unsafe fn rent_or_create_uninitialized(self: &Arc<Self>, zeroed: bool) -> BorrowingSlice<T>{
        let local_chain = self.get_local();
        let array;
        if self.chunk_count.load(Ordering::Acquire) == 0 {
            array = self.new_uninitialized(zeroed);
        } else if let Some(cached) = local_chain.borrow(){
            array = cached;
        } else if let Some(cached) = self.borrow_from_other_chains() {
            array = cached
        } else {
            array = self.new_uninitialized(zeroed);
        }
        BorrowingSlice{
            array,
            chain: self.clone(),
            initialized: false,
        }
    }
}

impl<T: Send> Drop for BorrowingSlice<T>{
    fn drop(&mut self) {
        if self.array.is_empty() { return; }
        if self.initialized {
            unsafe {
                for i in 0..self.len() {
                    let elem = &mut self[i];
                    drop_in_place(elem);
                }
            }
        }
        let mut lock_guard = self.chain.get_local().chunk_linked_list.lock().unwrap();
        let mut store = RawBuffer::<T>::empty();
        swap(&mut store, &mut self.array);
        lock_guard.push(store);
        self.chain.chunk_count.fetch_add(1, Ordering::SeqCst);
    }
}

impl<T: Send> Deref for BorrowingSlice<T>{
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        self.array.deref()
    }
}
impl<T: Send> DerefMut for BorrowingSlice<T>{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.array.deref_mut()
    }
}

impl<T: Send + Display> Display for BorrowingSlice<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[ ")?;

        let mut insert_colon = false;

        for x in self.iter() {
            if insert_colon{
                write!(f, ", ")?;
            }
            write!(f, "{x}")?;
            insert_colon = true;
        }

        write!(f, " ]")?;
        Ok(())
    }
}

impl<T: Send + Clone> Clone for BorrowingSlice<T> {
    fn clone(&self) -> Self {
        let mut new_buffer: RawBuffer<T>;
        unsafe {
            new_buffer = match self.chain.get_local().borrow(){
                Some(v) => v,
                None => self.chain.new_uninitialized(false)
            };
            for i in 0..self.len(){
                // ptr contain uninitialized value
                std::ptr::write(&mut new_buffer[i], self[i].clone());
            }
        }


        Self{
            array: new_buffer,
            chain: self.chain.clone(),
            initialized: true,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum ArrayPoolError {
    MaxPowerTooSmall,
    MaxChunkSizeNotSufficient
}

impl<T: Send> ArrayPool<T>{
    /// Create a new `ArrayPool` with `max_power`.
    ///
    /// `max_power` determine how many size variants does a pool have.
    /// A `max_power` of x will create arrays with length 2^n (3 <= n < x).
    pub fn with_max_power(max_power: u8) -> Result<Self, ArrayPoolError> {
        let mut map: BTreeMap<usize, Arc<BufferChain<T>>> = BTreeMap::new();
        if max_power < 4 { return Err(ArrayPoolError::MaxPowerTooSmall); }
        for x in 3..max_power {
            map.insert(1usize << x, BufferChain::new(x));
        }
        Ok(Self {
            empty_chain: BufferChain::new(0),
            chunk_map: map
        })
    }

    /// Create a new `ArrayPool` with `max_power` of `target_pointer_width - 1`.
    pub fn new() -> Self {
        #[cfg(target_pointer_width = "64")]{
            return Self::with_max_power(63).unwrap();
        }

        #[cfg(target_pointer_width = "32")]{
            return Self::with_max_power(31).unwrap();
        }
    }

    fn get_chain(&self, minimum_capacity: usize) -> Option<&Arc<BufferChain<T>>>{
        for (size, chunk_chain) in &self.chunk_map {
            if minimum_capacity <= *size {
                return Some(chunk_chain);
            }
        }

        None
    }

    /// Rent a new array with `minimum_capacity`.
    ///
    /// If no cached array was found, create a new one with each element
    /// initialized by `fabricator`.
    pub fn rent_with<F: FnMut() -> T>(&self, minimum_capacity: usize, fabricator: &mut F) -> Result<BorrowingSlice<T>, ArrayPoolError> {
        if let Some(chunk_chain) = self.get_chain(minimum_capacity){
            return Ok(chunk_chain.rent_with(fabricator));
        }

        Err(ArrayPoolError::MaxChunkSizeNotSufficient)
    }

    /// Rent a new array with `minimum_capacity`.
    ///
    /// If no cached array was found, create a new one without initializing it,
    /// zero if needed.
    pub unsafe fn rent_or_create_uninitialized(&self, minimum_capacity: usize, zeroed: bool) -> Result<BorrowingSlice<T>, ArrayPoolError> {
        if let Some(chunk_chain) = self.get_chain(minimum_capacity){
            return Ok(chunk_chain.rent_or_create_uninitialized(zeroed));
        }

        Err(ArrayPoolError::MaxChunkSizeNotSufficient)
    }

    /// Rent an array with the smallest supported capacity.
    ///
    /// If no cached array was found, create a new one with each element
    /// initialized by `fabricator`.
    pub fn rent_minimum_with<F: FnMut() -> T>(&self, fabricator: &mut F) -> Result<BorrowingSlice<T>, ArrayPoolError>{
        for (_, chunk_chain) in &self.chunk_map {
            return Ok(chunk_chain.rent_with(fabricator));
        }

        Err(ArrayPoolError::MaxChunkSizeNotSufficient)
    }

    /// Rent an array with the smallest supported capacity.
    ///
    /// If no cached array was found, create a new one without initializing it,
    /// zero if needed.
    pub unsafe fn rent_or_create_minimum_uninitialized(&self, zeroed: bool) -> Result<BorrowingSlice<T>, ArrayPoolError> {
        for (_, chunk_chain) in &self.chunk_map {
            return Ok(chunk_chain.rent_or_create_uninitialized(zeroed));
        }

        Err(ArrayPoolError::MaxChunkSizeNotSufficient)
    }

    /// Double the capacity of `old_buffer`. New slots won't be initialized.
    pub unsafe fn expand_buffer(&self, mut old_buffer: BorrowingSlice<T>) -> Result<BorrowingSlice<T>, ArrayPoolError> {
        let old_size = old_buffer.len();
        let new_size = old_size * 2;
        if let Ok(mut new_buffer) = unsafe {self.rent_or_create_uninitialized(new_size, false)} {
            for i in 0..old_size {
                swap(&mut old_buffer[i], &mut new_buffer[i]);
            }

            old_buffer.initialized = false;
            drop(old_buffer);
            Ok(new_buffer)
        } else { Err(ArrayPoolError::MaxChunkSizeNotSufficient) }
    }

    /// Halve the capacity of `old_buffer`. Old slots won't be dropped.
    pub unsafe fn shrink_buffer(&self, mut old_buffer: BorrowingSlice<T>) -> BorrowingSlice<T> {
        let old_size = old_buffer.len();
        let new_size = old_size / 2;

        if let Ok(mut new_buffer) = unsafe {self.rent_or_create_uninitialized(new_size, false)} {
            for i in 0..new_size {
                swap(&mut old_buffer[i], &mut new_buffer[i]);
            }

            old_buffer.initialized = false;
            drop(old_buffer);
            new_buffer
        } else {
            old_buffer
        }
    }

    /// Rent an empty array.
    pub fn rent_empty(&self) -> BorrowingSlice<T> {
        BorrowingSlice{
            array: RawBuffer::empty(),
            chain: self.empty_chain.clone(),
            initialized: true,
        }
    }

    /// Gets the smallest supported capacity.
    pub fn min_size(&self) -> usize {
        *self.chunk_map.first_key_value().unwrap().0
    }

    /// Gets the largest supported capacity.
    pub fn max_size(&self) -> usize {
        *self.chunk_map.last_key_value().unwrap().0
    }
}

impl<T: Default + Send> ArrayPool<T>{
    /// Rent a new array with `minimum_capacity`.
    ///
    /// If no cached array was found, create a new one with each element
    /// initialized by the default constructor.
    pub fn rent(&self, minimum_capacity: usize) -> Result<BorrowingSlice<T>, ArrayPoolError> {
        self.rent_with(minimum_capacity, &mut T::default)
    }

    /// Rent an array with the smallest supported capacity.
    ///
    /// If no cached array was found, create a new one with each element
    /// initialized by the default constructor.
    pub fn rent_minimum(&self) -> Result<BorrowingSlice<T>, ArrayPoolError>{
        self.rent_minimum_with(&mut T::default)
    }
}