index_alloc 0.1.1

A toy static allocator wich can serve as a global_allocator.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! This module contains the [`Rc`] smart point capable of shared ownership of memory in a [`IndexAllocator`]

use core::cell::Cell;
use core::fmt::Debug;
use core::ops::Deref;

use crate::{IndexAllocator, IndexError};

/// A smart pointer holding it's value in a [`IndexAllocator`] and managing its memory.
/// It also keep track of the number of strong and weak references to the inner value.
struct RcBox<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize>
where
    T: ?Sized,
{
    pub val: Cell<Option<&'a T>>,
    pub strong: Cell<usize>,
    pub weak: Cell<usize>,
    allocator: &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE>,
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> RcBox<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    /// Allocate the inner type and set the strong and weak count to 0.
    fn try_new<U>(
        val: U,
        allocator: &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE>,
    ) -> Result<Self, IndexError>
    where
        U: 'a,
        &'a T: From<&'a U>,
    {
        let val_ref = unsafe { allocator.try_alloc_value(val)? };

        Ok(Self {
            val: Cell::new(Some(<&'a T>::from(&*val_ref))),
            strong: Cell::new(0),
            weak: Cell::new(0),
            allocator,
        })
    }

    /// Try to free the inner value and set it to None.
    /// Panic if the inner value is already freed. (Which shouldn't happen).
    fn try_free_inner(&self) -> Result<(), IndexError> {
        match self.val.get() {
            Some(v) => {
                unsafe {
                    self.allocator.try_free_value(v)?;
                }
                self.val.set(None);
                Ok(())
            }
            None => unreachable!(),
        }
    }

    fn increment_strong(&self) {
        self.strong.set(self.strong.get() + 1);
    }

    fn decrement_strong(&self) {
        self.strong.set(self.strong.get() - 1);
    }

    fn increment_weak(&self) {
        self.weak.set(self.weak.get() + 1);
    }

    fn decrement_weak(&self) {
        self.weak.set(self.weak.get() - 1);
    }

    /// Return the inner allocator used.
    fn allocator(&self) -> &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE> {
        self.allocator
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Drop
    for RcBox<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    /// Drop the inner value if not already done.
    fn drop(&mut self) {
        if let Some(v) = self.val.get() {
            unsafe {
                self.allocator.try_free_value(v).unwrap();
                self.val.set(None);
            }
        }
    }
}

/// A smart pointer holding its value in an [`IndexAllocator`] and allowing shared ownership between multiple [`Rc`].
///
/// The [`Rc`] smart pointer can be obtained by using [`Rc::try_new`].
///
/// # Example
///
/// ```
/// use index_alloc::IndexAllocator;
/// use index_alloc::rc::Rc;
///
/// let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();
///
/// let test_rc = Rc::try_new([1, 2, 3, 4], &allocator).unwrap();
/// assert_eq!(*test_rc, [1, 2, 3, 4]);
/// ```
pub struct Rc<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize>
where
    T: ?Sized,
{
    rc_box: &'a RcBox<'a, T, MEMORY_SIZE, INDEX_SIZE>,
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    /// Try to create a new [`Rc`] owning a value allocated of type `T` on a [`IndexAllocator`].
    /// The inner memory is reference counted and only freed when every strong reference ([`Rc`]) are dropped.
    ///
    /// # Errors
    /// The method return an [`IndexError`] if the allocation failed.
    pub fn try_new<U>(
        val: U,
        allocator: &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE>,
    ) -> Result<Self, IndexError>
    where
        U: 'a,
        &'a T: From<&'a U>,
    {
        let rc_box = RcBox::try_new(val, allocator)?;
        rc_box.increment_strong();

        let rc_box_ref = unsafe { allocator.try_alloc_value(rc_box)? };

        Ok(Self { rc_box: rc_box_ref })
    }

    /// Create a [`Weak`] reference to the value owned by the [`Rc`].
    pub fn downgrade(&self) -> Weak<'a, T, MEMORY_SIZE, INDEX_SIZE> {
        self.rc_box.increment_weak();
        Weak {
            rc_box: self.rc_box,
        }
    }

    /// Return the number of strong reference (see [`Rc`]) to the inner value.
    #[must_use]
    pub fn strong_count(&self) -> usize {
        self.rc_box.strong.get()
    }

    /// Return the number of weak reference (see [`Weak`]) to the inner value.
    #[must_use]
    pub fn weak_count(&self) -> usize {
        self.rc_box.weak.get()
    }

    /// Get a reference to the [`IndexAllocator`] used by the [`Rc`].
    #[must_use]
    pub fn allocator(&self) -> &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE> {
        self.rc_box.allocator()
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Clone
    for Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    /// Create a new [`Rc`] referencing to the same value.
    ///
    /// # Example
    ///
    /// ```
    /// use index_alloc::IndexAllocator;
    /// use index_alloc::rc::Rc;
    ///
    /// let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();
    ///
    /// let test_rc = Rc::try_new("Hello World", &allocator).unwrap();
    ///
    /// {
    ///     let test_ref = Rc::clone(&test_rc);
    ///     assert_eq!(*test_ref, "Hello World");
    /// }
    /// ```
    #[must_use]
    fn clone(&self) -> Self {
        self.rc_box.increment_strong();
        Self { ..*self }
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Deref
    for Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self.rc_box.val.get() {
            Some(v) => v,
            None => unreachable!(),
        }
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Debug
    for Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized + Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.rc_box.val.get().unwrap().fmt(f)
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Drop
    for Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    fn drop(&mut self) {
        self.rc_box.decrement_strong();
        // If the strong count get to 0, drop the inner value.
        if self.rc_box.strong.get() == 0 {
            self.rc_box.try_free_inner().unwrap();

            // If morover the weak count gets to 0, drop the inner box.
            if self.rc_box.weak.get() == 0 {
                unsafe {
                    self.allocator().try_free_value(self.rc_box).unwrap();
                }
            }
        }
    }
}

/// A smart pointer to a value in an [`Rc`] which doesn't hold the inner data.
/// As the inner data can be dropped when no more [`Rc`] are holding it,
/// a [`Weak`] reference can't directly access it's inner data and must be upgraded to an [`Rc`] with the [`Weak::upgrade`] method.
///
/// The [`Weak`] smart pointer can be obtained by using the [`Rc::downgrade`] method.
///
/// # Example
///
/// ```
/// use index_alloc::IndexAllocator;
/// use index_alloc::rc::Rc;
///
/// let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();
///
/// let test_rc = Rc::try_new([1, 2, 3, 4], &allocator).unwrap();
/// let test_ref = test_rc.downgrade();
/// assert_eq!(test_ref.strong_count(), 1);
/// ```
pub struct Weak<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize>
where
    T: ?Sized,
{
    rc_box: &'a RcBox<'a, T, MEMORY_SIZE, INDEX_SIZE>,
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Weak<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    /// Try to upgrade the [`Weak`] reference to a strong reference ([`Rc`]) return `None` if the inner_value was already dropped.
    #[must_use]
    pub fn upgrade(&self) -> Option<Rc<'a, T, MEMORY_SIZE, INDEX_SIZE>> {
        if self.strong_count() > 0 {
            self.rc_box.increment_strong();
            Some(Rc {
                rc_box: self.rc_box,
            })
        } else {
            None
        }
    }

    /// Return the number of strong reference (see [`Rc`]) to the inner value.
    #[must_use]
    pub fn strong_count(&self) -> usize {
        self.rc_box.strong.get()
    }

    /// Return the number of weak reference (see [`Weak`]) to the inner value.
    #[must_use]
    pub fn weak_count(&self) -> usize {
        self.rc_box.weak.get()
    }

    /// Get a reference to the [`IndexAllocator`] used by the [`Weak`] reference.
    #[must_use]
    pub fn allocator(&self) -> &'a IndexAllocator<MEMORY_SIZE, INDEX_SIZE> {
        self.rc_box.allocator
    }
}
impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Clone
    for Weak<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    fn clone(&self) -> Self {
        self.rc_box.increment_weak();
        Self { ..*self }
    }
}

impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Debug
    for Weak<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "(Weak)")
    }
}
impl<'a, T, const MEMORY_SIZE: usize, const INDEX_SIZE: usize> Drop
    for Weak<'a, T, MEMORY_SIZE, INDEX_SIZE>
where
    T: ?Sized,
{
    fn drop(&mut self) {
        self.rc_box.decrement_weak();

        // If no more reference (strong or weak), drop the inner box.
        if self.rc_box.strong.get() == 0 && self.rc_box.weak.get() == 0 {
            unsafe {
                self.allocator().try_free_value(self.rc_box).unwrap();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::index::MemoryRegion;

    use super::*;

    #[test]
    fn test_rc_allocation() {
        let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();

        let test_rc = Rc::try_new([1u8, 2, 3, 4], &allocator).unwrap();

        assert_eq!(*test_rc, [1, 2, 3, 4]);

        drop(test_rc);

        assert_eq!(
            allocator.index.borrow().get_region(0),
            Ok(&MemoryRegion::new(0, 64, false))
        );
    }

    #[test]
    fn test_rc_counting() {
        let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();

        let test_rc = Rc::try_new("Hello world", &allocator).unwrap();

        assert_eq!(test_rc.strong_count(), 1);

        {
            let rc_clone = Rc::clone(&test_rc);

            assert_eq!(rc_clone.strong_count(), 2);
        }

        assert_eq!(test_rc.strong_count(), 1);
        assert_eq!(*test_rc, "Hello world");
    }

    #[test]
    fn test_weak_counting() {
        let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();

        let test_rc = Rc::try_new("Hello World", &allocator).unwrap();
        let test_weak = test_rc.downgrade();

        assert_eq!(test_rc.strong_count(), 1);
        assert_eq!(test_rc.weak_count(), 1);
        assert_eq!(test_weak.strong_count(), 1);
        assert_eq!(test_weak.weak_count(), 1);

        {
            let second_rc = test_weak.upgrade().unwrap();
            assert_eq!(second_rc.weak_count(), 1);
            assert_eq!(second_rc.strong_count(), 2);
        }

        assert_eq!(test_rc.strong_count(), 1);
    }

    #[test]
    fn test_weak_on_dropped_value() {
        let allocator: IndexAllocator<64, 8> = IndexAllocator::empty();

        let test_rc = Rc::try_new("Hello World", &allocator).unwrap();
        let test_weak = test_rc.downgrade();

        drop(test_rc);

        assert_eq!(test_weak.strong_count(), 0);
        assert!(matches!(test_weak.upgrade(), None));

        drop(test_weak);

        assert_eq!(
            allocator.index.borrow().get_region(0),
            Ok(&MemoryRegion::new(0, 64, false))
        );
    }
}