1/Hejsil/mecha v0.11


Mecha

A parser combinator library for the Zig programming language. Time to make your own parser mech! mech

const mecha = @import("mecha");
const std = @import("std");

const Rgb = struct {
    r: u8,
    g: u8,
    b: u8,
};

fn toByte(v: u4) u8 {
    return @as(u8, v) * 0x10 + v;
}

const hex1 = mecha.map(u8, toByte, mecha.int(u4, .{
    .parse_sign = false,
    .base = 16,
    .max_digits = 1,
}));
const hex2 = mecha.int(u8, .{
    .parse_sign = false,
    .base = 16,
    .max_digits = 2,
});
const rgb1 = mecha.map(Rgb, mecha.toStruct(Rgb), mecha.manyN(hex1, 3, .{}));
const rgb2 = mecha.map(Rgb, mecha.toStruct(Rgb), mecha.manyN(hex2, 3, .{}));
const rgb = mecha.combine(.{
    mecha.ascii.char('#'),
    mecha.oneOf(.{
        rgb2,
        rgb1,
    }),
});

test "rgb" {
    const testing = std.testing;
    const allocator = testing.allocator;
    const a = (try rgb(allocator, "#aabbcc")).value;
    try testing.expectEqual(@as(u8, 0xaa), a.r);
    try testing.expectEqual(@as(u8, 0xbb), a.g);
    try testing.expectEqual(@as(u8, 0xcc), a.b);

    const b = (try rgb(allocator, "#abc")).value;
    try testing.expectEqual(@as(u8, 0xaa), b.r);
    try testing.expectEqual(@as(u8, 0xbb), b.g);
    try testing.expectEqual(@as(u8, 0xcc), b.b);

    const c = (try rgb(allocator, "#000000")).value;
    try testing.expectEqual(@as(u8, 0), c.r);
    try testing.expectEqual(@as(u8, 0), c.g);
    try testing.expectEqual(@as(u8, 0), c.b);

    const d = (try rgb(allocator, "#000")).value;
    try testing.expectEqual(@as(u8, 0), d.r);
    try testing.expectEqual(@as(u8, 0), d.g);
    try testing.expectEqual(@as(u8, 0), d.b);
}

Package Contents

  • example/rgb.zig
  • example/json.zig
  • example/README.md.template
  • gyro.zzz
  • .gitattributes
  • mecha.zig
  • LICENSE
  • .github/workflows/ci.yml
  • .github/dependabot.yml
  • .github/FUNDING.yml
  • build.zig
  • src/ascii.zig
  • src/utf8.zig
  • README.md
  • zig.mod
  • .gitignore

History

Published On Tree @ Commit Size
v0.11 Sun, 20 Nov 2022 10:00:57 UTC Tree 82.824 KB
v0.10 Wed, 16 Nov 2022 12:11:56 UTC Tree 82.833 KB
v0.9 Wed, 16 Nov 2022 10:18:31 UTC Tree 82.523 KB
v0.8 Tue, 08 Nov 2022 12:48:38 UTC Tree 82.502 KB
v0.7 Thu, 15 Sep 2022 11:45:25 UTC Tree 82.502 KB
v0.6 Tue, 23 Aug 2022 15:47:27 UTC Tree 82.419 KB
v0.5 Fri, 29 Jul 2022 12:12:52 UTC Tree 82.371 KB
v0.4 Tue, 31 May 2022 08:09:48 UTC Tree 82.362 KB
v0.3 Wed, 02 Mar 2022 16:55:39 UTC Tree 82.357 KB
v0.2 Thu, 17 Feb 2022 14:59:09 UTC Tree 82.365 KB
v0.1 Thu, 03 Feb 2022 20:53:48 UTC Tree 82.299 KB