refactoring

This commit is contained in:
Paul Campbell 2021-12-29 20:00:03 +00:00
parent 58551ff7da
commit 1980d3a588

View file

@ -4,9 +4,8 @@ const os = builtin.os;
const mem = std.mem; const mem = std.mem;
const testing = std.testing; const testing = std.testing;
const io = std.io; const io = std.io;
const heap = std.heap;
const fs = std.fs; const fs = std.fs;
const File = fs.File;
const FileReader = File.Reader;
// step 1: [x] read in a file from stdin and write out to stdout // step 1: [x] read in a file from stdin and write out to stdout
// step 2: [ ] read in a named file in parameters and write out to stdout // step 2: [ ] read in a named file in parameters and write out to stdout
@ -17,33 +16,46 @@ const FileReader = File.Reader;
pub fn main() anyerror!void { pub fn main() anyerror!void {
const stdin = io.getStdIn(); const stdin = io.getStdIn();
const stdout = io.getStdOut(); const stdout = io.getStdOut();
try dumpInput(stdin, stdout); var buffer: [4096]u8 = undefined;
var fba = heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
try dumpInput(stdin, stdout, allocator);
} }
const maxLineLength = 4096; const maxLineLength = 4096;
fn dumpInput(in: File, out: File) !void { fn dumpInput(in: fs.File, out: fs.File, allocator: mem.Allocator) !void {
var buffer: [maxLineLength]u8 = undefined;
const writer = out.writer(); const writer = out.writer();
const reader = in.reader(); const reader = in.reader();
while (true) { var it = lineIterator(reader, allocator);
const input = try nextLine(reader, &buffer); while (it.next()) |line| {
if (input) |line| { defer allocator.free(line);
try writer.print("{s}\n", .{ line });
} else { try writer.print("{s}\n", .{ windowsSafe(line) });
break;
}
} }
} }
fn nextLine(reader: FileReader, buffer: []u8) !?[]const u8 { fn lineIterator(reader: fs.File.Reader, allocator: mem.Allocator) LineIterator {
var line: []u8 = (try reader.readUntilDelimiterOrEof( return LineIterator {
buffer, .reader = io.bufferedReader(reader),
'\n', .delimiter = '\n',
)) orelse return null; .allocator = allocator
return windowsSafe(line); };
} }
const LineIterator = struct {
reader: std.io.BufferedReader(4096, fs.File.Reader),
delimiter: u8,
allocator: mem.Allocator,
const Self = @This();
/// Caller owns returned memory
pub fn next(self: *Self) ?[]u8 {
return self.reader.reader().readUntilDelimiterOrEofAlloc(self.allocator, self.delimiter, 4096) catch null;
}
};
// trim annoying windows-only carriage return character // trim annoying windows-only carriage return character
fn windowsSafe(line: []const u8) []const u8 { fn windowsSafe(line: []const u8) []const u8 {
if (os.tag == .windows) { if (os.tag == .windows) {