From 87c05013309813b3bbf91746ddfa08d3c7825e7b Mon Sep 17 00:00:00 2001 From: Kaido Kert Date: Sun, 15 Jan 2023 10:01:41 -0800 Subject: [PATCH] Add convenience constructor for null-terminated byte literals --- src/array_string.rs | 17 +++++++++++++++++ tests/tests.rs | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/src/array_string.rs b/src/array_string.rs index 5c3414f..847cdb9 100644 --- a/src/array_string.rs +++ b/src/array_string.rs @@ -129,6 +129,23 @@ impl ArrayString 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 { + 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. /// diff --git a/tests/tests.rs b/tests/tests.rs index 2f8a5ef..8fb98e1 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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";