authorgravatar for thejoshwolfe@gmail.comJosh Wolfe <thejoshwolfe@gmail.com> 2018-01-16 13:28:31-07:00
committergravatar for thejoshwolfe@gmail.comJosh Wolfe <thejoshwolfe@gmail.com> 2018-01-16 13:28:53-07:00
logc58f5a4742156c09e215533ae274f9f991e287a7
treea53fa4f1452de46154ca5486d5693f89619a1fcb
parentee9ab15679ee04a40bdc582779faf43fb10836ce

Buffer.toSliceCopy


1 files changed, 19 insertions(+), 0 deletions(-)

std/buffer.zig+19
......@@ -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
151161test "simple Buffer" {
......@@ -168,3 +178,12 @@ test "simple Buffer" {
168178 try buf2.resize(4);
169179 assert(buf.startsWith(buf2.toSliceConst()));
170180}
181
182test "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}