Skip to content

Commit

Permalink
Add zero_filled constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
c410-f3r committed Aug 13, 2021
1 parent e5b3c9b commit 0fee9fe
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/array_string.rs
Expand Up @@ -129,6 +129,28 @@ impl<const CAP: usize> ArrayString<CAP>
Ok(vec)
}

/// Creates a new `ArrayString` instance fully filled with ASCII NULL characters (`\0`). Useful
/// to be used as buffer to collect external data or as an buffer for intermediate processing.
///
/// ```
/// use arrayvec::ArrayString;
///
/// let string = ArrayString::<16>::zero_filled();
/// assert_eq!(string.len(), 16);
/// ```
#[inline]
pub fn zero_filled() -> Self {
let mut vec = Self::new();
let data = [b'\0'; CAP];
// SAFETY: The array is fully filled with valid UTF-8
unsafe {
let ptr = data.as_ptr() as *const [MaybeUninit<u8>; CAP];
ptr.copy_to_nonoverlapping(&mut vec.xs as *mut _, 1);
vec.set_len(CAP);
}
vec
}

/// Return the capacity of the `ArrayString`.
///
/// ```
Expand Down
7 changes: 6 additions & 1 deletion tests/tests.rs
Expand Up @@ -773,7 +773,6 @@ fn test_arrayvec_const_constructible() {
assert_eq!(var[..], [vec![3, 5, 8]]);
}


#[test]
fn test_arraystring_const_constructible() {
const AS: ArrayString<10> = ArrayString::new_const();
Expand All @@ -786,3 +785,9 @@ fn test_arraystring_const_constructible() {
}


#[test]
fn test_array_string_has_some_sanity_checks() {
let string = ArrayString::<4>::zero_filled();
assert_eq!(string.as_str(), "\0\0\0\0");
assert_eq!(string.len(), 4);
}

0 comments on commit 0fee9fe

Please sign in to comment.