diff --git a/src/ZigZag.zig b/src/ZigZag.zig new file mode 100644 index 0000000..498237f --- /dev/null +++ b/src/ZigZag.zig @@ -0,0 +1,37 @@ +pub fn encode(value: isize) usize { + if (value < 0) return @as(usize, @intCast(value * -1)) * 2 - 1; + return @as(usize, @intCast(value)) * 2; +} + +pub fn decode(value: usize) isize { + if (value & 1 == 1) return -@as(isize, @intCast(value / 2)) - 1; + return @as(isize, @intCast(value / 2)); +} + +test "zigzag.encode val = 10" { + const testing = @import("std").testing; + + const encoded = encode(10); + try testing.expectEqual(20, encoded); +} + +test "zigzag.encode val = -42" { + const testing = @import("std").testing; + + const encoded = encode(-42); + try testing.expectEqual(83, encoded); +} + +test "zigzag.decode val = 20" { + const testing = @import("std").testing; + + const decoded = decode(20); + try testing.expectEqual(10, decoded); +} + +test "zigzag.decode val = 83" { + const testing = @import("std").testing; + + const decoded = decode(83); + try testing.expectEqual(-42, decoded); +} diff --git a/src/root.zig b/src/root.zig index 15e922a..b5afa98 100644 --- a/src/root.zig +++ b/src/root.zig @@ -2,6 +2,7 @@ const std = @import("std"); pub const Golomb = @import("Golomb.zig"); +pub const ZigZag = @import("ZigZag.zig"); test { std.testing.refAllDecls(@This());