| ... | @@ -3,12 +3,17 @@ const io = std.io; | ... | @@ -3,12 +3,17 @@ const io = std.io; |
| 3 | const process = std.process; | 3 | const process = std.process; |
| 4 | const fs = std.fs; | 4 | const fs = std.fs; |
| 5 | const mem = std.mem; | 5 | const mem = std.mem; |
| 6 | const warn = std.debug.warn; | 6 | const warn = std.log.warn; |
| 7 | const allocator = std.testing.allocator; | 7 | |
| | 8 | var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; |
| | 9 | const allocator = &general_purpose_allocator.allocator; |
| 8 | | 10 | |
| 9 | pub fn main() !void { | 11 | pub fn main() !void { |
| | 12 | defer _ = general_purpose_allocator.deinit(); |
| | 13 | |
| 10 | var args_it = process.args(); | 14 | var args_it = process.args(); |
| 11 | const exe = try unwrapArg(args_it.next(allocator).?); | 15 | const exe = try unwrapArg(args_it.next(allocator).?); |
| | 16 | defer allocator.free(exe); |
| 12 | var catted_anything = false; | 17 | var catted_anything = false; |
| 13 | const stdout_file = io.getStdOut(); | 18 | const stdout_file = io.getStdOut(); |
| 14 | | 19 | |
| ... | @@ -16,6 +21,7 @@ pub fn main() !void { | ... | @@ -16,6 +21,7 @@ pub fn main() !void { |
| 16 | | 21 | |
| 17 | while (args_it.next(allocator)) |arg_or_err| { | 22 | while (args_it.next(allocator)) |arg_or_err| { |
| 18 | const arg = try unwrapArg(arg_or_err); | 23 | const arg = try unwrapArg(arg_or_err); |
| | 24 | defer allocator.free(arg); |
| 19 | if (mem.eql(u8, arg, "-")) { | 25 | if (mem.eql(u8, arg, "-")) { |
| 20 | catted_anything = true; | 26 | catted_anything = true; |
| 21 | try cat_file(stdout_file, io.getStdIn()); | 27 | try cat_file(stdout_file, io.getStdIn()); |
| ... | @@ -44,23 +50,12 @@ fn usage(exe: []const u8) !void { | ... | @@ -44,23 +50,12 @@ fn usage(exe: []const u8) !void { |
| 44 | | 50 | |
| 45 | // TODO use copy_file_range | 51 | // TODO use copy_file_range |
| 46 | fn cat_file(stdout: fs.File, file: fs.File) !void { | 52 | fn cat_file(stdout: fs.File, file: fs.File) !void { |
| 47 | var buf: [1024 * 4]u8 = undefined; | 53 | var fifo = std.fifo.LinearFifo(u8, .{ .Static = 1024 * 4 }).init(); |
| 48 | | | |
| 49 | while (true) { | | |
| 50 | const bytes_read = file.read(buf[0..]) catch |err| { | | |
| 51 | warn("Unable to read from stream: {}\n", .{@errorName(err)}); | | |
| 52 | return err; | | |
| 53 | }; | | |
| 54 | | | |
| 55 | if (bytes_read == 0) { | | |
| 56 | break; | | |
| 57 | } | | |
| 58 | | 54 | |
| 59 | stdout.writeAll(buf[0..bytes_read]) catch |err| { | 55 | fifo.pump(file.reader(), stdout.writer()) catch |err| { |
| 60 | warn("Unable to write to stdout: {}\n", .{@errorName(err)}); | 56 | warn("Unable to read from stream or write to stdout: {}\n", .{@errorName(err)}); |
| 61 | return err; | 57 | return err; |
| 62 | }; | 58 | }; |
| 63 | } | | |
| 64 | } | 59 | } |
| 65 | | 60 | |
| 66 | fn unwrapArg(arg: anyerror![]u8) ![]u8 { | 61 | fn unwrapArg(arg: anyerror![]u8) ![]u8 { |