From b74fc535c6f1020670c3609b86a76e33095b2235 Mon Sep 17 00:00:00 2001 From: Ossi Herrala Date: Wed, 20 Aug 2025 23:07:57 +0300 Subject: [PATCH] Validate UTF-8 string before heap allocation This avoids unnecessary heap allocation with invalid strings. --- src/utils/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/utils/mod.rs b/src/utils/mod.rs index f1411016..ea694a03 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -67,8 +67,11 @@ pub fn u64_from_bytes(bytes: &[u8]) -> Result Result { - 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 { + str::from_utf8(bytes).map(ToOwned::to_owned) } pub fn random_string(length: usize) -> String {