aboutsummaryrefslogtreecommitdiff
path: root/std/mem.zig
diff options
context:
space:
mode:
Diffstat (limited to 'std/mem.zig')
-rw-r--r--std/mem.zig26
1 files changed, 26 insertions, 0 deletions
diff --git a/std/mem.zig b/std/mem.zig
index 97cb35ae65..8a59d6251b 100644
--- a/std/mem.zig
+++ b/std/mem.zig
@@ -3,6 +3,7 @@ const debug = std.debug;
const assert = debug.assert;
const math = std.math;
const builtin = @import("builtin");
+const mem = this;
pub const Allocator = struct {
const Error = error {OutOfMemory};
@@ -550,3 +551,28 @@ test "std.mem.rotate" {
assert(eql(i32, arr, []i32{ 1, 2, 4, 5, 3 }));
}
+
+// TODO: When https://github.com/zig-lang/zig/issues/649 is solved these can be done by
+// endian-casting the pointer and then dereferencing
+
+pub fn endianSwapIfLe(comptime T: type, x: T) T {
+ return endianSwapIf(builtin.Endian.Little, T, x);
+}
+
+pub fn endianSwapIfBe(comptime T: type, x: T) T {
+ return endianSwapIf(builtin.Endian.Big, T, x);
+}
+
+pub fn endianSwapIf(endian: builtin.Endian, comptime T: type, x: T) T {
+ return if (builtin.endian == endian) endianSwap(T, x) else x;
+}
+
+pub fn endianSwap(comptime T: type, x: T) T {
+ var buf: [@sizeOf(T)]u8 = undefined;
+ mem.writeInt(buf[0..], x, builtin.Endian.Little);
+ return mem.readInt(buf, T, builtin.Endian.Big);
+}
+
+test "std.mem.endianSwap" {
+ assert(endianSwap(u32, 0xDEADBEEF) == 0xEFBEADDE);
+}