zig/std/endian.zig

26 lines
692 B
Zig
Raw Normal View History

const mem = @import("mem.zig");
const builtin = @import("builtin");
pub fn swapIfLe(comptime T: type, x: T) T {
2018-01-10 22:42:32 -08:00
return swapIf(builtin.Endian.Little, T, x);
2016-08-17 20:11:04 -07:00
}
pub fn swapIfBe(comptime T: type, x: T) T {
2018-01-10 22:42:32 -08:00
return swapIf(builtin.Endian.Big, T, x);
2016-08-17 20:11:04 -07:00
}
pub fn swapIf(endian: builtin.Endian, comptime T: type, x: T) T {
return if (builtin.endian == endian) swap(T, x) else x;
2016-08-17 20:11:04 -07:00
}
pub fn swap(comptime T: type, x: T) T {
var buf: [@sizeOf(T)]u8 = undefined;
2018-01-10 22:42:32 -08:00
mem.writeInt(buf[0..], x, builtin.Endian.Little);
return mem.readInt(buf, T, builtin.Endian.Big);
2016-08-17 20:11:04 -07:00
}
2018-01-10 22:42:32 -08:00
test "swap" {
const debug = @import("debug/index.zig");
debug.assert(swap(u32, 0xDEADBEEF) == 0xEFBEADDE);
}