Zig NEWS

Cover image for pretty, a pretty printer for deeply nested structures in Zig
Timur Fayzrakhmanov
Timur Fayzrakhmanov

Posted on

pretty, a pretty printer for deeply nested structures in Zig

I'm excited* to publish my first Zig project – pretty, a simple pretty printer for inspecting complex and deeply-nested data structures.

I developed it as part of my language project to inspect complex trees (AST). Later on, I realized how useful it is on its own. So, I spent a couple of months honing it. With various printing options, you can almost "query" the things you want to see in your data. While it doesn't yet support every type for laying out things nicely, I believe I covered the most important ones. Feel free to check it out!

Here is the demo (excerpt from the repo):


simplified version of src/demo.zig:

// main.zig
const std = @import("std");
const pretty = @import("pretty.zig");
const alloc = std.heap.page_allocator;

pub fn main() !void {
    const array = [3]u8{ 4, 5, 6 };

    // method 1: print with default options
    try pretty.print(alloc, array, .{});

    // method 2: customize your print
    try pretty.print(alloc, array, .{
        .arr_show_item_idx = false,
        .arr_max_len = 2,
    });

    // method 3: don't print, get a string!
    var out = try pretty.dump(alloc, array, .{});
    defer alloc.free(out);
    std.debug.print("{s}..\n", .{out[0..5]});
}
Enter fullscreen mode Exit fullscreen mode

output:

$ zig run main.zig
[3]u8
  0: 4
  1: 5
  2: 6

[3]u8
  4
  5

[3]u8..
Enter fullscreen mode Exit fullscreen mode

*Zig's Discord server and ziggit.dev forum helped me immensely to get through the hard times of learning Zig. The effort I put into making the utility I use myself reusable for others is my humble way of saying thank you to the community. Plus, I made my first donation today. So, thank you guys a lot!

Top comments (4)

Collapse
 
liyu1981 profile image
LI Yu

Thanks for sharing this! It will be very useful when write tests, or do printing debugging. And by reading it, I just discovered the excellent std.meta namespace, so many useful functions over there.

Collapse
 
htqx profile image
thanks you see

no color?

Collapse
 
msw profile image
Martin

I for one am thankful for the lacking support of this feature; this would mean supporting color schemes as well and a way to streamline the user's custom printing and the library's printing; IMO: immediately messy.

Collapse
 
rabbit profile image
pylang

Distinguishing the color display is just icing on the cake.