From 7197bf33bf2ceefa583f346ca60c9b09d035baed Mon Sep 17 00:00:00 2001 From: owl Date: Sat, 14 Oct 2023 01:57:30 +0200 Subject: [PATCH] little cleanups --- src/main.zig | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main.zig b/src/main.zig index e0ead5f..db400e2 100644 --- a/src/main.zig +++ b/src/main.zig @@ -21,8 +21,8 @@ var cat = struct { // data var input_buffer: [0x1_000]u8 = undefined; -const color_map_entries = 360; -var color_map_data: [color_map_entries * entry_len]u8 = undefined; +const num_color_entries = 360; +var color_data: [num_color_entries * entry_len]u8 = undefined; const color_fmt = "\x1b[38;2;{d:0>3};{d:0>3};{d:0>3}m"; const entry_len: usize = @intCast(std.fmt.count(color_fmt, .{ 255, 255, 255 })); @@ -52,12 +52,12 @@ fn init() !void { cat.max_width = @max(termsz.ws_col, 2) - 1; } - cat.pos.mod = @intCast(color_map_entries / cat.freq); + cat.pos.mod = @intCast(num_color_entries / cat.freq); for (0..cat.pos.mod) |i| { const col = colorForIndex(i); _ = try std.fmt.bufPrint( - color_map_data[i * entry_len ..], + color_data[i * entry_len ..], color_fmt, .{ color.crudeIntFromF32(u8, col.r), @@ -89,7 +89,7 @@ pub fn main() !void { if (res.args.chroma) |c| cat.chroma = math.clamp(c, 0.0, 150.0); if (res.args.frequency) |f| - cat.freq = math.clamp(f, 1, color_map_entries - 1); + cat.freq = math.clamp(f, 1, num_color_entries - 1); if (res.args.start) |s| cat.pos.y = s; if (res.args.color == 0 and !std.io.getStdOut().isTty()) @@ -108,11 +108,11 @@ fn lolcat(files: []const []const u8) !void { const stdout = bw.writer(); if (cat.use_color) { - @prefetch(&color_map_data, .{ .rw = .write }); + @prefetch(&color_data, .{ .rw = .write }); try init(); } - @prefetch(&color_map_data, .{ .rw = .read }); + @prefetch(&color_data, .{ .rw = .read }); if (0 < files.len) { for (files) |fname| { var f = try std.fs.cwd().openFile(fname, .{}); @@ -174,14 +174,15 @@ fn writeGayBytesFromReader(allocator: std.mem.Allocator, writer: anytype, reader var sgi = try StreamingGraphemeIterator(@TypeOf(reader)).init(allocator, reader); while (try sgi.next()) |sl| { + defer allocator.free(sl); + if (isNewLine(sl)) { cat.pos.x = 0; cat.pos.y +%= 1; try writer.writeAll(sl); } else { const i = @mod(cat.pos.x +% cat.pos.y, cat.pos.mod); - const si = entry_len * i; - const s = color_map_data[si .. si + entry_len]; + const s = getColorSliceForIndex(i); const w = strWidth(sl, amb_opt) catch 1; const nx = cat.pos.x +% w; @@ -193,11 +194,14 @@ fn writeGayBytesFromReader(allocator: std.mem.Allocator, writer: anytype, reader cat.pos.y +%= 1; } else cat.pos.x = nx; } - - allocator.free(sl); } } +inline fn getColorSliceForIndex(ix: usize) []const u8 { + const start = ix * entry_len; + return color_data[start .. start + entry_len]; +} + inline fn isNewLine(sl: []const u8) bool { // ziglyph fails instead of returning empty slices @setRuntimeSafety(false); -- 2.45.2