Skip to content

Commit 0edafd3

Browse files
committed
Add resize_with
1 parent a541e2d commit 0edafd3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

lib.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,6 +1093,48 @@ impl<A: Array> SmallVec<A> {
10931093
self.dedup_by(|a, b| key(a) == key(b));
10941094
}
10951095

1096+
/// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1097+
///
1098+
/// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each
1099+
/// additional slot filled with the result of calling the closure `f`. The return values from `f`
1100+
//// will end up in the `SmallVec` in the order they have been generated.
1101+
///
1102+
/// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1103+
///
1104+
/// This method uses a closure to create new values on every push. If you'd rather `Clone` a given
1105+
/// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass
1106+
/// `Default::default()` as the second argument.
1107+
///
1108+
/// Added for std::vec::Vec compatibility (added in Rust 1.33.0)
1109+
///
1110+
/// ```
1111+
/// # use smallvec::{smallvec, SmallVec};
1112+
/// let mut vec : SmallVec<[_; 4]> = smallvec![1, 2, 3];
1113+
/// vec.resize_with(5, Default::default);
1114+
/// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1115+
///
1116+
/// let mut vec : SmallVec<[_; 4]> = smallvec![];
1117+
/// let mut p = 1;
1118+
/// vec.resize_with(4, || { p *= 2; p });
1119+
/// assert_eq!(&*vec, &[2, 4, 8, 16]);
1120+
/// ```
1121+
pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1122+
where
1123+
F: FnMut() -> A::Item,
1124+
{
1125+
let old_len = self.len();
1126+
if old_len < new_len {
1127+
let mut f = f;
1128+
let additional = new_len - old_len;
1129+
self.reserve(additional);
1130+
for _ in 0..additional {
1131+
self.push(f());
1132+
}
1133+
} else if old_len > new_len {
1134+
self.truncate(new_len);
1135+
}
1136+
}
1137+
10961138
/// Creates a `SmallVec` directly from the raw components of another
10971139
/// `SmallVec`.
10981140
///

0 commit comments

Comments
 (0)