1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4
5pub fn sliceToInt(comptime T: type, comptime E: type, slice: []const E) !T {
6 const a = @typeInfo(T).int.bits;
7 const b = @typeInfo(E).int.bits;
8 if (a < b * slice.len) return error.Overflow;
9
10 var n: T = 0;
11 for (slice, 0..) |item, i| {
12 const shift: std.math.Log2Int(T) = @intCast(b * (slice.len - 1 - i));
13 n = n | (@as(T, item) << shift);
14 }
15 return n;
16}
17
18test {
19 try std.testing.expect(try sliceToInt(u32, u4, &.{ 0x4, 0xe, 0x5, 0xa, 0x7, 0xd, 0xa, 0x9 }) == 0x4e5a7da9);
20}
21test {
22 try std.testing.expect(try sliceToInt(u30, u3, &.{ 0b010, 0b011, 0b100, 0b101, 0b101, 0b001, 0b111, 0b101, 0b101, 0b010 }) == 0b010011100101101001111101101010);
23}
24test {
25 try std.testing.expect(try sliceToInt(u30, u5, &.{ 0b01001, 0b11001, 0b01101, 0b00111, 0b11011, 0b01010 }) == 0b010011100101101001111101101010);
26}