Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4256,12 +4256,15 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {

#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_default", issue = "143894")]
impl<T> const Default for Vec<T> {
/// Creates an empty `Vec<T>`.
impl<T, A> const Default for Vec<T, A>
where
A: Allocator + [const] Default,
{
/// Creates an empty `Vec<T>` in the allocator `A`.
///
/// The vector will not allocate until elements are pushed onto it.
fn default() -> Vec<T> {
Vec::new()
fn default() -> Self {
Vec::new_in(A::default())
}
}

Expand Down
1 change: 1 addition & 0 deletions library/alloctests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#![feature(macro_metavar_expr_concat)]
#![feature(vec_peek_mut)]
#![feature(vec_try_remove)]
#![feature(const_default)]
#![allow(internal_features)]
#![deny(fuzzy_provenance_casts)]
#![deny(unsafe_op_in_unsafe_fn)]
Expand Down
27 changes: 27 additions & 0 deletions library/alloctests/tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,33 @@ fn test_into_iter_drop_allocator() {
assert_eq!(drop_count, 2);
}

#[test]
fn test_default_vec_in_custom_allocator() {
struct ReferenceCountedAllocator;

impl const Default for ReferenceCountedAllocator {
fn default() -> Self {
Self {}
}
}

unsafe impl Allocator for ReferenceCountedAllocator {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, core::alloc::AllocError> {
System.allocate(layout)
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
// Safety: Invariants passed to caller.
unsafe { System.deallocate(ptr, layout) }
}
}

let mut vec = Vec::<i32, ReferenceCountedAllocator>::default();

vec.push(10);
assert_eq!(vec.len(), 1);
}

#[test]
fn test_into_iter_zst() {
#[derive(Debug, Clone)]
Expand Down
Loading