Skip to content

Instantly share code, notes, and snippets.

@charles-l
Last active May 7, 2020 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charles-l/40c8c3ece0ed393181c1a54a505fa7d3 to your computer and use it in GitHub Desktop.
Save charles-l/40c8c3ece0ed393181c1a54a505fa7d3 to your computer and use it in GitHub Desktop.
Small hexdump utility written in zig to test the language out a bit.
const std = @import("std");
pub const BlockIterator = struct {
buffer: []const u8,
block_size: usize,
index: usize,
pub fn next(self: *BlockIterator) ?[]const u8 {
if (self.index == self.buffer.len) {
return null;
}
var j: i32 = 0;
const start = self.index;
while(self.index < self.buffer.len and j < self.block_size) {
self.index += 1;
j += 1;
}
return self.buffer[start..self.index];
}
};
pub fn iter_blocks(buffer: []const u8, block_size: usize) BlockIterator {
return BlockIterator {
.index = 0,
.buffer = buffer,
.block_size = block_size
};
}
pub fn main() !void {
const args = try std.process.argsAlloc(std.heap.page_allocator);
defer std.process.argsFree(std.heap.page_allocator, args);
const file = try std.fs.cwd().openFile(args[1], .{});
defer file.close();
var buf: [1024]u8 = undefined;
while(true) {
var bytes_read = try file.read(&buf);
var blocks = iter_blocks(buf[0..bytes_read], 16);
while (blocks.next()) |block| {
for (block) |b| {
std.debug.warn("{X:02} ", .{b});
}
std.debug.warn(" ", .{});
for (block) |b| {
if(0x20 <= b and b <= 0x7E) {
std.debug.warn("{c}", .{b});
} else {
std.debug.warn(".", .{});
}
}
std.debug.warn("\n", .{});
}
if(bytes_read < buf.len) {
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment