just read all bytes
This commit is contained in:
parent
d37ce56eef
commit
c290ad1e65
@ -2,4 +2,3 @@
|
||||
pqr3stu8vwx
|
||||
a1b2c3d4e5f
|
||||
treb7uchet
|
||||
|
||||
|
55
src/main.zig
55
src/main.zig
@ -16,18 +16,12 @@ pub fn main() !void {
|
||||
|
||||
fn day01part1(allocator: std.mem.Allocator, comptime is_test: bool) !void {
|
||||
const filename = file_name(is_test, "01");
|
||||
const line_reader = try LineReader.init(allocator, filename);
|
||||
errdefer line_reader.deinit();
|
||||
const buff = try read_file(allocator, filename);
|
||||
defer allocator.free(buff);
|
||||
var lines = std.mem.split(u8, buff, "\n");
|
||||
|
||||
while (true) {
|
||||
const bytes = line_reader.next() catch |err| switch (err) {
|
||||
error.EndOfStream => {
|
||||
break;
|
||||
},
|
||||
else => return err,
|
||||
};
|
||||
|
||||
print("Bytes: {s}\n", .{bytes});
|
||||
while (lines.next()) |line| {
|
||||
print("line! {s}\n", .{line});
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,42 +31,15 @@ fn file_name(comptime is_test: bool, comptime day: []const u8) []const u8 {
|
||||
return "inputs" ++ input_suffix ++ day;
|
||||
}
|
||||
|
||||
const U8ArrayList = std.ArrayList(u8);
|
||||
fn read_file(allocator: std.mem.Allocator, filename: []const u8) ![]u8 {
|
||||
const file = try std.fs.cwd().openFile(filename, .{});
|
||||
defer file.close();
|
||||
|
||||
const LineReader = struct {
|
||||
allocator: std.mem.Allocator,
|
||||
file: *std.fs.File,
|
||||
line: *U8ArrayList,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator, filename: []const u8) !LineReader {
|
||||
var file = try std.fs.cwd().openFile(filename, .{ .read = true });
|
||||
var line = std.ArrayList(u8).init(allocator);
|
||||
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.file = &file,
|
||||
.line = &line,
|
||||
};
|
||||
const stat = try file.stat();
|
||||
const buff = try file.readToEndAlloc(allocator, stat.size);
|
||||
return buff;
|
||||
}
|
||||
|
||||
pub fn next(self: LineReader) ![]u8 {
|
||||
// self.line.clearRetainingCapacity();
|
||||
var line = std.ArrayList(u8).init(self.allocator);
|
||||
errdefer line.deinit();
|
||||
|
||||
const reader = self.file.reader();
|
||||
const writer = line.writer();
|
||||
|
||||
try reader.streamUntilDelimiter(writer, '\n', null);
|
||||
return self.line.items;
|
||||
}
|
||||
|
||||
pub fn deinit(self: LineReader) void {
|
||||
self.file.close();
|
||||
self.line.deinit();
|
||||
}
|
||||
};
|
||||
|
||||
test "simple test" {
|
||||
var list = std.ArrayList(i32).init(std.testing.allocator);
|
||||
defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
|
||||
|
Loading…
Reference in New Issue
Block a user