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