1 /* 2 * Copyright (c) 2008-2014 Travis Geiselbrecht 3 * Copyright 2016 The Fuchsia Authors 4 * 5 * Use of this source code is governed by a MIT-style 6 * license that can be found in the LICENSE file or at 7 * https://opensource.org/licenses/MIT 8 */ 9 #pragma once 10 11 #include <sys/types.h> 12 13 #ifndef __BYTE_ORDER__ 14 #error Compiler does not provide __BYTE_ORDER__ 15 #endif 16 17 /* the compiler provides it, use what it says */ 18 #define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ 19 #define BIG_ENDIAN __ORDER_BIG_ENDIAN__ 20 #define BYTE_ORDER __BYTE_ORDER__ 21 22 // define a macro that unconditionally swaps SWAP_64(uint64_t x)23static inline uint64_t SWAP_64(uint64_t x) { return __builtin_bswap64(x); } SWAP_32(uint32_t x)24static inline uint32_t SWAP_32(uint32_t x) { return __builtin_bswap32(x); } SWAP_16(uint16_t x)25static inline uint16_t SWAP_16(uint16_t x) { return __builtin_bswap16(x); } 26 27 // standard swap macros 28 #if BYTE_ORDER == BIG_ENDIAN 29 #define LE64(val) SWAP_64(val) 30 #define LE32(val) SWAP_32(val) 31 #define LE16(val) SWAP_16(val) 32 #define BE64(val) (val) 33 #define BE32(val) (val) 34 #define BE16(val) (val) 35 #else 36 #define LE64(val) (val) 37 #define LE32(val) (val) 38 #define LE16(val) (val) 39 #define BE64(val) SWAP_64(val) 40 #define BE32(val) SWAP_32(val) 41 #define BE16(val) SWAP_16(val) 42 #endif 43 44 #define LE32SWAP(var) do { (var) = LE32(var); } while (0) 45 #define LE16SWAP(var) do { (var) = LE16(var); } while (0) 46 #define BE32SWAP(var) do { (var) = BE32(var); } while (0) 47 #define BE16SWAP(var) do { (var) = BE16(var); } while (0) 48 49 /* classic network byte swap stuff */ 50 #define ntohs(n) BE16(n) 51 #define htons(h) BE16(h) 52 #define ntohl(n) BE32(n) 53 #define htonl(h) BE32(h) 54 55 /* 64-bit network byte swap stuff */ 56 #define htobe64(h) BE64(h) 57 #define be64toh(b) BE64(b) 58 59