From 685221d40bd39b1f00d743970e6ba894c978963b Mon Sep 17 00:00:00 2001 From: fereidani Date: Tue, 4 Aug 2026 14:31:12 +0330 Subject: [PATCH 1/3] feat: implement Clone trait for ByteString with custom clone and clone_from methods --- library/alloc/src/bstr.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/library/alloc/src/bstr.rs b/library/alloc/src/bstr.rs index e0d88b27672e0..ee1f143e4c4b2 100644 --- a/library/alloc/src/bstr.rs +++ b/library/alloc/src/bstr.rs @@ -42,10 +42,23 @@ use crate::vec::Vec; /// showing invalid UTF-8 as hex escapes or the Unicode replacement character, respectively. #[unstable(feature = "bstr", issue = "134915")] #[repr(transparent)] -#[derive(Clone)] #[doc(alias = "BString")] pub struct ByteString(pub Vec); +#[unstable(feature = "bstr", issue = "134915")] +impl Clone for ByteString { + #[inline] + fn clone(&self) -> Self { + ByteString(self.0.clone()) + } + + #[inline] + fn clone_from(&mut self, source: &Self) { + self.0.clone_from(&source.0); + } +} + +#[unstable(feature = "bstr", issue = "134915")] impl ByteString { #[inline] pub(crate) fn as_bytes(&self) -> &[u8] { From 9b0e0a3fd45876f79776abe13b69a287c3578988 Mon Sep 17 00:00:00 2001 From: fereidani Date: Tue, 4 Aug 2026 14:31:42 +0330 Subject: [PATCH 2/3] feat: add clone_into method for ByteStr to improve cloning efficiency --- library/alloc/src/bstr.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/library/alloc/src/bstr.rs b/library/alloc/src/bstr.rs index ee1f143e4c4b2..1d921d1b3592a 100644 --- a/library/alloc/src/bstr.rs +++ b/library/alloc/src/bstr.rs @@ -574,6 +574,11 @@ impl ToOwned for ByteStr { fn to_owned(&self) -> ByteString { ByteString(self.0.to_vec()) } + + #[inline] + fn clone_into(&self, target: &mut ByteString) { + self.0.clone_into(&mut target.0); + } } #[unstable(feature = "bstr", issue = "134915")] From 5e746bd73f6827b4ed52c74bb19f88c8fd009ce4 Mon Sep 17 00:00:00 2001 From: fereidani Date: Tue, 4 Aug 2026 14:39:08 +0330 Subject: [PATCH 3/3] perf: optimize from_iter implementation for ByteString to reduce allocations --- library/alloc/src/bstr.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/library/alloc/src/bstr.rs b/library/alloc/src/bstr.rs index 1d921d1b3592a..e7bb533caa94c 100644 --- a/library/alloc/src/bstr.rs +++ b/library/alloc/src/bstr.rs @@ -325,11 +325,16 @@ impl<'a> FromIterator<&'a ByteStr> for ByteString { impl FromIterator for ByteString { #[inline] fn from_iter>(iter: T) -> Self { - let mut buf = Vec::new(); + // Reuse first `ByteString`'s buffer to avoid an allocation and copy. + let mut first: Option = None; for mut b in iter { - buf.append(&mut b.0); + if let Some(buf) = &mut first { + buf.0.append(&mut b.0); + } else { + first = Some(b); + } } - ByteString(buf) + first.unwrap_or(ByteString(Vec::new())) } }