Skip to content

Commit c58f5a4

Browse files
committedJan 16, 2018
Buffer.toSliceCopy
1 parent ee9ab15 commit c58f5a4

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 

‎std/buffer.zig

+19
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,16 @@ pub const Buffer = struct {
146146
pub fn ptr(self: &const Buffer) -> &u8 {
147147
return self.list.items.ptr;
148148
}
149+
150+
/// Returns a copy of this buffer's toSlice() contents
151+
/// allocated exactly to size.
152+
/// This method uses the provided allocator instead of
153+
/// this object's own allocator to allocate the new array.
154+
pub fn toSliceCopy(self: &Buffer, allocator: &Allocator) -> %[]u8 {
155+
var result = try allocator.alloc(u8, self.len());
156+
mem.copy(u8, result, self.toSliceConst());
157+
return result;
158+
}
149159
};
150160

151161
test "simple Buffer" {
@@ -168,3 +178,12 @@ test "simple Buffer" {
168178
try buf2.resize(4);
169179
assert(buf.startsWith(buf2.toSliceConst()));
170180
}
181+
182+
test "Buffer.toSliceCopy" {
183+
var buffer = try Buffer.init(debug.global_allocator, "abc");
184+
var copy = try buffer.toSliceCopy(debug.global_allocator);
185+
buffer.shrink(0);
186+
try buffer.append("xyz");
187+
assert(mem.eql(u8, buffer.toSliceConst(), "xyz"));
188+
assert(mem.eql(u8, copy, "abc"));
189+
}

2 commit comments

Comments
 (2)

andrewrk commented on Jan 16, 2018

@andrewrk
Member

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

thejoshwolfe commented on Jan 16, 2018

@thejoshwolfe
ContributorAuthor

oh. that's a better idea.

Please sign in to comment.