cesium_allocator/
lib.rs

1pub mod allocator;
2
3use std::{
4    collections::BTreeMap,
5    sync::Arc,
6};
7
8use cesium_libmimalloc_sys::heap::mi_heap_new;
9
10use crate::allocator::Allocator;
11
12/// A pool of general allocators.
13pub struct AllocatorPool {
14    lowest_id: u32,
15    heaps: BTreeMap<u32, Arc<Allocator>>,
16}
17
18impl AllocatorPool {
19    /// Create a new pool for allocators.
20    pub fn new() -> Self {
21        AllocatorPool {
22            lowest_id: 0,
23            heaps: BTreeMap::new(),
24        }
25    }
26
27    /// Create a new allocator
28    pub fn new_allocator(&mut self) -> Arc<Allocator> {
29        let heap = unsafe { mi_heap_new() };
30        let id = self.lowest_id + 1;
31        self.lowest_id = id;
32
33        let alloc = Arc::new(Allocator::new(id, heap));
34        self.heaps.insert(id, alloc.clone());
35
36        alloc
37    }
38
39    /// Gets or creates an allocator
40    pub fn get_allocator(&mut self, id: u32, create: Option<bool>) -> Option<Arc<Allocator>> {
41        match self.heaps.get(&id) {
42            | None => match create {
43                | None => None,
44                | Some(_) => Some(self.new_allocator()),
45            },
46            | Some(v) => Some(v.clone()),
47        }
48    }
49}