shrink_fit_wrapper

Crates.ioshrink_fit_wrapper
lib.rsshrink_fit_wrapper
version1.0.0
created_at2025-10-23 09:05:10.73603+00
updated_at2025-10-23 09:05:10.73603+00
description"shrink_to_fit" on any "mut"
homepage
repositoryhttps://github.com/tonymushah/shrink_fit_wrapper
max_upload_size
id1896831
size9,916
Dirk Tony (tonymushah)

documentation

README

shrink_fit_wrapper

An extremely simple, "idiomatic" shrink_to_fit on any mut.

Why making this crate?

If you didn't know, std::collections reallocate themselves when you want to add an item in it but the initial/current capacity cannot hold up.

However, they don't reallocate when you remove item(s) which can often causes "memory leaks" problem(s) when you use them as global state.

This crate allow you to do that: shrink_to_fit on any [std::collections] "mut".

How to use?

  1. Install this crate into your project.

  2. Wrap any [Vec] or [HashMap] with the [ShrinkFitWrapper] struct:

use shrink_fit_wrapper::ShrinkFitWrapper;

let mut my_vec = ShrinkFitWrapper::new(Vec::<u32>::with_capacity(3));

// You can also put `shrink_to_fit` period with it.
// let mut my_vec = ShrinkFitWrapper::new(Vec::<u32>::with_capacity(3)).set_shrink_duration_cycle(Duration::from_secs(2));

// use `.as_mut()` to borrow it mutably.
my_vec.as_mut().push(2);

// wait and shrink fit at another time.
// std::thread::sleep(Duration::from_secs(2));
// drop(my_vec.as_mut());

// Checking if the length correspond to the capacity
// assert_eq!(my_vec.len(), my_vec.capacity());

Note: It is worth noting that by setting a shrink_duration_cycle, the wrapper doesn't periodically shrink_to_fit the underlying container at that duration. See ShrinkFitWrapperMutGuard::drop implementation.

License

MIT

Commit count: 0

cargo fmt