From 16a2f5e28cee39a206d96e15480eceb881ece1bb Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Wed, 22 Dec 2021 23:06:57 +0100 Subject: [PATCH] feat: Vec::try_with_capacity(_in) --- library/alloc/src/raw_vec.rs | 14 ++++++++++++++ library/alloc/src/vec/mod.rs | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 3d38e73305a37..2ca46a6e306ab 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -132,6 +132,20 @@ impl RawVec { Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) } + /// Attempts to create a `RawVec` (on the system heap) with exactly the + /// capacity and alignment requirements for a `[T; capacity]`. This is + /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is + /// zero-sized. Note that if `T` is zero-sized this means you will + /// *not* get a `RawVec` with the requested capacity. + /// + /// Parameterized over the choice of allocator for the returned `RawVec`. + #[inline] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + let mut raw_vec = Self::new_in(alloc); + raw_vec.try_reserve_exact(0, capacity)?; + Ok(raw_vec) + } + /// Like `with_capacity_zeroed`, but parameterized over the choice /// of allocator for the returned `RawVec`. #[cfg(not(no_global_oom_handling))] diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 16df293108017..b50bc0c1682ae 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -470,6 +470,13 @@ impl Vec { Self::with_capacity_in(capacity, Global) } + /// FIXME(poliorcetics): docs & tracking issue + #[inline] + #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity(capacity: usize) -> Result { + Self::try_with_capacity_in(capacity, Global) + } + /// Creates a `Vec` directly from the raw components of another vector. /// /// # Safety @@ -609,6 +616,13 @@ impl Vec { Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } } + /// FIXME(poliorcetics): docs & tracking issue + #[inline] + #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) + } + /// Creates a `Vec` directly from the raw components of another vector. /// /// # Safety