Skip to content

Commit 2549c2a

Browse files
author
bors-servo
authored
Auto merge of #54 - Vurich:master, r=mbrubeck
Add ExtendFromSlice trait At Parity we tried to switch from our internal `elastic-array` crate (which has soundness and ergonomics issues) to `smallvec` but the PR that attempted this replaced `extend_from_slice` calls with `push` loops (which are much slower). We could fix this internally, but the discussion around it made me wonder if this would be something that could be useful upstream. <!-- 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/54) <!-- Reviewable:end -->
2 parents 0627339 + 226730c commit 2549c2a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lib.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,36 @@ impl<T> VecLike<T> for Vec<T> {
8888
}
8989
}
9090

91+
/// Trait to be implemented by a collection that can be extended from a slice
92+
///
93+
/// ## Example
94+
///
95+
/// ```rust
96+
/// use smallvec::{ExtendFromSlice, SmallVec8};
97+
///
98+
/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
99+
/// v.extend_from_slice(b"Test!");
100+
/// }
101+
///
102+
/// let mut vec = Vec::new();
103+
/// initialize(&mut vec);
104+
/// assert_eq!(&vec, b"Test!");
105+
///
106+
/// let mut small_vec = SmallVec8::new();
107+
/// initialize(&mut small_vec);
108+
/// assert_eq!(&small_vec as &[_], b"Test!");
109+
/// ```
110+
pub trait ExtendFromSlice<T>: VecLike<T> {
111+
/// Extends a collection from a slice of its element type
112+
fn extend_from_slice(&mut self, other: &[T]);
113+
}
114+
115+
impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
116+
fn extend_from_slice(&mut self, other: &[T]) {
117+
Vec::extend_from_slice(self, other)
118+
}
119+
}
120+
91121
unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) {
92122
let _vec: Vec<T> = Vec::from_raw_parts(ptr, 0, capacity);
93123
// Let it drop.
@@ -686,6 +716,11 @@ impl_index!(ops::RangeFrom<usize>, [A::Item]);
686716
impl_index!(ops::RangeTo<usize>, [A::Item]);
687717
impl_index!(ops::RangeFull, [A::Item]);
688718

719+
impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A> where A::Item: Copy {
720+
fn extend_from_slice(&mut self, other: &[A::Item]) {
721+
SmallVec::extend_from_slice(self, other)
722+
}
723+
}
689724

690725
impl<A: Array> VecLike<A::Item> for SmallVec<A> {
691726
#[inline]

0 commit comments

Comments
 (0)