alloc-singleton 0.1.0

Memory allocators backed by singletons that own statically allocated memory
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
//! Fixed size memory pool

use core::{fmt, marker::PhantomData, mem, ops, ptr, u8};

use as_slice::{AsMutSlice, AsSlice};
use owned_singleton::Singleton;
use stable_deref_trait::StableDeref;

/// A value allocated on the memory pool `Pool<M>`
///
/// - `sizeof(Box<_>)` is a single byte
/// - `Box<M>` implements `Send` if it derefs to a type `T` that implements `Send`
/// - `Box<M>` implements `Sync` if it derefs to a type `T` that implements `Sync`
pub struct Box<M>
where
    M: Singleton,
{
    _memory: PhantomData<M>,
    _not_send_or_sync: PhantomData<*const ()>,
    index: u8,
}

impl<T, M> ops::Deref for Box<M>
where
    M: Singleton,
    M::Type: AsSlice<Element = T>,
{
    type Target = T;

    fn deref(&self) -> &T {
        unsafe {
            (*M::get())
                .as_slice()
                .get_unchecked(usize::from(self.index))
        }
    }
}

impl<T, M> ops::DerefMut for Box<M>
where
    M: Singleton,
    M::Type: AsMutSlice<Element = T>,
{
    fn deref_mut(&mut self) -> &mut T {
        unsafe {
            (*M::get())
                .as_mut_slice()
                .get_unchecked_mut(usize::from(self.index))
        }
    }
}

unsafe impl<T, M> StableDeref for Box<M>
where
    M: Singleton,
    M::Type: AsMutSlice<Element = T>,
{
}

impl<T, M> fmt::Debug for Box<M>
where
    M: Singleton,
    M::Type: AsSlice<Element = T>,
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        T::fmt(&**self, f)
    }
}

impl<T, M> fmt::Display for Box<M>
where
    M: Singleton,
    M::Type: AsSlice<Element = T>,
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        T::fmt(&**self, f)
    }
}

unsafe impl<T, M> Send for Box<M>
where
    M: Singleton,
    M::Type: AsSlice<Element = T>,
    T: Send,
{
}

unsafe impl<T, M> Sync for Box<M>
where
    M: Singleton,
    M::Type: AsSlice<Element = T>,
    T: Sync,
{
}

/// A fixed-size memory pool backed by the memory chunk behind the owned singleton `M`
///
/// # Example
///
/// ```
/// use alloc_singleton::stable::pool::{Box, Pool};
/// use owned_singleton::Singleton;
///
/// #[Singleton]
/// static mut M: [[u8; 128]; 4] = [[0; 128]; 4];
///
/// let mut pool = Pool::new(unsafe { M::new() });
///
/// let buffer: Box<M> = pool.alloc([0; 128]).ok().unwrap();
///
/// // ..
///
/// // return the memory to the pool or the memory will be leaked
/// pool.dealloc(buffer);
/// ```
pub struct Pool<M>
where
    M: Singleton,
{
    free: u8,
    head: u8,
    initialized: u8,
    memory: M,
}

impl<T, A, M> Pool<M>
where
    M: Singleton<Type = A> + ops::DerefMut<Target = A>,
    A: AsMutSlice<Element = T>,
{
    /// Creates a memory pool that allocates on the given `memory` chunk
    ///
    /// The resulting `Pool` is semantically a singleton: there can only exist a single instead of
    /// `Pool<#M>` for any concrete `#M`
    ///
    /// *NOTE*: `Pool` will have a maximum capacity of 25**5** elements, even if `M::Type` has a
    /// bigger capacity.
    ///
    /// # Panics
    ///
    /// This constructor panics if `sizeof(M::Type::Element)` is a zero. In other words, `Pool`
    /// doesn't support ZST.
    #[allow(unused_variables)]
    pub fn new(memory: M) -> Self {
        assert!(mem::size_of::<T>() > 0);

        let capacity = memory.as_slice().len();

        Pool {
            free: if capacity > usize::from(u8::MAX) {
                u8::MAX
            } else {
                capacity as u8
            },
            head: 0,
            initialized: 0,
            memory,
        }
    }

    /// Allocates the given `value` on the memory pool
    ///
    /// # Errors
    ///
    /// If the memory pool has been exhausted an error containing `value` is returned
    pub fn alloc(&mut self, value: T) -> Result<Box<M>, T> {
        unsafe {
            let n = self.memory.as_slice().len() as u8;

            if self.initialized < n {
                let index = self.initialized;

                let p: *mut T = self
                    .memory
                    .as_mut_slice()
                    .get_unchecked_mut(usize::from(index));

                // the memory (`M`) starts initialized; we have to deinitialize it before we
                // overwrite its contents
                ptr::drop_in_place(p);

                *(p as *mut u8) = index + 1;
                self.initialized += 1;
            }

            if self.free != 0 {
                let index = self.head;
                let p = self
                    .memory
                    .as_mut_slice()
                    .as_mut_ptr()
                    .add(usize::from(index));
                self.head = *(p as *const u8);

                self.free -= 1;

                ptr::write(p, value);

                Ok(Box {
                    _memory: PhantomData,
                    _not_send_or_sync: PhantomData,
                    index,
                })
            } else {
                Err(value)
            }
        }
    }

    /// Deallocates the given `value` and returns the memory to the pool
    ///
    /// *NOTE*: `M::Type::Element`'s destructor (if any) will run on `value`
    pub fn dealloc(&mut self, value: Box<M>) {
        unsafe {
            let p: *mut T = self
                .memory
                .as_mut_slice()
                .get_unchecked_mut(value.index as usize);

            ptr::drop_in_place(p);

            *(p as *mut u8) = self.head;

            self.free += 1;
            self.head = value.index;
        }
    }
}

#[cfg(test)]
mod tests {
    use core::sync::atomic::{AtomicUsize, Ordering};

    use owned_singleton::Singleton;

    use super::Pool;

    #[test]
    fn sanity() {
        #[Singleton]
        static mut M: [i8; 4] = [0; 4];

        let mut pool = Pool::new(unsafe { M::new() });

        let _0 = pool.alloc(-1).unwrap();
        assert_eq!(*_0, -1);
        assert_eq!(_0.index, 0);
        assert_eq!(pool.head, 1);
        assert_eq!(pool.free, 3);
        assert_eq!(pool.initialized, 1);

        let _1 = pool.alloc(-2).unwrap();
        assert_eq!(*_1, -2);
        assert_eq!(_1.index, 1);
        assert_eq!(pool.head, 2);
        assert_eq!(pool.free, 2);
        assert_eq!(pool.initialized, 2);

        let _2 = pool.alloc(-3).unwrap();
        assert_eq!(*_2, -3);
        assert_eq!(_2.index, 2);
        assert_eq!(pool.head, 3);
        assert_eq!(pool.free, 1);
        assert_eq!(pool.initialized, 3);

        pool.dealloc(_0);
        assert_eq!(pool.head, 0);
        assert_eq!(pool.free, 2);
        assert_eq!(pool.initialized, 3);
        assert_eq!(unsafe { (*M::get())[0] }, 3);

        pool.dealloc(_2);
        assert_eq!(pool.head, 2);
        assert_eq!(pool.free, 3);
        assert_eq!(pool.initialized, 3);
        assert_eq!(unsafe { (*M::get())[2] }, 0);

        let _2 = pool.alloc(-4).unwrap();
        assert_eq!(*_2, -4);
        assert_eq!(_2.index, 2);
        assert_eq!(pool.head, 0);
        assert_eq!(pool.free, 2);
        assert_eq!(pool.initialized, 4);
        assert_eq!(unsafe { (*M::get())[3] }, 4);
    }

    // test that deallocated values are dropped
    #[test]
    fn destructor() {
        static COUNT: AtomicUsize = AtomicUsize::new(1);

        pub struct A(u32);

        impl A {
            fn new() -> Self {
                COUNT.fetch_add(1, Ordering::SeqCst);
                A(0)
            }
        }

        impl Drop for A {
            fn drop(&mut self) {
                COUNT.fetch_sub(1, Ordering::SeqCst);
            }
        }

        #[Singleton]
        static mut M: [A; 4] = [A(0), A(1), A(2), A(3)];

        {
            let mut pool = Pool::new(unsafe { M::new() });

            let _0 = pool.alloc(A::new()).ok().unwrap();
            assert_eq!(COUNT.load(Ordering::SeqCst), 1);

            // Deallocating the `Box` should run `A`'s destructor
            pool.dealloc(_0);
            assert_eq!(COUNT.load(Ordering::SeqCst), 0);
        }

        assert_eq!(COUNT.load(Ordering::SeqCst), 0);
    }

    // test that not explicitly deallocated values are leaked
    #[test]
    fn leak() {
        static COUNT: AtomicUsize = AtomicUsize::new(1);

        pub struct A(u32);

        impl A {
            fn new() -> Self {
                COUNT.fetch_add(1, Ordering::SeqCst);
                A(0)
            }
        }

        impl Drop for A {
            fn drop(&mut self) {
                COUNT.fetch_sub(1, Ordering::SeqCst);
            }
        }

        #[Singleton]
        static mut M: [A; 4] = [A(0), A(1), A(2), A(3)];

        {
            let mut pool = Pool::new(unsafe { M::new() });

            let _0 = pool.alloc(A::new()).ok().unwrap();
            assert_eq!(COUNT.load(Ordering::SeqCst), 1);

            // destroying the object does NOT invoke `A`'s destructor
            drop(_0);

            assert_eq!(COUNT.load(Ordering::SeqCst), 1);

            let _1 = pool.alloc(A::new()).ok().unwrap();
            assert_eq!(COUNT.load(Ordering::SeqCst), 1);

            drop(_1);

            assert_eq!(COUNT.load(Ordering::SeqCst), 1);

            // destroying the object pool does NOT invoke `A`'s destructor
            drop(pool);
        }

        assert_eq!(COUNT.load(Ordering::SeqCst), 1);
    }

    // test that exhausting the pool and then deallocating works correctly
    #[test]
    fn empty() {
        #[Singleton]
        static mut M: [i8; 4] = [0; 4];

        let mut pool = Pool::new(unsafe { M::new() });

        let _0 = pool.alloc(-1).unwrap();
        let _1 = pool.alloc(-1).unwrap();
        let _2 = pool.alloc(-1).unwrap();
        let _3 = pool.alloc(-1).unwrap();

        assert!(pool.alloc(-1).is_err());

        pool.dealloc(_0);
        pool.dealloc(_2);

        let _2 = pool.alloc(-1).unwrap();
        assert_eq!(_2.index, 2);

        let _0 = pool.alloc(-1).unwrap();
        assert_eq!(_0.index, 0);
    }

    #[test]
    fn max_capacity() {
        #[Singleton]
        static mut M: [i8; 256] = [0; 256];

        let mut pool = Pool::new(unsafe { M::new() });

        for _ in 0..255 {
            assert!(pool.alloc(-1).is_ok());
        }

        assert!(pool.alloc(-1).is_err());
    }
}