• 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__) || defined(ANDROID_HOST_MUSL)
29 
30 /* glibc and musl's <endian.h> are like bionic's <sys/endian.h>. */
31 #include <endian.h>
32 
33 /* glibc and musl keep htons and htonl in <netinet/in.h>. */
34 #include <netinet/in.h>
35 
36 /* glibc and musl don't have the 64-bit variants. */
37 #define htonq(x) htobe64(x)
38 #define ntohq(x) be64toh(x)
39 
40 #if defined(__GLIBC__)
41 /* glibc has different names to BSD for these. */
42 #define betoh16(x) be16toh(x)
43 #define betoh32(x) be32toh(x)
44 #define betoh64(x) be64toh(x)
45 #define letoh16(x) le16toh(x)
46 #define letoh32(x) le32toh(x)
47 #define letoh64(x) le64toh(x)
48 #endif
49 
50 #else
51 
52 #if defined(__APPLE__)
53 /* macOS has some of the basics. */
54 #include <sys/_endian.h>
55 #else
56 /* Windows has some of the basics as well. */
57 #include <sys/param.h>
58 #include <winsock2.h>
59 /* winsock2.h *must* be included before the following four macros. */
60 #define htons(x) __builtin_bswap16(x)
61 #define htonl(x) __builtin_bswap32(x)
62 #define ntohs(x) __builtin_bswap16(x)
63 #define ntohl(x) __builtin_bswap32(x)
64 #endif
65 
66 /* Neither macOS nor Windows have the rest. */
67 
68 #define __LITTLE_ENDIAN 1234
69 #define __BIG_ENDIAN 4321
70 #define __BYTE_ORDER __LITTLE_ENDIAN
71 
72 #define htonq(x) __builtin_bswap64(x)
73 
74 #define ntohq(x) __builtin_bswap64(x)
75 
76 #define htobe16(x) __builtin_bswap16(x)
77 #define htobe32(x) __builtin_bswap32(x)
78 #define htobe64(x) __builtin_bswap64(x)
79 
80 #define betoh16(x) __builtin_bswap16(x)
81 #define betoh32(x) __builtin_bswap32(x)
82 #define betoh64(x) __builtin_bswap64(x)
83 
84 #define htole16(x) (x)
85 #define htole32(x) (x)
86 #define htole64(x) (x)
87 
88 #define letoh16(x) (x)
89 #define letoh32(x) (x)
90 #define letoh64(x) (x)
91 
92 #define be16toh(x) __builtin_bswap16(x)
93 #define be32toh(x) __builtin_bswap32(x)
94 #define be64toh(x) __builtin_bswap64(x)
95 
96 #define le16toh(x) (x)
97 #define le32toh(x) (x)
98 #define le64toh(x) (x)
99 
100 #endif
101