Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions crates/bytesbuf/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,33 @@ impl BytesView {
BytesViewSlices::new(self)
}

/// Copies the byte sequence into a new [`Vec<u8>`].
///
/// 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<u8> {
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
Expand Down Expand Up @@ -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();
Expand Down
Loading