From 1e6a350c3922eeb9c79ac14453399b6cab5a0b66 Mon Sep 17 00:00:00 2001 From: Altagos Date: Fri, 5 Sep 2025 10:27:39 +0200 Subject: [PATCH] add zigzag coding Change-Id: qvzvqruqmuwqywnwrsuoykzsmmnvpuxy --- src/ZigZag.zig | 37 +++++++++++++++++++++++++++++++++++++ src/root.zig | 1 + 2 files changed, 38 insertions(+) create mode 100644 src/ZigZag.zig 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()); -- 2.43.0