Skip to content

Commit

Permalink
Buffer.toSliceCopy
Browse files Browse the repository at this point in the history
  • Loading branch information
thejoshwolfe committed Jan 16, 2018
1 parent ee9ab15 commit c58f5a4
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions std/buffer.zig
Expand Up @@ -146,6 +146,16 @@ pub const Buffer = struct {
pub fn ptr(self: &const Buffer) -> &u8 {
return self.list.items.ptr;
}

/// Returns a copy of this buffer's toSlice() contents
/// allocated exactly to size.
/// This method uses the provided allocator instead of
/// this object's own allocator to allocate the new array.
pub fn toSliceCopy(self: &Buffer, allocator: &Allocator) -> %[]u8 {
var result = try allocator.alloc(u8, self.len());
mem.copy(u8, result, self.toSliceConst());
return result;
}
};

test "simple Buffer" {
Expand All @@ -168,3 +178,12 @@ test "simple Buffer" {
try buf2.resize(4);
assert(buf.startsWith(buf2.toSliceConst()));
}

test "Buffer.toSliceCopy" {
var buffer = try Buffer.init(debug.global_allocator, "abc");
var copy = try buffer.toSliceCopy(debug.global_allocator);
buffer.shrink(0);
try buffer.append("xyz");
assert(mem.eql(u8, buffer.toSliceConst(), "xyz"));
assert(mem.eql(u8, copy, "abc"));
}

2 comments on commit c58f5a4

@andrewrk
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use mem.dupe(allocator, u8, buffer.toSliceConst()) ?

@thejoshwolfe
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh. that's a better idea.

Please sign in to comment.