authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2024-01-28 00:37:44 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2024-01-28 00:37:44 -08:00
loge8f81eb1d126e37dc5b57e796fd8ee5e10123312
tree45119a61a555de7e9c2aabdbe21ad3673bd7b089
parentaa4f14760e80efa703f12cff0eca6f3d23103ec7

add rawInt


2 files changed, 43 insertions(+), 0 deletions(-)

src/lib.zig+2
...@@ -89,3 +89,5 @@ pub fn fd_realpath(fd: std.os.fd_t) ![std.fs.MAX_PATH_BYTES:0]u8 {...@@ -89,3 +89,5 @@ pub fn fd_realpath(fd: std.os.fd_t) ![std.fs.MAX_PATH_BYTES:0]u8 {
89 else => @compileError("not implemented!"),89 else => @compileError("not implemented!"),
90 }90 }
91}91}
92
93pub usingnamespace @import("./rawInt.zig");
src/rawInt.zig created+41
...@@ -0,0 +1,41 @@
1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4const builtin = @import("builtin");
5const native_endian = builtin.target.cpu.arch.endian();
6
7pub fn rawInt(comptime T: type, comptime literal: comptime_int) T {
8 comptime std.debug.assert(@typeInfo(T).Int.bits % 8 == 0);
9 return switch (native_endian) {
10 .Little => @byteSwap(@as(T, literal)),
11 .Big => @compileError("unreachable"),
12 };
13}
14
15test {
16 const bytes = std.mem.toBytes(rawInt(u16, 0x4e5a));
17 try std.testing.expect(bytes[0] == 0x4e);
18}
19test {
20 const bytes = std.mem.toBytes(rawInt(u16, 0x4e5a));
21 try std.testing.expect(bytes[0] == 0x4e);
22 try std.testing.expect(bytes[1] == 0x5a);
23}
24test {
25 const bytes = std.mem.toBytes(rawInt(u32, 0x4e5a7da9));
26 try std.testing.expect(bytes[0] == 0x4e);
27 try std.testing.expect(bytes[1] == 0x5a);
28 try std.testing.expect(bytes[2] == 0x7d);
29 try std.testing.expect(bytes[3] == 0xa9);
30}
31test {
32 const bytes = std.mem.toBytes(rawInt(u64, 0x4e5a7da9f3f1d132));
33 try std.testing.expect(bytes[0] == 0x4e);
34 try std.testing.expect(bytes[1] == 0x5a);
35 try std.testing.expect(bytes[2] == 0x7d);
36 try std.testing.expect(bytes[3] == 0xa9);
37 try std.testing.expect(bytes[4] == 0xf3);
38 try std.testing.expect(bytes[5] == 0xf1);
39 try std.testing.expect(bytes[6] == 0xd1);
40 try std.testing.expect(bytes[7] == 0x32);
41}