add zigzag coding #3

merged
opened by altagos.dev targeting main from push-xmxnlpnsnyqo
Changed files
+38
src
+37
src/ZigZag.zig
···
+
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);
+
}
+1
src/root.zig
···
const std = @import("std");
pub const Golomb = @import("Golomb.zig");
+
pub const ZigZag = @import("ZigZag.zig");
test {
std.testing.refAllDecls(@This());