zig/std/endian.zig

26 lines
704 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-11 14:42:32 +08:00
return swapIf(builtin.Endian.Little, T, x);
2016-08-18 11:11:04 +08:00
}
pub fn swapIfBe(comptime T: type, x: T) -> T {
2018-01-11 14:42:32 +08:00
return swapIf(builtin.Endian.Big, T, x);
2016-08-18 11:11:04 +08: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-18 11:11:04 +08:00
}
pub fn swap(comptime T: type, x: T) -> T {
var buf: [@sizeOf(T)]u8 = undefined;
2018-01-11 14:42:32 +08:00
mem.writeInt(buf[0..], x, builtin.Endian.Little);
return mem.readInt(buf, T, builtin.Endian.Big);
2016-08-18 11:11:04 +08:00
}
2018-01-11 14:42:32 +08:00
test "swap" {
const debug = @import("debug/index.zig");
debug.assert(swap(u32, 0xDEADBEEF) == 0xEFBEADDE);
}