xref: /aosp_15_r20/external/cronet/base/allocator/partition_allocator/src/partition_alloc/reverse_bytes.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2022 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 #ifndef PARTITION_ALLOC_REVERSE_BYTES_H_
6 #define PARTITION_ALLOC_REVERSE_BYTES_H_
7 
8 // This header defines drop-in constexpr replacements for the
9 // byte-reversing routines that we used from `//base/sys_byteorder.h`.
10 // They will be made moot by C++23's <endian> header or by C++20's
11 // <bit> header.
12 
13 #include <cstdint>
14 
15 #include "build/build_config.h"
16 #include "partition_alloc/partition_alloc_config.h"
17 
18 namespace partition_alloc::internal {
19 
ReverseFourBytes(uint32_t value)20 constexpr uint32_t ReverseFourBytes(uint32_t value) {
21 #if PA_CONFIG(IS_NONCLANG_MSVC)
22   return value >> 24 | (value >> 8 & 0xff00) | (value & 0xff00) << 8 |
23          value << 24;
24 #else
25   return __builtin_bswap32(value);
26 #endif  // PA_CONFIG(IS_NONCLANG_MSVC)
27 }
28 
ReverseEightBytes(uint64_t value)29 constexpr uint64_t ReverseEightBytes(uint64_t value) {
30 #if PA_CONFIG(IS_NONCLANG_MSVC)
31   return value >> 56 | (value >> 40 & 0xff00) | (value >> 24 & 0xff0000) |
32          (value >> 8 & 0xff000000) | (value & 0xff000000) << 8 |
33          (value & 0xff0000) << 24 | (value & 0xff00) << 40 |
34          (value & 0xff) << 56;
35 #else
36   return __builtin_bswap64(value);
37 #endif  // PA_CONFIG(IS_NONCLANG_MSVC)
38 }
39 
ReverseBytes(uintptr_t value)40 constexpr uintptr_t ReverseBytes(uintptr_t value) {
41   if (sizeof(uintptr_t) == 4) {
42     return ReverseFourBytes(static_cast<uint32_t>(value));
43   }
44   return ReverseEightBytes(static_cast<uint64_t>(value));
45 }
46 
47 }  // namespace partition_alloc::internal
48 
49 #endif  // PARTITION_ALLOC_REVERSE_BYTES_H_
50