2017-02-12 14:22:35 -08:00
|
|
|
const mem = @import("mem.zig");
|
2017-05-01 10:12:38 -07:00
|
|
|
const builtin = @import("builtin");
|
2017-02-12 14:22:35 -08:00
|
|
|
|
2018-01-25 01:10:11 -08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2018-01-25 01:10:11 -08: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
|
|
|
}
|
|
|
|
|
2018-01-25 01:10:11 -08:00
|
|
|
pub fn swapIf(endian: builtin.Endian, comptime T: type, x: T) T {
|
2017-12-21 21:50:30 -08:00
|
|
|
return if (builtin.endian == endian) swap(T, x) else x;
|
2016-08-17 20:11:04 -07:00
|
|
|
}
|
|
|
|
|
2018-01-25 01:10:11 -08:00
|
|
|
pub fn swap(comptime T: type, x: T) T {
|
2017-02-12 14:22:35 -08:00
|
|
|
var buf: [@sizeOf(T)]u8 = undefined;
|
2018-01-10 22:42:32 -08:00
|
|
|
mem.writeInt(buf[0..], x, builtin.Endian.Little);
|
2018-01-06 15:24:35 -08:00
|
|
|
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);
|
|
|
|
}
|