diff options
| author | 2021-09-12 00:37:59 -0700 | |
|---|---|---|
| committer | 2021-09-12 00:37:59 -0700 | |
| commit | dfb65ef1ca0406e9679f21ae316b6a0878b56271 (patch) | |
| tree | 1a99326014d40b68de8f66454605b45c2dc1233d /src/string_builder.zig | |
| parent | 57ca04444b0397c5fd92177382627cf5113282b5 (diff) | |
| download | bun-dfb65ef1ca0406e9679f21ae316b6a0878b56271.tar.gz bun-dfb65ef1ca0406e9679f21ae316b6a0878b56271.tar.zst bun-dfb65ef1ca0406e9679f21ae316b6a0878b56271.zip | |
Reduce number of allocations for serializing error messages
Diffstat (limited to 'src/string_builder.zig')
| -rw-r--r-- | src/string_builder.zig | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/string_builder.zig b/src/string_builder.zig new file mode 100644 index 000000000..26782b896 --- /dev/null +++ b/src/string_builder.zig @@ -0,0 +1,32 @@ +usingnamespace @import("string_types.zig"); +const Allocator = @import("std").mem.Allocator; +const assert = @import("std").debug.assert; +const copy = @import("std").mem.copy; + +const StringBuilder = @This(); + +len: usize = 0, +cap: usize = 0, +ptr: ?[*]u8 = null, + +pub fn count(this: *StringBuilder, slice: string) void { + this.cap += slice.len; +} + +pub fn allocate(this: *StringBuilder, allocator: *Allocator) !void { + var slice = try allocator.alloc(u8, this.cap); + this.ptr = slice.ptr; + this.len = 0; +} + +pub fn append(this: *StringBuilder, slice: string) string { + assert(this.len <= this.cap); // didn't count everything + assert(this.ptr != null); // must call allocate first + + copy(u8, this.ptr.?[this.len..this.cap], slice); + const result = this.ptr.?[this.len..this.cap][0..slice.len]; + this.len += slice.len; + + assert(this.len <= this.cap); + return result; +} |
