Skip to main content

cranpose_core/collections/
growth_slack.rs

1//! Giving back the room a collection's growth left past its items: a
2//! collection that lives as long as a screen and doubled to take one more
3//! item would keep room for as many again.
4
5use std::hash::{BuildHasher, Hash};
6
7const MIN_TRIMMED_SLACK: usize = 16;
8
9fn slack_target(len: usize, capacity: usize) -> Option<usize> {
10    let slack = capacity.saturating_sub(len);
11    (slack > (len / 4).max(MIN_TRIMMED_SLACK)).then_some(len + len / 8)
12}
13
14/// A collection that can give back the room its growth left past its items.
15pub trait GrowthSlack {
16    /// Gives back the room past the items once it is more than a quarter of
17    /// them, and 16 at least, down to an eighth of them.
18    fn trim_growth_slack(&mut self);
19}
20
21// The trims run out of line: one copy for each collection type serves every
22// collection of it.
23impl<T> GrowthSlack for Vec<T> {
24    #[inline(never)]
25    fn trim_growth_slack(&mut self) {
26        if let Some(target) = slack_target(self.len(), self.capacity()) {
27            self.shrink_to(target);
28        }
29    }
30}
31
32#[expect(
33    clippy::disallowed_types,
34    reason = "every hash map trims alike, whatever it hashes with"
35)]
36impl<K: Eq + Hash, V, S: BuildHasher> GrowthSlack for std::collections::HashMap<K, V, S> {
37    #[inline(never)]
38    fn trim_growth_slack(&mut self) {
39        // A map rounds its buckets up to a power of two, which leaves room
40        // past the items: asked for room past them, it may keep twice that.
41        if slack_target(self.len(), self.capacity()).is_some() {
42            self.shrink_to(self.len());
43        }
44    }
45}
46
47#[expect(
48    clippy::disallowed_types,
49    reason = "every hash set trims alike, whatever it hashes with"
50)]
51impl<T: Eq + Hash, S: BuildHasher> GrowthSlack for std::collections::HashSet<T, S> {
52    #[inline(never)]
53    fn trim_growth_slack(&mut self) {
54        if slack_target(self.len(), self.capacity()).is_some() {
55            self.shrink_to(self.len());
56        }
57    }
58}