Skip to content

Add into_inner #115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 13, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,8 @@ impl<A: Array> SmallVecData<A> {
SmallVecData { inline }
}
#[inline]
unsafe fn into_inline(self) -> A { self.inline }
#[inline]
unsafe fn heap(&self) -> (*mut A::Item, usize) {
self.heap
}
Expand Down Expand Up @@ -327,6 +329,13 @@ impl<A: Array> SmallVecData<A> {
SmallVecData::Inline(ManuallyDrop::new(inline))
}
#[inline]
unsafe fn into_inline(self) -> A {
match self {
SmallVecData::Inline(a) => ManuallyDrop::into_inner(a),
_ => debug_unreachable!(),
}
}
#[inline]
unsafe fn heap(&self) -> (*mut A::Item, usize) {
match *self {
SmallVecData::Heap(data) => data,
Expand Down Expand Up @@ -812,6 +821,22 @@ impl<A: Array> SmallVec<A> {
}
}

/// Convert the SmallVec into an `A` if possible. Otherwise return `Err(Self)`.
///
/// This method returns `Err(Self)` if the SmallVec is too short (and the `A` contains uninitialized elements),
/// or if the SmallVec is too long (and all the elements were spilled to the heap).
pub fn into_inner(self) -> Result<A, Self> {
if self.spilled() || self.len() != A::size() {
Err(self)
} else {
unsafe {
let data = ptr::read(&self.data);
mem::forget(self);
Ok(data.into_inline())
}
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns `false`.
Expand Down Expand Up @@ -1945,6 +1970,18 @@ mod tests {
assert_eq!(vec.into_vec(), vec![0, 1, 2]);
}

#[test]
fn test_into_inner() {
let vec = SmallVec::<[u8; 2]>::from_iter(0..2);
assert_eq!(vec.into_inner(), Ok([0, 1]));

let vec = SmallVec::<[u8; 2]>::from_iter(0..1);
assert_eq!(vec.clone().into_inner(), Err(vec));

let vec = SmallVec::<[u8; 2]>::from_iter(0..3);
assert_eq!(vec.clone().into_inner(), Err(vec));
}

#[test]
fn test_from_vec() {
let vec = vec![];
Expand Down