From e8f81eb1d126e37dc5b57e796fd8ee5e10123312 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Sun, 28 Jan 2024 00:37:44 -0800 Subject: [PATCH] add rawInt --- src/lib.zig | 2 ++ src/rawInt.zig | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/rawInt.zig diff --git a/src/lib.zig b/src/lib.zig index c50f4245830ad0f085ab63e7eb8230fd48e60c07..cd1c3aca7fb9f709471919ca0d6d745a238a2d5d 100644 --- a/src/lib.zig +++ b/src/lib.zig @@ -89,3 +89,5 @@ pub fn fd_realpath(fd: std.os.fd_t) ![std.fs.MAX_PATH_BYTES:0]u8 { else => @compileError("not implemented!"), } } + +pub usingnamespace @import("./rawInt.zig"); diff --git a/src/rawInt.zig b/src/rawInt.zig new file mode 100644 index 0000000000000000000000000000000000000000..3ff83dff13bc2e072251ef39a7e90d5aa5bf5945 --- /dev/null +++ b/src/rawInt.zig @@ -0,0 +1,41 @@ +const std = @import("std"); +const string = []const u8; +const extras = @import("./lib.zig"); +const builtin = @import("builtin"); +const native_endian = builtin.target.cpu.arch.endian(); + +pub fn rawInt(comptime T: type, comptime literal: comptime_int) T { + comptime std.debug.assert(@typeInfo(T).Int.bits % 8 == 0); + return switch (native_endian) { + .Little => @byteSwap(@as(T, literal)), + .Big => @compileError("unreachable"), + }; +} + +test { + const bytes = std.mem.toBytes(rawInt(u16, 0x4e5a)); + try std.testing.expect(bytes[0] == 0x4e); +} +test { + const bytes = std.mem.toBytes(rawInt(u16, 0x4e5a)); + try std.testing.expect(bytes[0] == 0x4e); + try std.testing.expect(bytes[1] == 0x5a); +} +test { + const bytes = std.mem.toBytes(rawInt(u32, 0x4e5a7da9)); + try std.testing.expect(bytes[0] == 0x4e); + try std.testing.expect(bytes[1] == 0x5a); + try std.testing.expect(bytes[2] == 0x7d); + try std.testing.expect(bytes[3] == 0xa9); +} +test { + const bytes = std.mem.toBytes(rawInt(u64, 0x4e5a7da9f3f1d132)); + try std.testing.expect(bytes[0] == 0x4e); + try std.testing.expect(bytes[1] == 0x5a); + try std.testing.expect(bytes[2] == 0x7d); + try std.testing.expect(bytes[3] == 0xa9); + try std.testing.expect(bytes[4] == 0xf3); + try std.testing.expect(bytes[5] == 0xf1); + try std.testing.expect(bytes[6] == 0xd1); + try std.testing.expect(bytes[7] == 0x32); +} -- 2.54.0