Skip to main content

kaspa_utils/
vec.rs

1use alloc::vec::Vec;
2
3pub trait VecExtensions<T> {
4    /// Pushes the provided value to the container if the container is empty
5    fn push_if_empty(self, value: T) -> Self;
6
7    /// Inserts the provided `value` at `index` while swapping the item at index to the end of the container
8    fn swap_insert(&mut self, index: usize, value: T);
9
10    /// Merges two containers one into the other and returns the result. The method is identical
11    /// to [`Vec<T>::append`] but can be used more ergonomically in a fluent calling fashion
12    fn merge(self, other: Self) -> Self;
13}
14
15impl<T> VecExtensions<T> for Vec<T> {
16    fn push_if_empty(mut self, value: T) -> Self {
17        if self.is_empty() {
18            self.push(value);
19        }
20        self
21    }
22
23    fn swap_insert(&mut self, index: usize, value: T) {
24        self.push(value);
25        let loc = self.len() - 1;
26        self.swap(index, loc);
27    }
28
29    fn merge(mut self, mut other: Self) -> Self {
30        self.append(&mut other);
31        self
32    }
33}