aboutsummaryrefslogtreecommitdiff
path: root/std/endian.zig
blob: 8ae8ae22f8f1b80dc2b4de8f1797ed66950a01d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const mem = @import("mem.zig");
const builtin = @import("builtin");

pub fn swapIfLe(comptime T: type, x: T) -> T {
    swapIf(false, T, x)
}

pub fn swapIfBe(comptime T: type, x: T) -> T {
    swapIf(true, T, x)
}

pub fn swapIf(is_be: bool, comptime T: type, x: T) -> T {
    if (builtin.is_big_endian == is_be) swap(T, x) else x
}

pub fn swap(comptime T: type, x: T) -> T {
    var buf: [@sizeOf(T)]u8 = undefined;
    mem.writeInt(buf[0..], x, false);
    return mem.readInt(buf, T, true);
}