[email protected] | 0e6f619 | 2011-12-28 23:18:21 | [diff] [blame] | 1 | // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | // This is a convenience header to pull in the platform-specific |
| 6 | // headers that define functions for byte-order conversion, |
| 7 | // particularly: ntohs(), htons(), ntohl(), htonl(). Prefer including |
| 8 | // this file instead of directly writing the #if / #else, since it |
| 9 | // avoids duplicating the platform-specific selections. |
| 10 | // This header also provides ntohll() and htonll() for byte-order conversion |
| 11 | // for 64-bit integers. |
| 12 | |
| 13 | #ifndef BASE_SYS_BYTEORDER_H_ |
| 14 | #define BASE_SYS_BYTEORDER_H_ |
| 15 | |
| 16 | #include "base/basictypes.h" |
| 17 | #include "build/build_config.h" |
| 18 | |
| 19 | #if defined(OS_WIN) |
| 20 | #include <winsock2.h> |
| 21 | #else |
| 22 | #include <arpa/inet.h> |
| 23 | #endif |
| 24 | |
| 25 | // Include headers to provide byteswap for all platforms. |
| 26 | #if defined(COMPILER_MSVC) |
| 27 | #include <stdlib.h> |
| 28 | #elif defined(OS_MACOSX) |
| 29 | #include <libkern/OSByteOrder.h> |
| 30 | #elif defined(OS_OPENBSD) |
| 31 | #include <sys/endian.h> |
| 32 | #else |
| 33 | #include <byteswap.h> |
| 34 | #endif |
| 35 | |
| 36 | |
| 37 | namespace base { |
| 38 | |
| 39 | // Returns a value with all bytes in |x| swapped, i.e. reverses the endianness. |
| 40 | inline uint64 ByteSwap(uint64 x) { |
| 41 | #if defined(COMPILER_MSVC) |
| 42 | return _byteswap_uint64(x); |
| 43 | #elif defined(OS_MACOSX) |
| 44 | return OSSwapInt64(x); |
| 45 | #elif defined(OS_OPENBSD) |
| 46 | return swap64(x); |
| 47 | #else |
| 48 | return bswap_64(x); |
| 49 | #endif |
| 50 | } |
| 51 | |
| 52 | // Converts the bytes in |x| from network to host order (endianness), and |
| 53 | // returns the result. |
| 54 | inline uint64 ntohll(uint64 x) { |
| 55 | #if defined(ARCH_CPU_LITTLE_ENDIAN) |
| 56 | return ByteSwap(x); |
| 57 | #else |
| 58 | return x; |
| 59 | #endif |
| 60 | } |
| 61 | |
| 62 | // Converts the bytes in |x| from host to network order (endianness), and |
| 63 | // returns the result. |
| 64 | inline uint64 htonll(uint64 x) { |
| 65 | #if defined(ARCH_CPU_LITTLE_ENDIAN) |
| 66 | return ByteSwap(x); |
| 67 | #else |
| 68 | return x; |
| 69 | #endif |
| 70 | } |
| 71 | |
| 72 | } // namespace base |
| 73 | |
| 74 | |
| 75 | #endif // BASE_SYS_BYTEORDER_H_ |