Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience constructor for null-terminated byte literals #233

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/array_string.rs
Expand Up @@ -129,6 +129,23 @@ impl<const CAP: usize> ArrayString<CAP>
Ok(vec)
}

/// Create a new `ArrayString` from a byte string literal, that can be null-terminated.
///
/// **Errors** if the byte string literal is not valid UTF-8.
/// ```
/// use arrayvec::ArrayString;
///
/// let string = ArrayString::from_c_byte_string(b"hello\0world").unwrap();
/// assert_eq!(&string,"hello")
/// ```
pub fn from_c_byte_string(b: &[u8; CAP]) -> Result<Self, Utf8Error> {
let mut result = Self::from_byte_string(b)?;
if let Some(i) = &result.find('\0') {
result.truncate(*i);
}
Ok(result)
}

/// Create a new `ArrayString` value fully filled with ASCII NULL characters (`\0`). Useful
/// to be used as a buffer to collect external data or as a buffer for intermediate processing.
///
Expand Down
8 changes: 8 additions & 0 deletions tests/tests.rs
Expand Up @@ -579,6 +579,14 @@ fn test_string_from_bytes() {
assert_eq!(u.len(), text.len());
}

#[test]
fn test_string_from_c_bytes() {
let text = "hello";
let u = ArrayString::from_c_byte_string(b"hello\0world").unwrap();
assert_eq!(&u, text);
assert_eq!(u.len(), text.len());
}

#[test]
fn test_string_clone() {
let text = "hi";
Expand Down