diff options
| author | The8472 <git@infinite-source.de> | 2021-09-20 20:22:14 +0200 |
|---|---|---|
| committer | The 8472 <git@infinite-source.de> | 2022-08-13 10:57:22 +0200 |
| commit | 46396e847d56037cbbf31dfccccbc0b45332af74 (patch) | |
| tree | d9bbf925e897b5e395b0039b35430550d6c3bf7f /library/alloc/src/vec/mod.rs | |
| parent | 75b7e52e92c3b00fc891b47f5b2efdff0a2be55a (diff) | |
| download | rust-46396e847d56037cbbf31dfccccbc0b45332af74.tar.gz rust-46396e847d56037cbbf31dfccccbc0b45332af74.zip | |
add Vec::push_within_capacity - fallible, does not allocate
Diffstat (limited to 'library/alloc/src/vec/mod.rs')
| -rw-r--r-- | library/alloc/src/vec/mod.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index fa9f2131c0c..1dccb053f90 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1773,6 +1773,50 @@ impl<T, A: Allocator> Vec<T, A> { } } + /// Appends an element if there is sufficient spare capacity, otherwise the element is returned. + /// + /// Unlike [`push`] method will not reallocate when there's insufficient capacity. + /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. + /// + /// [`push`]: Vec::push + /// [`reserve`]: Vec::reserve + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Examples + /// + /// A manual, panic-free alternative to FromIterator + /// + /// ``` + /// #![feature(vec_push_within_capacity, try_reserve)] + /// + /// use std::collections::TryReserveError; + /// fn from_iter<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> { + /// let mut vec = Vec::new(); + /// for value in iter { + /// if let Err(value) = vec.push_within_capacity(value) { + /// vec.try_reserve(1)?; + /// // this cannot fail, the previous line either returned or added at least 1 free slot + /// let _ = vec.push_within_capacity(value); + /// } + /// } + /// Ok(vec) + /// } + /// # from_iter(0..100).expect("please insert more memory"); + /// ``` + #[inline] + #[unstable(feature = "vec_push_within_capacity", issue = "none")] + pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> { + if self.len == self.buf.capacity() { + return Err(value); + } + unsafe { + let end = self.as_mut_ptr().add(self.len); + ptr::write(end, value); + self.len += 1; + } + Ok(()) + } + /// Removes the last element from a vector and returns it, or [`None`] if it /// is empty. /// |
