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
17 changes: 17 additions & 0 deletions src/array_string.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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