+37
src/ZigZag.zig
+37
src/ZigZag.zig
···
···
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;
4
+
}
5
+
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));
9
+
}
10
+
11
+
test "zigzag.encode val = 10" {
12
+
const testing = @import("std").testing;
13
+
14
+
const encoded = encode(10);
15
+
try testing.expectEqual(20, encoded);
16
+
}
17
+
18
+
test "zigzag.encode val = -42" {
19
+
const testing = @import("std").testing;
20
+
21
+
const encoded = encode(-42);
22
+
try testing.expectEqual(83, encoded);
23
+
}
24
+
25
+
test "zigzag.decode val = 20" {
26
+
const testing = @import("std").testing;
27
+
28
+
const decoded = decode(20);
29
+
try testing.expectEqual(10, decoded);
30
+
}
31
+
32
+
test "zigzag.decode val = 83" {
33
+
const testing = @import("std").testing;
34
+
35
+
const decoded = decode(83);
36
+
try testing.expectEqual(-42, decoded);
37
+
}
+1
src/root.zig
+1
src/root.zig