• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 /* A cross-platform equivalent of bionic's <sys/endian.h>. */
20 
21 /* For __BIONIC__ and __GLIBC__ */
22 #include <sys/cdefs.h>
23 
24 #if defined(__BIONIC__)
25 
26 #include <sys/endian.h>
27 
28 #elif defined(__GLIBC__)
29 
30 /* glibc's <endian.h> is like bionic's <sys/endian.h>. */
31 #include <endian.h>
32 
33 /* glibc keeps htons and htonl in <netinet/in.h>. */
34 #include <netinet/in.h>
35 
36 /* glibc doesn't have the 64-bit variants. */
37 #define htonq(x) htobe64(x)
38 #define ntohq(x) be64toh(x)
39 
40 /* glibc has different names to BSD for these. */
41 #define betoh16(x) be16toh(x)
42 #define betoh32(x) be32toh(x)
43 #define betoh64(x) be64toh(x)
44 #define letoh16(x) le16toh(x)
45 #define letoh32(x) le32toh(x)
46 #define letoh64(x) le64toh(x)
47 
48 #else
49 
50 #if defined(__APPLE__)
51 /* macOS has some of the basics. */
52 #include <sys/_endian.h>
53 #else
54 /* Windows has some of the basics as well. */
55 #include <sys/param.h>
56 #include <winsock2.h>
57 /* winsock2.h *must* be included before the following four macros. */
58 #define htons(x) __builtin_bswap16(x)
59 #define htonl(x) __builtin_bswap32(x)
60 #define ntohs(x) __builtin_bswap16(x)
61 #define ntohl(x) __builtin_bswap32(x)
62 #endif
63 
64 /* Neither macOS nor Windows have the rest. */
65 
66 #define __LITTLE_ENDIAN 1234
67 #define __BIG_ENDIAN 4321
68 #define __BYTE_ORDER __LITTLE_ENDIAN
69 
70 #define htonq(x) __builtin_bswap64(x)
71 
72 #define ntohq(x) __builtin_bswap64(x)
73 
74 #define htobe16(x) __builtin_bswap16(x)
75 #define htobe32(x) __builtin_bswap32(x)
76 #define htobe64(x) __builtin_bswap64(x)
77 
78 #define betoh16(x) __builtin_bswap16(x)
79 #define betoh32(x) __builtin_bswap32(x)
80 #define betoh64(x) __builtin_bswap64(x)
81 
82 #define htole16(x) (x)
83 #define htole32(x) (x)
84 #define htole64(x) (x)
85 
86 #define letoh16(x) (x)
87 #define letoh32(x) (x)
88 #define letoh64(x) (x)
89 
90 #define be16toh(x) __builtin_bswap16(x)
91 #define be32toh(x) __builtin_bswap32(x)
92 #define be64toh(x) __builtin_bswap64(x)
93 
94 #define le16toh(x) (x)
95 #define le32toh(x) (x)
96 #define le64toh(x) (x)
97 
98 #endif
99