Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created August 22, 2025 12:26
Show Gist options
  • Select an option

  • Save peterhellberg/f797e09d8f4154624eb10da0781be55e to your computer and use it in GitHub Desktop.

Select an option

Save peterhellberg/f797e09d8f4154624eb10da0781be55e to your computer and use it in GitHub Desktop.

Revisions

  1. peterhellberg created this gist Aug 22, 2025.
    46 changes: 46 additions & 0 deletions counter.zig
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    const std = @import("std");

    pub fn main() !void {
    var a = Counter(u32){};
    var b = Counter(i32){ .value = 41 };

    a.count.increment();
    b.count.increment();

    std.debug.print("a: {}\tb: {}\n", .{ a.value, b.value });

    a.count.reset();
    a.count.decrement();

    b.count.reset();
    b.count.decrement();

    std.debug.print("a: {}\tb: {}\n", .{ a.value, b.value });
    }

    pub fn Counter(comptime T: type) type {
    return struct {
    value: T = 0,
    count: Mixin(@This()) = .{},
    };
    }

    pub fn Mixin(comptime T: type) type {
    return struct {
    pub fn increment(m: *@This()) void {
    m.parent().value +|= 1;
    }

    pub fn decrement(m: *@This()) void {
    m.parent().value -|= 1;
    }

    pub fn reset(m: *@This()) void {
    m.parent().value = 0;
    }

    fn parent(m: *@This()) *T {
    return @alignCast(@fieldParentPtr("count", m));
    }
    };
    }