cranpose_core/collections/
growth_slack.rs1use 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
14pub trait GrowthSlack {
16 fn trim_growth_slack(&mut self);
19}
20
21impl<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 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}