byte_pool/
poolable.rs

1use std::collections::HashMap;
2use std::hash::{BuildHasher, Hash};
3
4/// The trait required to be able to use a type in `BytePool`.
5pub trait Poolable {
6    fn capacity(&self) -> usize;
7    fn alloc(size: usize) -> Self;
8}
9
10impl<T: Default + Clone> Poolable for Vec<T> {
11    fn capacity(&self) -> usize {
12        self.len()
13    }
14
15    fn alloc(size: usize) -> Self {
16        vec![T::default(); size]
17    }
18}
19
20impl<K, V, S> Poolable for HashMap<K, V, S>
21where
22    K: Eq + Hash,
23    S: BuildHasher + Default,
24{
25    fn capacity(&self) -> usize {
26        self.len()
27    }
28
29    fn alloc(size: usize) -> Self {
30        HashMap::with_capacity_and_hasher(size, Default::default())
31    }
32}
33
34/// A trait allowing for efficient reallocation.
35pub trait Realloc {
36    fn realloc(&mut self, new_size: usize);
37}
38
39impl<T: Default + Clone> Realloc for Vec<T> {
40    fn realloc(&mut self, new_size: usize) {
41        use std::cmp::Ordering::*;
42
43        assert!(new_size > 0);
44        match new_size.cmp(&self.len()) {
45            Greater => {
46                self.reserve_exact(new_size - self.len());
47                debug_assert_eq!(self.capacity(), new_size);
48                self.resize(new_size, T::default());
49                debug_assert_eq!(self.len(), new_size);
50
51                // Check that resize() did not reserve additional space.
52                debug_assert_eq!(self.capacity(), new_size);
53            }
54            Less => {
55                self.truncate(new_size);
56                debug_assert_eq!(self.len(), new_size);
57                self.shrink_to_fit();
58                debug_assert_eq!(self.capacity(), new_size);
59            }
60            Equal => {}
61        }
62    }
63}
64
65impl<K, V, S> Realloc for HashMap<K, V, S>
66where
67    K: Eq + Hash,
68    S: BuildHasher,
69{
70    fn realloc(&mut self, new_size: usize) {
71        use std::cmp::Ordering::*;
72
73        assert!(new_size > 0);
74        match new_size.cmp(&self.capacity()) {
75            Greater => {
76                let current = self.capacity();
77                let diff = new_size - current;
78                self.reserve(diff);
79            }
80            Less => {
81                self.shrink_to_fit();
82            }
83            Equal => {}
84        }
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    /// Regression test for `Realloc` trait implementation of `Vec`.
93    ///
94    /// Previously `Realloc::realloc()` called `self.capacity()` instead
95    /// of `self.len()` when checking whether the vector should be expanded.
96    /// As a result, it sometimes attempted to shrink the vector
97    /// when it should be expanded, and effectively did nothing.
98    #[test]
99    fn realloc_vec() {
100        let mut v: Vec<u8> = Poolable::alloc(100);
101
102        for i in 1..100 {
103            let new_size = Poolable::capacity(&v) + i;
104            v.realloc(new_size);
105            assert_eq!(Poolable::capacity(&v), new_size);
106
107            // Length of the vectory and underlying buffer
108            // for poolable vectors should
109            // be exactly of the requested size.
110            assert_eq!(v.len(), new_size);
111            assert_eq!(v.capacity(), new_size);
112        }
113    }
114}