1
0

day04: solve

Add a few util functions now that I'm getting sick of typing
std.mem.splitScalar.
This commit is contained in:
2023-12-04 18:02:48 +11:00
parent e112876796
commit 9c64d710a3
2 changed files with 132 additions and 0 deletions

View File

@ -1,4 +1,37 @@
const std = @import("std");
const mem = std.mem;
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
/// General purpose allocator.
pub const gpa = gpa_impl.allocator();
pub const ParseIntsOptions = struct {
base: u8 = 10,
sep: u8 = ' ',
};
/// Parses separated integers. Sequential separators are treated as one. Caller owns memory.
pub fn parseIntsScalar(comptime T: type, alloc: std.mem.Allocator, input: []const u8, opts: ParseIntsOptions) ![]T {
var items = std.ArrayList(T).init(alloc);
errdefer items.deinit();
var it = split(input, opts.sep);
while (it.next()) |i| {
if (i.len == 0) continue;
try items.append(try std.fmt.parseInt(T, i, opts.base));
}
return try items.toOwnedSlice();
}
/// Shortcut to splitScalar with a byte buffer.
pub fn split(buffer: []const u8, sep: u8) mem.SplitIterator(u8, .scalar) {
return mem.splitScalar(u8, buffer, sep);
}
pub fn splitLines(buffer: []const u8) mem.SplitIterator(u8, .scalar) {
return split(buffer, '\n');
}
pub fn splitSpace(buffer: []const u8) mem.SplitIterator(u8, .scalar) {
return split(buffer, ' ');
}