Skip to content

Commit

Permalink
FIX: Add new_const() for const construction and revert new to old ver…
Browse files Browse the repository at this point in the history
…sion

The new() function is significantly faster, it optimizes better at the
moment/in current rust. For this reason, provide a const fn constructor,
but not as the default `new`.
  • Loading branch information
bluss committed Mar 29, 2021
1 parent 198a403 commit 1f75553
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
21 changes: 20 additions & 1 deletion src/array_string.rs
Expand Up @@ -59,7 +59,26 @@ impl<const CAP: usize> ArrayString<CAP>
/// assert_eq!(&string[..], "foo");
/// assert_eq!(string.capacity(), 16);
/// ```
pub const fn new() -> ArrayString<CAP> {
pub fn new() -> ArrayString<CAP> {
assert_capacity_limit!(CAP);
unsafe {
ArrayString { xs: MaybeUninit::uninit().assume_init(), len: 0 }
}
}

/// Create a new empty `ArrayString` (const fn).
///
/// Capacity is inferred from the type parameter.
///
/// ```
/// use arrayvec::ArrayString;
///
/// let mut string = ArrayString::<16>::new();
/// string.push_str("foo");
/// assert_eq!(&string[..], "foo");
/// assert_eq!(string.capacity(), 16);
/// ```
pub const fn new_const() -> ArrayString<CAP> {
assert_capacity_limit!(CAP);
ArrayString { xs: MakeMaybeUninit::ARRAY, len: 0 }
}
Expand Down
22 changes: 21 additions & 1 deletion src/arrayvec.rs
Expand Up @@ -77,7 +77,27 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
/// assert_eq!(&array[..], &[1, 2]);
/// assert_eq!(array.capacity(), 16);
/// ```
pub const fn new() -> ArrayVec<T, CAP> {
pub fn new() -> ArrayVec<T, CAP> {
assert_capacity_limit!(CAP);
unsafe {
ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 }
}
}

/// Create a new empty `ArrayVec` (const fn).
///
/// The maximum capacity is given by the generic parameter `CAP`.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::<_, 16>::new();
/// array.push(1);
/// array.push(2);
/// assert_eq!(&array[..], &[1, 2]);
/// assert_eq!(array.capacity(), 16);
/// ```
pub const fn new_const() -> ArrayVec<T, CAP> {
assert_capacity_limit!(CAP);
ArrayVec { xs: MakeMaybeUninit::ARRAY, len: 0 }
}
Expand Down
4 changes: 2 additions & 2 deletions tests/tests.rs
Expand Up @@ -730,7 +730,7 @@ fn deny_max_capacity_arrayvec_value() {

#[test]
fn test_arrayvec_const_constructible() {
const OF_U8: ArrayVec<Vec<u8>, 10> = ArrayVec::new();
const OF_U8: ArrayVec<Vec<u8>, 10> = ArrayVec::new_const();

let mut var = OF_U8;
assert!(var.is_empty());
Expand All @@ -742,7 +742,7 @@ fn test_arrayvec_const_constructible() {

#[test]
fn test_arraystring_const_constructible() {
const AS: ArrayString<10> = ArrayString::new();
const AS: ArrayString<10> = ArrayString::new_const();

let mut var = AS;
assert!(var.is_empty());
Expand Down

0 comments on commit 1f75553

Please sign in to comment.