tadpole/engine/pkg/xxd/xxd.zig

319 lines
10 KiB
Zig

const std = @import("std");
pub const Endian = enum {
big,
little,
};
pub const XxdOptions = struct {
wordSize: u32 = 8, // value is in bits... but maybe its better if it's in bytes?
endian: Endian = .little, // .big will reverse each word
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
};
const Color = enum {
default,
black,
red,
green,
yellow,
blue,
};
const ColorOp = struct {
color: Color = .default,
count: u32 = 0,
pub const reset = @This(){ .count = 0, .color = .default };
pub const green = @This(){ .count = 0, .color = .green };
pub fn colorAscii(self: @This()) []const u8 {
switch (self.color) {
.default => return "\x1b[0m",
.black => return "\x1b[0;30m",
.red => return "\x1b[0;31m",
.green => return "\x1b[0;32m",
.yellow => return "\x1b[0;33m",
.blue => return "\x1b[0;34m",
}
}
};
pub fn getColorFromByte(byte: u8) Color {
return switch (byte) {
0x0 => return .red,
0x20...0x7E => return .blue,
else => .default,
};
}
pub fn cursorProceed(opCursor: *usize, opCount: *usize, ops: []const ColorOp) void {
opCount.* -= 1;
if (opCount.* == 0) {
opCursor.* += 1;
opCount.* = ops[opCursor.*].count;
}
}
fn getNextLine(start: *usize, stride: usize, bytes: []const u8) ?[]const u8 {
if (start.* >= bytes.len)
return null;
const s = bytes[start.*..@min(stride + start.*, bytes.len)];
start.* += stride;
return s;
}
pub fn xxdWrite(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;
const op = if (i % 2 == 0) ColorOp.reset else ColorOp.green;
if (options.color)
try writer.writeAll(op.colorAscii());
try writeByteAsHex2(@intCast(i), writer, true);
}
if (options.color)
try writer.writeAll(ColorOp.reset.colorAscii());
}
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);
}
}
{
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;
if (options.color) {
try writer.writeAll(ops.items[opCursor].colorAscii());
}
{
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];
if (options.color)
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(" ");
}
}
}
// render ascii sidecar
{
opCursor = 0;
var op = ops.items[opCursor];
if (options.color)
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];
if (options.color)
try writer.writeAll(ops.items[opCursor].colorAscii());
}
try writer.writeByte(if (b >= 0x20 and b <= 0x7e) b else getUnprintableByte(b));
op.count -= 1;
}
if (options.color)
try writer.writeAll(ColorOp.reset.colorAscii());
if (lineBytes.items.len < bytesPerLine) {
_ = try writer.splatByte(' ', bytesPerLine - lineBytes.items.len);
}
}
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) {
0 => return '~',
else => return '.',
};
}
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);
}
inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer, options: XxdOptions, op: ColorOp) std.Io.Writer.Error!void {
const digits = "0123456789ABCDEF";
if (options.color)
try writer.writeAll(op.colorAscii());
try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] });
}
/// std.debug helper functions
/// warning! needs 64k on your stack
pub fn 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 show(bytes: []const u8) void {
printBytes(bytes, XxdOptions{ .baseAddress = 0 });
}
pub inline fn print(bytes: []const u8, baseAddress: usize) void {
printBytes(bytes, XxdOptions{ .baseAddress = baseAddress });
}
pub inline fn printStruct(s: anytype) void {
std.debug.print("{s}: size:{d} bytes\n\n", .{ @typeName(@TypeOf(s)), @sizeOf(@TypeOf(s)) });
print(std.mem.asBytes(&s), 0);
}