|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! Extensions to [`Vec`] for fallible allocations. |
| 4 | +
|
| 5 | +use alloc::{collections::TryReserveError, vec::Vec}; |
| 6 | +use core::result::Result; |
| 7 | + |
| 8 | +/// Extensions to [`Vec`]. |
| 9 | +pub trait VecExt<T>: Sized { |
| 10 | + /// Creates a new [`Vec`] instance with at least the given capacity. |
| 11 | + fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError>; |
| 12 | + |
| 13 | + /// Appends an element to the back of the [`Vec`] instance. |
| 14 | + fn try_push(&mut self, v: T) -> Result<(), TryReserveError>; |
| 15 | + |
| 16 | + /// Pushes clones of the elements of slice into the [`Vec`] instance. |
| 17 | + fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 18 | + where |
| 19 | + T: Clone; |
| 20 | +} |
| 21 | + |
| 22 | +impl<T> VecExt<T> for Vec<T> { |
| 23 | + fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> { |
| 24 | + let mut v = Vec::new(); |
| 25 | + v.try_reserve(capacity)?; |
| 26 | + Ok(v) |
| 27 | + } |
| 28 | + |
| 29 | + fn try_push(&mut self, v: T) -> Result<(), TryReserveError> { |
| 30 | + if let Err(retry) = self.push_within_capacity(v) { |
| 31 | + self.try_reserve(1)?; |
| 32 | + let _ = self.push_within_capacity(retry); |
| 33 | + } |
| 34 | + Ok(()) |
| 35 | + } |
| 36 | + |
| 37 | + fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 38 | + where |
| 39 | + T: Clone, |
| 40 | + { |
| 41 | + self.try_reserve(other.len())?; |
| 42 | + for item in other { |
| 43 | + self.try_push(item.clone())?; |
| 44 | + } |
| 45 | + |
| 46 | + Ok(()) |
| 47 | + } |
| 48 | +} |
0 commit comments