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
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ jobs:
features: serde
experimental: false
# doctest of `ArrayVec::spare_capacity_mut` has MSRV 1.55
test-args: --skip spare_capacity_mut
# doctest of `ArrayVec::new_in_place` has MSRV 1.82
test-args: --skip spare_capacity_mut --skip new_in_place
- rust: 1.70.0
features: serde
experimental: false
# doctest of `ArrayVec::new_in_place` has MSRV 1.82
test-args: --skip new_in_place
- rust: stable
features:
bench: true
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
Recent Changes (arrayvec)
=========================

- Enable in-place initialization [#304](https://github.com/bluss/arrayvec/pull/304)

## 0.7.6

- Fix no-std build [#274](https://github.com/bluss/arrayvec/pull/274)
Expand Down
41 changes: 41 additions & 0 deletions src/arrayvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,47 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
}
}

/// Initialize an empty `ArrayVec` in-place.
///
/// Useful when you want to store a huge `ArrayVec` in some pre-initialized memory and
/// don't want to create and move it from the stack.
/// This is very cheap as all elements are uninitialized when the vec is empty.
///
/// ```
/// use arrayvec::ArrayVec;
/// use std::mem::MaybeUninit;
///
/// let mut place = MaybeUninit::<ArrayVec<_, 10>>::uninit();
/// let vec = ArrayVec::new_in_place(&mut place);
/// assert_eq!(vec.len(), 0);
/// assert_eq!(vec.capacity(), 10);
/// vec.push(42);
/// assert_eq!(vec, [42].as_slice());
/// ```
///
/// ### Creating an `ArrayVec` on the Heap
///
/// The return value is the same reference as passed to the function. Thus you can just
/// ignore that and assume that your [`MaybeUninit`] is initialized.
///
/// ```
/// use arrayvec::ArrayVec;
/// use std::mem::MaybeUninit;
///
/// let mut place = Box::new_uninit();
/// ArrayVec::new_in_place(&mut place);
/// let vec: Box<ArrayVec<u32, 10>> = unsafe { place.assume_init() };
/// assert_eq!(vec.len(), 0);
/// assert_eq!(vec.capacity(), 10);
/// ```
#[inline]
pub fn new_in_place(uninit: &mut MaybeUninit<Self>) -> &mut Self {
let ptr = uninit.as_mut_ptr();
unsafe { ptr::addr_of_mut!((*ptr).len).write(0); }
// XXX: Once MSRV >= 1.55 we can use: unsafe { uninit.assume_init_mut() }
unsafe { &mut *ptr }
}

/// Create a new empty `ArrayVec` (const fn).
///
/// The maximum capacity is given by the generic parameter `CAP`.
Expand Down