Skip to content

Commit 46396e8

Browse files
committed
add Vec::push_within_capacity - fallible, does not allocate
1 parent 75b7e52 commit 46396e8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

library/alloc/src/vec/mod.rs

+44
Original file line numberDiff line numberDiff line change
@@ -1773,6 +1773,50 @@ impl<T, A: Allocator> Vec<T, A> {
17731773
}
17741774
}
17751775

1776+
/// Appends an element if there is sufficient spare capacity, otherwise the element is returned.
1777+
///
1778+
/// Unlike [`push`] method will not reallocate when there's insufficient capacity.
1779+
/// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
1780+
///
1781+
/// [`push`]: Vec::push
1782+
/// [`reserve`]: Vec::reserve
1783+
/// [`try_reserve`]: Vec::try_reserve
1784+
///
1785+
/// # Examples
1786+
///
1787+
/// A manual, panic-free alternative to FromIterator
1788+
///
1789+
/// ```
1790+
/// #![feature(vec_push_within_capacity, try_reserve)]
1791+
///
1792+
/// use std::collections::TryReserveError;
1793+
/// fn from_iter<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
1794+
/// let mut vec = Vec::new();
1795+
/// for value in iter {
1796+
/// if let Err(value) = vec.push_within_capacity(value) {
1797+
/// vec.try_reserve(1)?;
1798+
/// // this cannot fail, the previous line either returned or added at least 1 free slot
1799+
/// let _ = vec.push_within_capacity(value);
1800+
/// }
1801+
/// }
1802+
/// Ok(vec)
1803+
/// }
1804+
/// # from_iter(0..100).expect("please insert more memory");
1805+
/// ```
1806+
#[inline]
1807+
#[unstable(feature = "vec_push_within_capacity", issue = "none")]
1808+
pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
1809+
if self.len == self.buf.capacity() {
1810+
return Err(value);
1811+
}
1812+
unsafe {
1813+
let end = self.as_mut_ptr().add(self.len);
1814+
ptr::write(end, value);
1815+
self.len += 1;
1816+
}
1817+
Ok(())
1818+
}
1819+
17761820
/// Removes the last element from a vector and returns it, or [`None`] if it
17771821
/// is empty.
17781822
///

0 commit comments

Comments
 (0)