Created
December 1, 2022 18:39
-
-
Save nothke/2780e300c83ea1603394c372b9e42af0 to your computer and use it in GitHub Desktop.
Minimal generic stack-based string buffer for zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
/// Minimal generic stack-based string buffer | |
pub fn StrBuff(comptime capacity: usize) type { | |
return struct { | |
chars: [capacity]u8 = std.mem.zeroes([capacity]u8), | |
cur: usize = 0, | |
const Error = error{AttemptingToAppendArrayLargerThanCapacity}; | |
pub fn clear(self: *@This()) void { | |
self.chars = std.mem.zeroes([capacity]u8); | |
self.cur = 0; | |
} | |
pub fn len(self: @This()) usize { | |
return self.cur; | |
} | |
pub fn isFull(self: @This()) bool { | |
return self.cur >= capacity; | |
} | |
pub fn append(self: *@This(), string: []const u8) !void { | |
if (self.cur + string.len > capacity) | |
return Error.AttemptingToAppendArrayLargerThanCapacity; | |
const start = self.cur; | |
while (self.cur < start + string.len) { | |
self.chars[self.cur] = string[self.cur - start]; | |
self.cur += 1; | |
} | |
std.log.info("cur: {}", .{self.cur}); | |
} | |
pub fn str(self: @This()) []const u8 { | |
return self.chars[0..self.cur]; | |
} | |
}; | |
} | |
test "append any size" { | |
var buff = StrBuff(16){}; | |
try buff.append("123456789"); | |
try std.testing.expect(buff.len() == 9); | |
} | |
test "append string of exactly capacity size" { | |
var buff = StrBuff(8){}; | |
try buff.append("12345678"); | |
try std.testing.expect(buff.isFull()); | |
} | |
test "fail on trying to append huge value" { | |
var buff = StrBuff(8){}; | |
try buff.append("smth"); | |
try std.testing.expectError(error.AttemptingToAppendArrayLargerThanCapacity, buff.append(" and something really big")); | |
} | |
test "multiple appends and clears" { | |
var buff = StrBuff(8){}; | |
try buff.append("1234"); | |
try buff.append("12"); | |
buff.clear(); | |
try buff.append("12345678"); | |
buff.clear(); | |
try buff.append("12345"); | |
buff.clear(); | |
try std.testing.expect(buff.len() == 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment