aboutsummaryrefslogtreecommitdiff
path: root/std/mem.zig
diff options
context:
space:
mode:
authorAndrew Kelley <superjoe30@gmail.com>2018-04-11 18:27:06 -0400
committerAndrew Kelley <superjoe30@gmail.com>2018-04-11 18:27:06 -0400
commitce68dda4b60914e947088e7cf0c5626ea7cebc08 (patch)
treefca8e600e1b48862d816e5caa87f6fa5ab50d175 /std/mem.zig
parent588116cacc77535137262832f1b2aa464e7a1131 (diff)
parented1b028276bc1d17ee5e99863dd5bf150c8aa2f7 (diff)
downloadzig-ce68dda4b60914e947088e7cf0c5626ea7cebc08.tar.gz
zig-ce68dda4b60914e947088e7cf0c5626ea7cebc08.zip
Merge remote-tracking branch 'origin/master' into llvm7
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);
+}