Skip to content

Commit

Permalink
Auto merge of #54 - Vurich:master, r=mbrubeck
Browse files Browse the repository at this point in the history
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 -->
  • Loading branch information
bors-servo authored Jun 28, 2017
2 parents 0627339 + 226730c commit 2549c2a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,36 @@ impl<T> VecLike<T> for Vec<T> {
}
}

/// Trait to be implemented by a collection that can be extended from a slice
///
/// ## Example
///
/// ```rust
/// use smallvec::{ExtendFromSlice, SmallVec8};
///
/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
/// v.extend_from_slice(b"Test!");
/// }
///
/// let mut vec = Vec::new();
/// initialize(&mut vec);
/// assert_eq!(&vec, b"Test!");
///
/// let mut small_vec = SmallVec8::new();
/// initialize(&mut small_vec);
/// assert_eq!(&small_vec as &[_], b"Test!");
/// ```
pub trait ExtendFromSlice<T>: VecLike<T> {
/// Extends a collection from a slice of its element type
fn extend_from_slice(&mut self, other: &[T]);
}

impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
fn extend_from_slice(&mut self, other: &[T]) {
Vec::extend_from_slice(self, other)
}
}

unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) {
let _vec: Vec<T> = Vec::from_raw_parts(ptr, 0, capacity);
// Let it drop.
Expand Down Expand Up @@ -686,6 +716,11 @@ impl_index!(ops::RangeFrom<usize>, [A::Item]);
impl_index!(ops::RangeTo<usize>, [A::Item]);
impl_index!(ops::RangeFull, [A::Item]);

impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A> where A::Item: Copy {
fn extend_from_slice(&mut self, other: &[A::Item]) {
SmallVec::extend_from_slice(self, other)
}
}

impl<A: Array> VecLike<A::Item> for SmallVec<A> {
#[inline]
Expand Down

0 comments on commit 2549c2a

Please sign in to comment.