Use mem::take shorthand for defaulted replace

This makes the code more readable by shortening lines and avoid explicit
or redundant type annotations. The core function would require a rust
version of 1.40 so straightforward implementation is added to the crate.
This commit is contained in:
Andreas Molzer
2020-01-18 16:10:12 +01:00
parent eed51be53b
commit 381eacaa46
2 changed files with 9 additions and 6 deletions
+4 -6
View File
@@ -343,8 +343,7 @@ impl<A: Array> ArrayVec<A> {
pub fn pop(&mut self) -> Option<A::Item> {
if self.len > 0 {
self.len -= 1;
let out =
replace(&mut self.data.as_slice_mut()[self.len], A::Item::default());
let out = take(&mut self.data.as_slice_mut()[self.len]);
Some(out)
} else {
None
@@ -759,8 +758,7 @@ impl<A: Array> Iterator for ArrayVecIterator<A> {
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.base < self.len {
let out =
replace(&mut self.data.as_slice_mut()[self.base], A::Item::default());
let out = take(&mut self.data.as_slice_mut()[self.base]);
self.base += 1;
Some(out)
} else {
@@ -779,13 +777,13 @@ impl<A: Array> Iterator for ArrayVecIterator<A> {
}
#[inline]
fn last(mut self) -> Option<Self::Item> {
Some(replace(&mut self.data.as_slice_mut()[self.len], A::Item::default()))
Some(take(&mut self.data.as_slice_mut()[self.len]))
}
#[inline]
fn nth(&mut self, n: usize) -> Option<A::Item> {
let i = self.base + (n - 1);
if i < self.len {
let out = replace(&mut self.data.as_slice_mut()[i], A::Item::default());
let out = take(&mut self.data.as_slice_mut()[i]);
self.base = i + 1;
Some(out)
} else {
+5
View File
@@ -84,3 +84,8 @@ pub use arrayvec::*;
mod tinyvec;
#[cfg(feature = "alloc")]
pub use tinyvec::*;
// Replace with mem::take as soon as MSRV allows it
fn take<T: Default>(from: &mut T) -> T {
replace(from, T::default())
}