Skip to content

Instantly share code, notes, and snippets.

@nothke
Created December 1, 2022 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nothke/2780e300c83ea1603394c372b9e42af0 to your computer and use it in GitHub Desktop.
Save nothke/2780e300c83ea1603394c372b9e42af0 to your computer and use it in GitHub Desktop.
Minimal generic stack-based string buffer for zig
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