-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuf-iter.zig
43 lines (37 loc) · 1.2 KB
/
buf-iter.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const std = @import("std");
const ReaderType = std.fs.File.Reader;
const BufReaderType = std.io.BufferedReader(4096, ReaderType);
const BufReaderReaderType = BufReaderType.Reader;
pub const ReadByLineIterator = struct {
file: std.fs.File,
reader: ReaderType,
buf_reader: BufReaderType,
stream: ?BufReaderReaderType,
buf: [32768]u8,
pub fn next(self: *@This()) !?[]u8 {
if (self.stream == null) {
self.stream = self.buf_reader.reader();
}
if (self.stream) |stream| {
return stream.readUntilDelimiterOrEof(&self.buf, '\n');
}
unreachable;
}
pub fn deinit(self: *@This()) void {
self.file.close();
}
};
// Iterate over the lines in the file using a buffered reader.
// Caller is responsible for calling deinit() on returned iterator when done.
pub fn iterLines(filename: []const u8) !ReadByLineIterator {
var file = try std.fs.cwd().openFile(filename, .{});
const reader = file.reader();
const buf_reader = std.io.bufferedReader(reader);
return ReadByLineIterator{
.file = file,
.reader = reader,
.buf_reader = buf_reader,
.stream = null,
.buf = undefined,
};
}