aboutsummaryrefslogtreecommitdiff
path: root/lib/std/buffer.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2019-12-01 09:56:01 -0500
committerAndrew Kelley <andrew@ziglang.org>2019-12-01 09:56:01 -0500
commitb36c07a95a6cf9b2cc120133b44cbd0673e6823a (patch)
tree2c2bf8ff9137d51b80ae56dc70ef9375b8c13583 /lib/std/buffer.zig
parentb220be7a33a9835a1ec7a033e472830290332d57 (diff)
parent4b6740e19d57454f3c4eac0c2e9a92ce08e7ec04 (diff)
downloadzig-b36c07a95a6cf9b2cc120133b44cbd0673e6823a.tar.gz
zig-b36c07a95a6cf9b2cc120133b44cbd0673e6823a.zip
Merge remote-tracking branch 'origin/master' into remove-array-type-coercion
Diffstat (limited to 'lib/std/buffer.zig')
-rw-r--r--lib/std/buffer.zig36
1 files changed, 35 insertions, 1 deletions
diff --git a/lib/std/buffer.zig b/lib/std/buffer.zig
index 37414d64d2..46c55a32b8 100644
--- a/lib/std/buffer.zig
+++ b/lib/std/buffer.zig
@@ -16,13 +16,22 @@ pub const Buffer = struct {
mem.copy(u8, self.list.items, m);
return self;
}
-
+
+ /// Initialize memory to size bytes of undefined values.
/// Must deinitialize with deinit.
pub fn initSize(allocator: *Allocator, size: usize) !Buffer {
var self = initNull(allocator);
try self.resize(size);
return self;
}
+
+ /// Initialize with capacity to hold at least num bytes.
+ /// Must deinitialize with deinit.
+ pub fn initCapacity(allocator: *Allocator, num: usize) !Buffer {
+ var self = Buffer{ .list = try ArrayList(u8).initCapacity(allocator, num + 1) };
+ self.list.appendAssumeCapacity(0);
+ return self;
+ }
/// Must deinitialize with deinit.
/// None of the other operations are valid until you do one of these:
@@ -98,6 +107,13 @@ pub const Buffer = struct {
pub fn len(self: Buffer) usize {
return self.list.len - 1;
}
+
+ pub fn capacity(self: Buffer) usize {
+ return if (self.list.items.len > 0)
+ self.list.items.len - 1
+ else
+ 0;
+ }
pub fn append(self: *Buffer, m: []const u8) !void {
const old_len = self.len();
@@ -151,3 +167,21 @@ test "simple Buffer" {
try buf2.resize(4);
testing.expect(buf.startsWith(buf2.toSlice()));
}
+
+test "Buffer.initSize" {
+ var buf = try Buffer.initSize(debug.global_allocator, 3);
+ testing.expect(buf.len() == 3);
+ try buf.append("hello");
+ testing.expect(mem.eql(u8, buf.toSliceConst()[3..], "hello"));
+}
+
+test "Buffer.initCapacity" {
+ var buf = try Buffer.initCapacity(debug.global_allocator, 10);
+ testing.expect(buf.len() == 0);
+ testing.expect(buf.capacity() >= 10);
+ const old_cap = buf.capacity();
+ try buf.append("hello");
+ testing.expect(buf.len() == 5);
+ testing.expect(buf.capacity() == old_cap);
+ testing.expect(mem.eql(u8, buf.toSliceConst(), "hello"));
+}