slice_pool2\sync/
mod.rs

1//! Synchronized memory pools.
2
3pub use self::owned::{SliceBox, SlicePool, Sliceable};
4use std::sync::Mutex;
5use crate::Chunk;
6
7mod owned;
8
9enum Order {
10  Preceding,
11  Following,
12}
13
14/// A thread-safe chunk chain.
15struct ChunkChain(Mutex<Vec<Chunk>>);
16
17impl ChunkChain {
18  pub fn new(size: usize) -> Self {
19    ChunkChain(Mutex::new(vec![Chunk::new(size)]))
20  }
21
22  pub fn allocate(&self, size: usize) -> Option<Chunk> {
23    let mut chunks = self.0.lock().expect("poisoned chain");
24
25    // Find a chunk with the least amount of memory required
26    let (index, _) = chunks
27      .iter()
28      .enumerate()
29      .filter(|(_, chunk)| chunk.free && chunk.size >= size)
30      .min_by_key(|(_, chunk)| chunk.size)?;
31
32    // Determine whether there is any memory surplus
33    let delta = chunks[index].size - size;
34
35    if delta > 0 {
36      // Deduct the left over memory from the allocation
37      chunks[index].size -= delta;
38
39      // Insert a new chunk representing the surplus memory
40      let offset = chunks[index].offset + size;
41      chunks.insert(index + 1, Chunk::with_offset(delta, offset));
42    }
43    chunks[index].free = false;
44
45    Some(chunks[index])
46  }
47
48  pub fn release(&self, offset: usize) {
49    let mut chunks = self.0.lock().expect("poisoned chain");
50
51    let index = chunks
52      .binary_search_by_key(&offset, |chunk| chunk.offset)
53      .expect("releasing chunk");
54
55    let preceding_free = Self::has_free_adjacent(&chunks, index, Order::Preceding);
56    let following_free = Self::has_free_adjacent(&chunks, index, Order::Following);
57
58    if !preceding_free && !following_free {
59      // No free adjacent chunks, simply mark this one as free
60      chunks[index].free = true;
61    } else {
62      // Find range of free chunks.
63      let start = if preceding_free { index - 1 } else { index };
64      let end = if following_free { index + 1 } else { index };
65
66      // Merge the free chunks
67      chunks[start].free = true;
68      chunks[start].size += chunks.drain(start+1..=end).map(|c| c.size).sum::<usize>();
69    }
70  }
71
72  fn has_free_adjacent(chunks: &[Chunk], index: usize, order: Order) -> bool {
73    match order {
74      Order::Preceding => index > 0 && chunks[index - 1].free,
75      Order::Following => index + 1 < chunks.len() && chunks[index + 1].free,
76    }
77  }
78}