Skip to content

Commit 0be8bb0

Browse files
author
bors-servo
authored
Auto merge of #84 - mbrubeck:resize, r=jdm
Add resize method Fixes #82. <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/rust-smallvec/84) <!-- Reviewable:end -->
2 parents 5758c25 + 5bacafa commit 0be8bb0

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

lib.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use std::borrow::{Borrow, BorrowMut};
3939
use std::cmp;
4040
use std::fmt;
4141
use std::hash::{Hash, Hasher};
42-
use std::iter::{IntoIterator, FromIterator};
42+
use std::iter::{IntoIterator, FromIterator, repeat};
4343
use std::mem;
4444
use std::ops;
4545
use std::ptr;
@@ -731,6 +731,24 @@ impl<A: Array> SmallVec<A> where A::Item: Copy {
731731
}
732732
}
733733

734+
impl<A: Array> SmallVec<A> where A::Item: Clone {
735+
/// Resizes the vector so that its length is equal to `len`.
736+
///
737+
/// If `len` is less than the current length, the vector simply truncated.
738+
///
739+
/// If `len` is greater than the current length, `value` is appended to the
740+
/// vector until its length equals `len`.
741+
pub fn resize(&mut self, len: usize, value: A::Item) {
742+
let old_len = self.len();
743+
744+
if len > old_len {
745+
self.extend(repeat(value).take(len - old_len));
746+
} else {
747+
self.truncate(len);
748+
}
749+
}
750+
}
751+
734752
impl<A: Array> ops::Deref for SmallVec<A> {
735753
type Target = [A::Item];
736754
#[inline]
@@ -1733,6 +1751,17 @@ mod tests {
17331751
assert_eq!(no_dupes.len(), 5);
17341752
}
17351753

1754+
#[test]
1755+
fn test_resize() {
1756+
let mut v: SmallVec<[i32; 8]> = SmallVec::new();
1757+
v.push(1);
1758+
v.resize(5, 0);
1759+
assert_eq!(v[..], [1, 0, 0, 0, 0][..]);
1760+
1761+
v.resize(2, -1);
1762+
assert_eq!(v[..], [1, 0][..]);
1763+
}
1764+
17361765
#[cfg(feature = "std")]
17371766
#[test]
17381767
fn test_write() {

0 commit comments

Comments
 (0)