1 /* $NetBSD: bswap.h,v 1.16 2009/08/08 21:23:15 christos Exp $ */ 2 3 /* Written by Manuel Bouyer. Public domain */ 4 5 #ifndef _SYS_BSWAP_H_ 6 #define _SYS_BSWAP_H_ 7 8 #ifndef _LOCORE 9 #include <sys/cdefs.h> 10 #include <sys/types.h> 11 12 #include <machine/bswap.h> 13 14 __BEGIN_DECLS 15 /* Always declare the functions in case their address is taken (etc) */ 16 #if defined(_KERNEL) || defined(_STANDALONE) || !defined(__BSWAP_RENAME) 17 uint16_t bswap16(uint16_t) __constfunc; 18 uint32_t bswap32(uint32_t) __constfunc; 19 #else 20 uint16_t bswap16(uint16_t) __RENAME(__bswap16) __constfunc; 21 uint32_t bswap32(uint32_t) __RENAME(__bswap32) __constfunc; 22 #endif 23 uint64_t bswap64(uint64_t) __constfunc; 24 __END_DECLS 25 26 #if defined(__GNUC__) && defined(__OPTIMIZE__) && !defined(__lint__) 27 28 /* machine/byte_swap.h might have defined inline versions */ 29 #ifndef __BYTE_SWAP_U64_VARIABLE 30 #define __BYTE_SWAP_U64_VARIABLE bswap64 31 #endif 32 33 #ifndef __BYTE_SWAP_U32_VARIABLE 34 #define __BYTE_SWAP_U32_VARIABLE bswap32 35 #endif 36 37 #ifndef __BYTE_SWAP_U16_VARIABLE 38 #define __BYTE_SWAP_U16_VARIABLE bswap16 39 #endif 40 41 #define __byte_swap_u64_constant(x) \ 42 (__CAST(uint64_t, \ 43 ((((x) & 0xff00000000000000ull) >> 56) | \ 44 (((x) & 0x00ff000000000000ull) >> 40) | \ 45 (((x) & 0x0000ff0000000000ull) >> 24) | \ 46 (((x) & 0x000000ff00000000ull) >> 8) | \ 47 (((x) & 0x00000000ff000000ull) << 8) | \ 48 (((x) & 0x0000000000ff0000ull) << 24) | \ 49 (((x) & 0x000000000000ff00ull) << 40) | \ 50 (((x) & 0x00000000000000ffull) << 56)))) 51 52 #define __byte_swap_u32_constant(x) \ 53 (__CAST(uint32_t, \ 54 ((((x) & 0xff000000) >> 24) | \ 55 (((x) & 0x00ff0000) >> 8) | \ 56 (((x) & 0x0000ff00) << 8) | \ 57 (((x) & 0x000000ff) << 24)))) 58 59 #define __byte_swap_u16_constant(x) \ 60 (__CAST(uint16_t, \ 61 ((((x) & 0xff00) >> 8) | \ 62 (((x) & 0x00ff) << 8)))) 63 64 #define bswap64(x) \ 65 (__builtin_constant_p((x)) ? \ 66 __byte_swap_u64_constant(x) : __BYTE_SWAP_U64_VARIABLE(x)) 67 68 #define bswap32(x) \ 69 (__builtin_constant_p((x)) ? \ 70 __byte_swap_u32_constant(x) : __BYTE_SWAP_U32_VARIABLE(x)) 71 72 #define bswap16(x) \ 73 (__builtin_constant_p((x)) ? \ 74 __byte_swap_u16_constant(x) : __BYTE_SWAP_U16_VARIABLE(x)) 75 76 #endif /* __GNUC__ && __OPTIMIZE__ */ 77 #endif /* !_LOCORE */ 78 79 #endif /* !_SYS_BSWAP_H_ */ 80