Skip to content

Commit e209a50

Browse files
authored
Merge pull request #197 from c410-f3r/str
Add `zero_filled` constructor
2 parents e5b3c9b + 1e74077 commit e209a50

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/array_string.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,28 @@ impl<const CAP: usize> ArrayString<CAP>
129129
Ok(vec)
130130
}
131131

132+
/// Create a new `ArrayString` value fully filled with ASCII NULL characters (`\0`). Useful
133+
/// to be used as a buffer to collect external data or as a buffer for intermediate processing.
134+
///
135+
/// ```
136+
/// use arrayvec::ArrayString;
137+
///
138+
/// let string = ArrayString::<16>::zero_filled();
139+
/// assert_eq!(string.len(), 16);
140+
/// ```
141+
#[inline]
142+
pub fn zero_filled() -> Self {
143+
assert_capacity_limit!(CAP);
144+
// SAFETY: `assert_capacity_limit` asserts that `len` won't overflow and
145+
// `zeroed` fully fills the array with nulls.
146+
unsafe {
147+
ArrayString {
148+
xs: MaybeUninit::zeroed().assume_init(),
149+
len: CAP as _
150+
}
151+
}
152+
}
153+
132154
/// Return the capacity of the `ArrayString`.
133155
///
134156
/// ```

tests/tests.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -773,7 +773,6 @@ fn test_arrayvec_const_constructible() {
773773
assert_eq!(var[..], [vec![3, 5, 8]]);
774774
}
775775

776-
777776
#[test]
778777
fn test_arraystring_const_constructible() {
779778
const AS: ArrayString<10> = ArrayString::new_const();
@@ -786,3 +785,9 @@ fn test_arraystring_const_constructible() {
786785
}
787786

788787

788+
#[test]
789+
fn test_arraystring_zero_filled_has_some_sanity_checks() {
790+
let string = ArrayString::<4>::zero_filled();
791+
assert_eq!(string.as_str(), "\0\0\0\0");
792+
assert_eq!(string.len(), 4);
793+
}

0 commit comments

Comments
 (0)