pub fn compact<T: IsEmpty>(values: &mut Vec<T>)Expand description
🚮 Compacts a mutable vector by removing all elements that are considered “empty”.
This function iterates through the vector and retains only those elements
for which the is_empty() method returns false.
§Type Parameters
T: The type of elements in the vector. Must implement theIsEmptytrait.
§Arguments
values: A mutable reference to theVec<T>to be compacted.
§Behavior
- Modifies the input vector in-place, removing elements for which
is_empty()is true. - If the vector is initially empty, it remains empty.
- If all elements are empty, the result is an empty vector.
- If no elements are empty, the vector remains unchanged.
§Performance
- Runs in O(n) time, where
nis the number of elements. - Uses
Vec::retain()under the hood — efficient, no reallocations. - Each element is checked once. For types where
is_empty()is O(1), overall cost is linear and very fast.
§Supported Types
This function works with any type that implements the IsEmpty trait, such as:
String,&str- All integers and floats (
0,0.0are “empty”) bool(falseis “empty”)Vec<T>whereT: IsEmptyOption<T>whereT: IsEmpty
§Examples
§📜 Remove empty strings
use pencil_box::array::compact::compact;
use pencil_box::traits::IsEmpty;
let mut items = vec!["hello".to_string(), "".to_string(), "world".to_string()];
compact(&mut items);
assert_eq!(items, vec!["hello", "world"]);§📦 Remove empty vectors
let mut data = vec![vec![1], vec![], vec![2, 3]];
compact(&mut data);
assert_eq!(data, vec![vec![1], vec![2, 3]]);§🧹 Remove zero values
let mut nums = vec![0, 1, 0, 2, 3];
compact(&mut nums);
assert_eq!(nums, vec![1, 2, 3]);§❓ Remove None and empty Somes
let mut opts = vec![Some("hi"), None, Some("")];
compact(&mut opts);
assert_eq!(opts, vec![Some("hi")]);§🔍 Leave non-empty values untouched
let mut flags = vec![true, true, true];
compact(&mut flags);
assert_eq!(flags, vec![true, true, true]);§📭 No-op on empty input
let mut empty: Vec<String> = vec![];
compact(&mut empty);
assert!(empty.is_empty());