1const std = @import("std");
2const builtin = @import("builtin");
3const compiler_rt = @import("../compiler_rt.zig");
4const symbol = compiler_rt.symbol;
5
6comptime {
7 symbol(&__bswapsi2, "__bswapsi2");
8 symbol(&__bswapdi2, "__bswapdi2");
9 symbol(&__bswapti2, "__bswapti2");
10}
11
12// bswap - byteswap
13// - bswapXi2 for unoptimized big and little endian
14// ie for u32
15// DE AD BE EF <- little|big endian
16// FE BE AD DE <- big|little endian
17// ff 00 00 00 >> 3*8 (leftmost byte)
18// 00 ff 00 00 >> 1*8 (2nd left byte)
19// 00 00 ff 00 << 1*8 (2n right byte)
20// 00 00 00 ff << 3*8 (rightmost byte)
21
22inline fn bswapXi2(comptime T: type, a: T) T {
23 switch (@bitSizeOf(T)) {
24 32 => {
25 // zig fmt: off
26 return (((a & 0xff000000) >> 24)
27 | ((a & 0x00ff0000) >> 8 )
28 | ((a & 0x0000ff00) << 8 )
29 | ((a & 0x000000ff) << 24));
30 // zig fmt: on
31 },
32 64 => {
33 // zig fmt: off
34 return (((a & 0xff00000000000000) >> 56)
35 | ((a & 0x00ff000000000000) >> 40 )
36 | ((a & 0x0000ff0000000000) >> 24 )
37 | ((a & 0x000000ff00000000) >> 8 )
38 | ((a & 0x00000000ff000000) << 8 )
39 | ((a & 0x0000000000ff0000) << 24 )
40 | ((a & 0x000000000000ff00) << 40 )
41 | ((a & 0x00000000000000ff) << 56));
42 // zig fmt: on
43 },
44 128 => {
45 // zig fmt: off
46 return (((a & 0xff000000000000000000000000000000) >> 120)
47 | ((a & 0x00ff0000000000000000000000000000) >> 104)
48 | ((a & 0x0000ff00000000000000000000000000) >> 88 )
49 | ((a & 0x000000ff000000000000000000000000) >> 72 )
50 | ((a & 0x00000000ff0000000000000000000000) >> 56 )
51 | ((a & 0x0000000000ff00000000000000000000) >> 40 )
52 | ((a & 0x000000000000ff000000000000000000) >> 24 )
53 | ((a & 0x00000000000000ff0000000000000000) >> 8 )
54 | ((a & 0x0000000000000000ff00000000000000) << 8 )
55 | ((a & 0x000000000000000000ff000000000000) << 24 )
56 | ((a & 0x00000000000000000000ff0000000000) << 40 )
57 | ((a & 0x0000000000000000000000ff00000000) << 56 )
58 | ((a & 0x000000000000000000000000ff000000) << 72 )
59 | ((a & 0x00000000000000000000000000ff0000) << 88 )
60 | ((a & 0x0000000000000000000000000000ff00) << 104)
61 | ((a & 0x000000000000000000000000000000ff) << 120));
62 // zig fmt: on
63 },
64 else => unreachable,
65 }
66}
67
68pub fn __bswapsi2(a: u32) callconv(.c) u32 {
69 return bswapXi2(u32, a);
70}
71
72pub fn __bswapdi2(a: u64) callconv(.c) u64 {
73 return bswapXi2(u64, a);
74}
75
76pub fn __bswapti2(a: u128) callconv(.c) u128 {
77 return bswapXi2(u128, a);
78}
79
80test {
81 _ = @import("bswapsi2_test.zig");
82 _ = @import("bswapdi2_test.zig");
83 _ = @import("bswapti2_test.zig");
84}