use std::cmp::max;
pub trait ExcessShrink {
fn shrink(len: usize, excess: usize) -> ShrinkResult;
}
pub struct DefaultExcessShrink;
impl ExcessShrink for DefaultExcessShrink {
#[inline]
fn shrink(len: usize, excess: usize) -> ShrinkResult {
if excess < 96 + 1 {
ShrinkResult::do_not_shrink()
} else if len < 1024 {
ShrinkResult::shrink_with_remaining_excess(48)
} else if len < 1024 * 4 + 1 {
if excess > 256 {
ShrinkResult::shrink_with_remaining_excess(64)
} else {
ShrinkResult::do_not_shrink()
}
} else if len < 1024 * 32 + 1 {
if excess > 1024 {
ShrinkResult::shrink_with_remaining_excess(128)
} else {
ShrinkResult::do_not_shrink()
}
} else if excess > 1024 * 4 + 1 {
ShrinkResult::shrink_with_remaining_excess(256)
} else {
ShrinkResult::do_not_shrink()
}
}
}
pub struct NeverShrink;
impl ExcessShrink for NeverShrink {
fn shrink(_len: usize, _capacity: usize) -> ShrinkResult {
ShrinkResult::do_not_shrink()
}
}
#[derive(Debug, Copy, Clone)]
pub struct ShrinkResult(u32);
impl ShrinkResult {
#[inline]
pub fn do_not_shrink() -> Self {
Self(core::u32::MAX)
}
#[inline]
pub fn shrink_with_remaining_excess(remaining_excess: u16) -> Self {
Self(remaining_excess as u32)
}
#[inline]
fn do_shrink(self) -> bool {
self.0 != core::u32::MAX
}
}
#[inline]
pub fn maybe_shrink<T: ExcessShrink>(vec: &mut Vec<u8>, never_below_excess: usize) -> bool {
let len = vec.len();
let capacity = vec.capacity();
let excess = capacity - len;
let result = T::shrink(len, excess);
if result.do_shrink() {
let excess_to_keep = result.0 as usize;
let excess_to_keep = max(excess_to_keep, never_below_excess);
if excess > excess_to_keep {
unsafe {
vec.set_len(len + excess_to_keep);
}
vec.shrink_to_fit();
unsafe {
vec.set_len(len);
}
true
} else {
false
}
} else {
false
}
}