xref: /aosp_15_r20/external/cronet/base/sys_byteorder.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
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 header defines cross-platform ByteSwap() implementations for 16, 32 and
6 // 64-bit values, and NetToHostXX() / HostToNextXX() functions equivalent to
7 // the traditional ntohX() and htonX() functions.
8 // Use the functions defined here rather than using the platform-specific
9 // functions directly.
10 
11 #ifndef BASE_SYS_BYTEORDER_H_
12 #define BASE_SYS_BYTEORDER_H_
13 
14 #include <stdint.h>
15 
16 #include "base/numerics/byte_conversions.h"
17 #include "build/build_config.h"
18 
19 #if defined(COMPILER_MSVC)
20 #include <stdlib.h>
21 #endif
22 
23 namespace base {
24 
25 // Converts the bytes in |x| from network to host order (endianness), and
26 // returns the result.
NetToHost16(uint16_t x)27 inline constexpr uint16_t NetToHost16(uint16_t x) {
28 #if defined(ARCH_CPU_LITTLE_ENDIAN)
29   return ByteSwap(x);
30 #else
31   return x;
32 #endif
33 }
NetToHost32(uint32_t x)34 inline constexpr uint32_t NetToHost32(uint32_t x) {
35 #if defined(ARCH_CPU_LITTLE_ENDIAN)
36   return ByteSwap(x);
37 #else
38   return x;
39 #endif
40 }
NetToHost64(uint64_t x)41 inline constexpr uint64_t NetToHost64(uint64_t x) {
42 #if defined(ARCH_CPU_LITTLE_ENDIAN)
43   return ByteSwap(x);
44 #else
45   return x;
46 #endif
47 }
48 
49 // Converts the bytes in |x| from host to network order (endianness), and
50 // returns the result.
HostToNet16(uint16_t x)51 inline constexpr uint16_t HostToNet16(uint16_t x) {
52 #if defined(ARCH_CPU_LITTLE_ENDIAN)
53   return ByteSwap(x);
54 #else
55   return x;
56 #endif
57 }
HostToNet32(uint32_t x)58 inline constexpr uint32_t HostToNet32(uint32_t x) {
59 #if defined(ARCH_CPU_LITTLE_ENDIAN)
60   return ByteSwap(x);
61 #else
62   return x;
63 #endif
64 }
HostToNet64(uint64_t x)65 inline constexpr uint64_t HostToNet64(uint64_t x) {
66 #if defined(ARCH_CPU_LITTLE_ENDIAN)
67   return ByteSwap(x);
68 #else
69   return x;
70 #endif
71 }
72 
73 }  // namespace base
74 
75 #endif  // BASE_SYS_BYTEORDER_H_
76