From 2f9ca7fd8ec5a76b927485492150b637478dfe7a Mon Sep 17 00:00:00 2001 From: Peterino Date: Thu, 19 Nov 2026 16:58:38 -0700 Subject: [PATCH] new xxd2 implementation total rewrite of xxd to the new implementation, it should be a bit more performant and use less memory. but more importantly allows base addresses. --- engine/lib/p2/src/structures/xxd.zig | 254 +++++++++++++++++------ engine/lib/p2/src/test.zig | 43 ++++ engine/lib/slugger/src/sluggerformat.zig | 11 + 3 files changed, 244 insertions(+), 64 deletions(-) create mode 100644 engine/lib/p2/src/test.zig diff --git a/engine/lib/p2/src/structures/xxd.zig b/engine/lib/p2/src/structures/xxd.zig index de79ca1..57bcb43 100644 --- a/engine/lib/p2/src/structures/xxd.zig +++ b/engine/lib/p2/src/structures/xxd.zig @@ -6,14 +6,16 @@ pub const Endian = enum { }; pub const XxdOptions = struct { - wordSize: u32 = 8, // bits; must be a nonzero multiple of 8 + wordSize: u32 = 8, // bits; must be a nonzero multiple of 8 , deprecated // Preserve the existing convention: little prints bytes in input order; // big reverses the bytes within each word. ASCII always uses input order. endian: Endian = .little, wordsPerGroup: u32 = 2, + showHeader: bool = true, groupsPerLine: u32 = 8, groupSplit: u32 = 4, // extra space every N groups; 0 disables it showAddress: bool = true, + baseAddress: u64 = 0, showAscii: bool = false, color: bool = true, // if true uses an ascii color code }; @@ -31,6 +33,8 @@ const ColorOp = struct { color: Color = .default, count: u32 = 0, + pub const reset = @This(){ .count = 0, .color = .default }; + pub fn colorAscii(self: @This()) []const u8 { switch (self.color) { .default => return "\x1b[0m", @@ -59,87 +63,192 @@ pub fn cursorProceed(opCursor: *usize, opCount: *usize, ops: []const ColorOp) vo } } -/// Writes a hex dump. Does not allocate or flush the caller's writer. -pub fn xxdWrite(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) !void { - if (options.wordSize == 0 or options.wordSize % 8 != 0 or options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions; - const bytes_per_word: usize = options.wordSize / 8; - const words_per_line = std.math.mul(usize, options.wordsPerGroup, options.groupsPerLine) catch return error.InvalidOptions; - const bytes_per_line = std.math.mul(usize, bytes_per_word, words_per_line) catch return error.InvalidOptions; +fn getNextLine(start: *usize, stride: usize, bytes: []const u8) ?[]const u8 { + if (start.* >= bytes.len) + return null; - var ops: [256]ColorOp = undefined; + const s = bytes[start.*..@min(stride + start.*, bytes.len)]; + start.* += stride; - var offset: usize = 0; - while (offset < bytes.len) { - const row = bytes[offset..][0..@min(bytes_per_line, bytes.len - offset)]; + return s; +} - // read ahead for the rest of the length - var cra: usize = 0; // color read-ahead - var opscount: usize = 0; - var active = &ops[opscount]; - active.* = .{}; - while (cra < row.len) : (cra += 1) { - const color = getColorFromByte(row[cra]); - if (color == active.color) { - active.count += 1; - } else { - if (active.count != 0) - opscount += 1; - active = &ops[opscount]; - active.color = color; - active.count = 1; +pub fn xxdWrite2(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) !void { + if (options.wordSize % 8 != 0 or options.wordSize == 0) return error.WordSizeNotByteAlignedUnsupported; + + if (options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions; + + const bytesPerWord = options.wordSize / 8; + const bytesPerLine = options.wordsPerGroup * options.groupsPerLine / bytesPerWord; + + const leadingNulls = options.baseAddress % bytesPerLine; + const displayBase = options.baseAddress - leadingNulls; + + var opsBuffer: [64]ColorOp = undefined; + var ops: std.ArrayList(ColorOp) = .initBuffer(&opsBuffer); + + var lineBuffer: [64]?u8 = undefined; + var lineBytes: std.ArrayList(?u8) = .initBuffer(&lineBuffer); + + var start: usize = 0; + var pad = leadingNulls; + // std.debug.print("leadingnulls {d} options.baseAddress {d} % {d}\n", .{ pad, options.baseAddress, bytesPerLine }); + var stride: usize = bytesPerLine - leadingNulls; + var addr = displayBase; + + const addrLen: usize = r: { + if (options.baseAddress < std.math.maxInt(u32)) + break :r 8 + 2; + break :r 8 + 8 + 1 + 2; + }; + + _ = try writer.splatByte(' ', addrLen); + + { + var word: usize = 0; + var group: usize = 0; + for (0..bytesPerLine) |i| { + if (word != 0 and word % options.wordsPerGroup == 0) { + try writer.writeByte(' '); + if (group != 0 and group % options.groupSplit == 0) + try writer.writeByte(' '); + } + if (i % bytesPerWord == 0) word += 1; + if (word % options.wordsPerGroup == 0) group += 1; + try writeByteAsHex2(@intCast(i), writer, true); + } + } + try writer.writeByte('\n'); + + while (getNextLine(&start, stride, bytes)) |s| { + stride = bytesPerLine; + ops.clearRetainingCapacity(); + lineBytes.clearRetainingCapacity(); + + // build working buffers for the line + if (pad != 0) { + lineBytes.appendNTimesAssumeCapacity(null, pad); + pad = 0; + } + + if (bytesPerWord != 1) { + return error.NotImplementedYet; + } else { + // dead simple here, just write to the buffer + for (s) |b| { + lineBytes.appendAssumeCapacity(b); } } - opscount += 1; - if (options.showAddress) try writer.print("{x:0>8}: ", .{offset}); - const word_count = if (options.showAscii) words_per_line else (row.len - 1) / bytes_per_word + 1; + { + var op: ColorOp = .{ .color = .default }; + for (lineBytes.items) |mb| { + const newOp = getop: { + if (mb) |b| { + break :getop getColorFromByte(b); + } + break :getop .black; + }; + if (newOp != op.color) { + if (op.count > 0) { + ops.appendAssumeCapacity(op); + } + op.color = newOp; + op.count = 0; + } + op.count += 1; + } + + if (op.count > 0) { + ops.appendAssumeCapacity(op); + } + } + + // render address + if (options.baseAddress > std.math.maxInt(u32)) { + try writer.print("{x:0>8}_", .{addr >> 32}); + try writer.print("{x:0>8}: ", .{addr & 0xffffffff}); + } else { + try writer.print("{x:0>8}: ", .{addr}); + } + + // render byteline var opCursor: usize = 0; - var opCount: usize = ops[opCursor].count; + try writer.writeAll(ops.items[opCursor].colorAscii()); - for (0..word_count) |word_index| { - if (word_index > 0 and word_index % options.wordsPerGroup == 0) { - try writer.writeByte(' '); - const group_index = word_index / options.wordsPerGroup; - if (options.groupSplit != 0 and group_index % options.groupSplit == 0) { + { + var word: usize = 0; + var group: usize = 0; + var op = ops.items[opCursor]; + + for (lineBytes.items, 0..) |b, i| { + if (word != 0 and word % options.wordsPerGroup == 0) { try writer.writeByte(' '); + if (group != 0 and group % options.groupSplit == 0) + try writer.writeByte(' '); + } + + if (i % bytesPerWord == 0) word += 1; + if (word % options.wordsPerGroup == 0) group += 1; + + if (op.count == 0) { + opCursor += 1; + op = ops.items[opCursor]; + try writer.writeAll(ops.items[opCursor].colorAscii()); + } + if (b) |x| { + try writeByteAsHex2(x, writer, false); + } else { + try writer.writeAll(".."); + } + // std.debug.print("{any}\n", .{ops.items[opCursor]}); + op.count -= 1; + } + + if (lineBytes.items.len < bytesPerLine) { + for (lineBytes.items.len..bytesPerLine) |i| { + if (word != 0 and word % options.wordsPerGroup == 0) { + try writer.writeByte(' '); + if (group != 0 and group % options.groupSplit == 0) + try writer.writeByte(' '); + } + + if (i % bytesPerWord == 0) word += 1; + if (word % options.wordsPerGroup == 0) group += 1; + + try writer.writeAll(" "); } } - const start = @min(word_index * bytes_per_word, row.len); - const word = row[start..][0..@min(bytes_per_word, row.len - start)]; - for (0..word.len) |i| { - const index = if (options.endian == .little) i else word.len - 1 - i; - if (opCursor >= opscount) return { - return error.WhatTheFucl; - }; - try writeByteAsHex(word[index], writer, options, ops[opCursor]); - cursorProceed(&opCursor, &opCount, &ops); - } - if (options.showAscii) { - // Pad missing bytes so every row's ASCII starts in the same column. - for (word.len..bytes_per_word) |_| try writer.writeAll(" "); - } } - if (options.showAscii) { + // render ascii sidecar + { opCursor = 0; - opCount = ops[opCursor].count; - - try writer.writeAll("\x1b[0m"); - try writer.writeAll(" | "); - for (row) |byte| { - try writer.writeAll(ops[opCursor].colorAscii()); - try writer.writeByte(if (byte >= 0x20 and byte <= 0x7e) byte else getUnprintableByte(byte)); - cursorProceed(&opCursor, &opCount, &ops); + var op = ops.items[opCursor]; + try writer.writeAll(ColorOp.reset.colorAscii()); + try writer.writeAll(" |"); + for (lineBytes.items, 0..) |mb, i| { + const b = mb orelse ' '; + _ = i; + if (op.count == 0) { + opCursor += 1; + op = ops.items[opCursor]; + try writer.writeAll(ops.items[opCursor].colorAscii()); + } + try writer.writeByte(if (b >= 0x20 and b <= 0x7e) b else getUnprintableByte(b)); + op.count -= 1; } - try writer.writeAll("\x1b[0m"); - try writer.writeAll(" | "); } - - try writer.writeByte('\n'); - offset += row.len; + try writer.writeAll(ColorOp.reset.colorAscii()); + try writer.writeAll("|\n"); + addr += stride; } } +inline fn writeByteAsHex2(byte: u8, writer: *std.Io.Writer, lower: bool) std.Io.Writer.Error!void { + const digits = if (lower) "0123456789abcdef" else "0123456789ABCDEF"; + try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] }); +} fn getUnprintableByte(byte: u8) u8 { return switch (byte) { @@ -151,7 +260,8 @@ fn getUnprintableByte(byte: u8) u8 { pub fn xxdWriteAscii(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) !void { var ascii_options = options; ascii_options.showAscii = true; - try xxdWrite(writer, bytes, ascii_options); + + try xxdWrite2(writer, bytes, ascii_options); } inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions, op: ColorOp) std.Io.Writer.Error!void { @@ -162,3 +272,19 @@ inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions, try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] }); } + +/// warning, needs 64k on your stack +pub fn debug_printBytes(bytes: []const u8, options: XxdOptions) void { + var workBuffer: [64 * 1024]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&workBuffer); + + var frame = std.Io.Writer.Allocating.init(fba.allocator()); + xxdWriteAscii(&frame.writer, bytes, options) catch { + std.debug.print("xxd write failed bytes len {d}", .{bytes.len}); + }; + std.debug.print("{s}", .{frame.written()}); +} + +pub inline fn print(bytes: []const u8, baseAddress: usize) void { + debug_printBytes(bytes, XxdOptions{ .baseAddress = baseAddress }); +} diff --git a/engine/lib/p2/src/test.zig b/engine/lib/p2/src/test.zig new file mode 100644 index 0000000..0d7de64 --- /dev/null +++ b/engine/lib/p2/src/test.zig @@ -0,0 +1,43 @@ +const Engine = struct {}; + +pub fn println(comptime fmt: []const u8, args: anytype) void { + std.debug.print(fmt ++ "\n", .{args}); +} + +pub fn printlns(comptime fmt: []const u8) void { + std.debug.print(fmt ++ "\n", .{}); +} + +const MyEngineSystem = struct { + pub fn init(self: *@This(), engineContext: *Engine) !void { + _ = self; + _ = engineContext; + println("initialized", .{}); + } + + pub fn tick(self: *@This(), dt: f32) void { + _ = self; + printlns("tick!"); + _ = dt; + } + + pub fn deinit(self: *@This()) void { + _ = self; + + printlns("deinitialized"); + } +}; + +const Vec2 = struct { + x: f32 = 0, + y: f32 = 0, +}; + +const Vec2d = struct { + x: f32 = 0, + y: f32 = 0, +}; + +test "testing" {} + +const std = @import("std"); diff --git a/engine/lib/slugger/src/sluggerformat.zig b/engine/lib/slugger/src/sluggerformat.zig index a1f0672..a3eae98 100644 --- a/engine/lib/slugger/src/sluggerformat.zig +++ b/engine/lib/slugger/src/sluggerformat.zig @@ -274,7 +274,15 @@ const SlugOutput = struct { } for (self.mem.entries.items) |entry| { + const start = frame.written().len; + try entry.marshalToWriter(&frame.writer); + + const end = frame.written().len; + + xxd.print(frame.written()[start..end], start + 2); + std.debug.print("\n", .{}); + self.entriesWritten += 1; } @@ -577,5 +585,8 @@ const ArgsDecoderOp = slugger.ArgsDecoderOp; const ArgsDecoderOpKind = slugger.ArgsDecoderOpKind; const RenderOp = slugger.RenderOp; const StructuredLog = slugger.StructuredLog; + +const xxd = @import("p2").xxd; +const debug_printBytes = xxd.debug_printBytes; const lz4 = @import("lz4"); const Lz4Writer = lz4.Lz4Writer;