| ... | ... | @@ -146,6 +146,16 @@ pub const Buffer = struct { |
| 146 | 146 | pub fn ptr(self: &const Buffer) -> &u8 { |
| 147 | 147 | return self.list.items.ptr; |
| 148 | 148 | } |
| 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 | } |
| 149 | 159 | }; |
| 150 | 160 | |
| 151 | 161 | test "simple Buffer" { |
| ... | ... | @@ -168,3 +178,12 @@ test "simple Buffer" { |
| 168 | 178 | try buf2.resize(4); |
| 169 | 179 | assert(buf.startsWith(buf2.toSliceConst())); |
| 170 | 180 | } |
| 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 | } |