From 6976958e5ee1ee1aa18605b6e208837a5dbb0248 Mon Sep 17 00:00:00 2001 From: Sander Saares Date: Fri, 12 Jun 2026 13:13:37 +0300 Subject: [PATCH] feat(bytesbuf): add BytesView::to_vec() Adds a method to copy the byte sequence of a BytesView into a new Vec, leaving the view unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/bytesbuf/src/view.rs | 61 +++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/bytesbuf/src/view.rs b/crates/bytesbuf/src/view.rs index 1a8f03bf5..7af3cafe0 100644 --- a/crates/bytesbuf/src/view.rs +++ b/crates/bytesbuf/src/view.rs @@ -564,6 +564,33 @@ impl BytesView { BytesViewSlices::new(self) } + /// Copies the byte sequence into a new [`Vec`]. + /// + /// The view itself is left unchanged. + /// + /// # Example + /// + /// ``` + /// # let memory = bytesbuf::mem::GlobalPool::new(); + /// use bytesbuf::BytesView; + /// + /// let view = BytesView::copied_from_slice(b"Hello, world!", &memory); + /// + /// let bytes = view.to_vec(); + /// + /// assert_eq!(bytes, b"Hello, world!"); + /// ``` + #[must_use] + pub fn to_vec(&self) -> Vec { + let mut bytes = Vec::with_capacity(self.len()); + + for (slice, _meta) in self.slices() { + bytes.extend_from_slice(slice); + } + + bytes + } + /// Inspects the metadata of the [`first_slice()`]. /// /// `None` if there is no metadata associated with the first slice or @@ -1389,6 +1416,40 @@ mod tests { assert_eq!(view.slices().count(), 0); } + #[test] + fn to_vec_single_span() { + let memory = TransparentMemory::new(); + let view = BytesView::copied_from_slice(b"Hello, world!", &memory); + + let bytes = view.to_vec(); + + assert_eq!(bytes, b"Hello, world!"); + // The view is left unchanged. + assert_eq!(view.len(), 13); + } + + #[test] + fn to_vec_multi_span() { + let memory = TransparentMemory::new(); + let segment1 = BytesView::copied_from_slice(b"Hello, ", &memory); + let segment2 = BytesView::copied_from_slice(b"world!", &memory); + + let view = BytesView::from_views(vec![segment1, segment2]); + + let bytes = view.to_vec(); + + assert_eq!(bytes, b"Hello, world!"); + } + + #[test] + fn to_vec_empty() { + let view = BytesView::new(); + + let bytes = view.to_vec(); + + assert!(bytes.is_empty()); + } + #[test] fn eq_view() { let memory = TransparentMemory::new();