···
1
+
pub fn encode(value: isize) usize {
2
+
if (value < 0) return @as(usize, @intCast(value * -1)) * 2 - 1;
3
+
return @as(usize, @intCast(value)) * 2;
6
+
pub fn decode(value: usize) isize {
7
+
if (value & 1 == 1) return -@as(isize, @intCast(value / 2)) - 1;
8
+
return @as(isize, @intCast(value / 2));
11
+
test "zigzag.encode val = 10" {
12
+
const testing = @import("std").testing;
14
+
const encoded = encode(10);
15
+
try testing.expectEqual(20, encoded);
18
+
test "zigzag.encode val = -42" {
19
+
const testing = @import("std").testing;
21
+
const encoded = encode(-42);
22
+
try testing.expectEqual(83, encoded);
25
+
test "zigzag.decode val = 20" {
26
+
const testing = @import("std").testing;
28
+
const decoded = decode(20);
29
+
try testing.expectEqual(10, decoded);
32
+
test "zigzag.decode val = 83" {
33
+
const testing = @import("std").testing;
35
+
const decoded = decode(83);
36
+
try testing.expectEqual(-42, decoded);