Skip to content

Commit feec617

Browse files
committed
try_with_capacity for Vec, VecDeque, String
#91913
1 parent 27686b2 commit feec617

File tree

12 files changed

+144
-3
lines changed

12 files changed

+144
-3
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+15
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,21 @@ impl<T> VecDeque<T> {
559559
pub fn with_capacity(capacity: usize) -> VecDeque<T> {
560560
Self::with_capacity_in(capacity, Global)
561561
}
562+
563+
/// Creates an empty deque with space for at least `capacity` elements.
564+
///
565+
/// # Examples
566+
///
567+
/// ```
568+
/// use std::collections::VecDeque;
569+
///
570+
/// let deque: VecDeque<u32> = VecDeque::with_capacity(10);
571+
/// ```
572+
#[inline]
573+
#[unstable(feature = "try_with_capacity", issue = "91913")]
574+
pub fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, TryReserveError> {
575+
Ok(VecDeque { head: 0, len: 0, buf: RawVec::try_with_capacity_in(capacity, Global)? })
576+
}
562577
}
563578

564579
impl<T, A: Allocator> VecDeque<T, A> {

library/alloc/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@
158158
#![feature(trusted_len)]
159159
#![feature(trusted_random_access)]
160160
#![feature(try_trait_v2)]
161+
#![feature(try_with_capacity)]
161162
#![feature(tuple_trait)]
162163
#![feature(unchecked_math)]
163164
#![feature(unicode_internals)]

library/alloc/src/raw_vec.rs

+7
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ impl<T, A: Allocator> RawVec<T, A> {
147147
handle_reserve(Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc))
148148
}
149149

150+
/// Like `try_with_capacity`, but parameterized over the choice of
151+
/// allocator for the returned `RawVec`.
152+
#[inline]
153+
pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
154+
Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc)
155+
}
156+
150157
/// Like `with_capacity_zeroed`, but parameterized over the choice
151158
/// of allocator for the returned `RawVec`.
152159
#[cfg(not(no_global_oom_handling))]

library/alloc/src/string.rs

+13
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,19 @@ impl String {
492492
String { vec: Vec::with_capacity(capacity) }
493493
}
494494

495+
/// Creates a new empty `String` with at least the specified capacity.
496+
///
497+
/// # Errors
498+
///
499+
/// Returns [`Err`] if the capacity exceeds `isize::MAX` bytes,
500+
/// or if the memory allocator reports failure.
501+
///
502+
#[inline]
503+
#[unstable(feature = "try_with_capacity", issue = "91913")]
504+
pub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError> {
505+
Ok(String { vec: Vec::try_with_capacity(capacity)? })
506+
}
507+
495508
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
496509
// required for this method definition, is not available. Since we don't
497510
// require this method for testing purposes, I'll just stub it

library/alloc/src/vec/mod.rs

+35
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,22 @@ impl<T> Vec<T> {
481481
Self::with_capacity_in(capacity, Global)
482482
}
483483

484+
/// Constructs a new, empty `Vec<T>` with at least the specified capacity.
485+
///
486+
/// The vector will be able to hold at least `capacity` elements without
487+
/// reallocating. This method is allowed to allocate for more elements than
488+
/// `capacity`. If `capacity` is 0, the vector will not allocate.
489+
///
490+
/// # Errors
491+
///
492+
/// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
493+
/// or if the allocator reports allocation failure.
494+
#[inline]
495+
#[unstable(feature = "try_with_capacity", issue = "91913")]
496+
pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
497+
Self::try_with_capacity_in(capacity, Global)
498+
}
499+
484500
/// Creates a `Vec<T>` directly from a pointer, a capacity, and a length.
485501
///
486502
/// # Safety
@@ -672,6 +688,25 @@ impl<T, A: Allocator> Vec<T, A> {
672688
Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
673689
}
674690

691+
/// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
692+
/// with the provided allocator.
693+
///
694+
/// The vector will be able to hold at least `capacity` elements without
695+
/// reallocating. This method is allowed to allocate for more elements than
696+
/// `capacity`. If `capacity` is 0, the vector will not allocate.
697+
///
698+
/// # Errors
699+
///
700+
/// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
701+
/// or if the allocator reports allocation failure.
702+
#[cfg(not(no_global_oom_handling))]
703+
#[inline]
704+
#[unstable(feature = "allocator_api", issue = "32838")]
705+
// #[unstable(feature = "try_with_capacity", issue = "91913")]
706+
pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
707+
Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
708+
}
709+
675710
/// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length,
676711
/// and an allocator.
677712
///

library/alloc/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#![feature(pattern)]
2020
#![feature(trusted_len)]
2121
#![feature(try_reserve_kind)]
22+
#![feature(try_with_capacity)]
2223
#![feature(unboxed_closures)]
2324
#![feature(associated_type_bounds)]
2425
#![feature(binary_heap_into_iter_sorted)]

library/alloc/tests/string.rs

+11
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,17 @@ fn test_reserve_exact() {
723723
assert!(s.capacity() >= 33)
724724
}
725725

726+
#[test]
727+
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
728+
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc
729+
fn test_try_with_capacity() {
730+
let string = String::try_with_capacity(1000).unwrap();
731+
assert_eq!(0, string.len());
732+
assert!(string.capacity() >= 1000 && string.capacity() <= isize::MAX as usize);
733+
734+
assert!(String::try_with_capacity(usize::MAX).is_err());
735+
}
736+
726737
#[test]
727738
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
728739
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc

library/alloc/tests/vec.rs

+12
Original file line numberDiff line numberDiff line change
@@ -1694,6 +1694,18 @@ fn test_reserve_exact() {
16941694
assert!(v.capacity() >= 33)
16951695
}
16961696

1697+
#[test]
1698+
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
1699+
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc
1700+
fn test_try_with_capacity() {
1701+
let mut vec: Vec<u32> = Vec::try_with_capacity(5).unwrap();
1702+
assert_eq!(0, vec.len());
1703+
assert!(vec.capacity() >= 5 && vec.capacity() <= isize::MAX as usize / 4);
1704+
assert!(vec.spare_capacity_mut().len() >= 5);
1705+
1706+
assert!(Vec::<u16>::try_with_capacity(isize::MAX as usize + 1).is_err());
1707+
}
1708+
16971709
#[test]
16981710
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
16991711
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc

library/alloc/tests/vec_deque.rs

+11
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,17 @@ fn test_reserve_exact_2() {
11821182
assert!(v.capacity() >= 33)
11831183
}
11841184

1185+
#[test]
1186+
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
1187+
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc
1188+
fn test_try_with_capacity() {
1189+
let vec: VecDeque<u32> = VecDeque::try_with_capacity(5).unwrap();
1190+
assert_eq!(0, vec.len());
1191+
assert!(vec.capacity() >= 5 && vec.capacity() <= isize::MAX as usize / 4);
1192+
1193+
assert!(VecDeque::<u16>::try_with_capacity(isize::MAX as usize + 1).is_err());
1194+
}
1195+
11851196
#[test]
11861197
#[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
11871198
#[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc

tests/codegen/vec-with-capacity.rs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// compile-flags: -O
2+
// ignore-debug
3+
// (with debug assertions turned on, `assert_unchecked` generates a real assertion)
4+
5+
#![crate_type = "lib"]
6+
#![feature(try_with_capacity)]
7+
8+
// CHECK-LABEL: @with_capacity_does_not_grow1
9+
#[no_mangle]
10+
pub fn with_capacity_does_not_grow1() -> Vec<u32> {
11+
let v = Vec::with_capacity(1234);
12+
// CHECK: call {{.*}}__rust_alloc(
13+
// CHECK-NOT: call {{.*}}__rust_realloc
14+
// CHECK-NOT: call {{.*}}capacity_overflow
15+
// CHECK-NOT: call {{.*}}finish_grow
16+
// CHECK-NOT: call {{.*}}reserve
17+
// CHECK-NOT: memcpy
18+
// CHECK-NOT: memset
19+
v
20+
}
21+
22+
// CHECK-LABEL: @try_with_capacity_does_not_grow2
23+
#[no_mangle]
24+
pub fn try_with_capacity_does_not_grow2() -> Option<Vec<Vec<u8>>> {
25+
let v = Vec::try_with_capacity(1234).ok()?;
26+
// CHECK: call {{.*}}__rust_alloc(
27+
// CHECK-NOT: call {{.*}}__rust_realloc
28+
// CHECK-NOT: call {{.*}}capacity_overflow
29+
// CHECK-NOT: call {{.*}}finish_grow
30+
// CHECK-NOT: call {{.*}}handle_alloc_error
31+
// CHECK-NOT: call {{.*}}reserve
32+
// CHECK-NOT: memcpy
33+
// CHECK-NOT: memset
34+
Some(v)
35+
}
+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
thread 'main' panicked at library/alloc/src/raw_vec.rs:570:5:
1+
thread 'main' panicked at library/alloc/src/raw_vec.rs:584:5:
22
capacity overflow
33
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

tests/ui/suggestions/deref-path-method.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ LL | Vec::contains(&vec, &0);
77
note: if you're trying to build a new `Vec<_, _>` consider using one of the following associated functions:
88
Vec::<T>::new
99
Vec::<T>::with_capacity
10+
Vec::<T>::try_with_capacity
1011
Vec::<T>::from_raw_parts
11-
Vec::<T, A>::new_in
12-
and 2 others
12+
and 4 others
1313
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
1414
help: the function `contains` is implemented on `[_]`
1515
|

0 commit comments

Comments
 (0)