Browse Source

Validate UTF-8 string before heap allocation

This avoids unnecessary heap allocation with invalid strings.
merge-requests/777/head
Ossi Herrala 7 months ago
parent
commit
b74fc535c6
No known key found for this signature in database
  1. 7
      src/utils/mod.rs

7
src/utils/mod.rs

@ -67,8 +67,11 @@ pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError
} }
/// Parses the bytes into a string. /// Parses the bytes into a string.
pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> { ///
String::from_utf8(bytes.to_vec()) /// If `&str` is enough please use [str::from_utf8] to avoid unnecessary
/// allocation.
pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::str::Utf8Error> {
str::from_utf8(bytes).map(ToOwned::to_owned)
} }
pub fn random_string(length: usize) -> String { pub fn random_string(length: usize) -> String {

Loading…
Cancel
Save