From c290ad1e658e6da3fb4d696e0d8652be7ca20b3e Mon Sep 17 00:00:00 2001 From: Araozu Date: Mon, 13 May 2024 14:02:26 -0500 Subject: [PATCH] just read all bytes --- inputs_test/01 | 1 - src/main.zig | 57 +++++++++++--------------------------------------- 2 files changed, 12 insertions(+), 46 deletions(-) diff --git a/inputs_test/01 b/inputs_test/01 index 4cba7d0..7bbc69a 100644 --- a/inputs_test/01 +++ b/inputs_test/01 @@ -2,4 +2,3 @@ pqr3stu8vwx a1b2c3d4e5f treb7uchet - diff --git a/src/main.zig b/src/main.zig index 37c672f..4ef4dfc 100644 --- a/src/main.zig +++ b/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,41 +31,14 @@ 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, - }; - } - - 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(); - } -}; + const stat = try file.stat(); + const buff = try file.readToEndAlloc(allocator, stat.size); + return buff; +} test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator);