Bitcoin ABC 0.32.5
P2P Digital Currency
byteswap.h
Go to the documentation of this file.
1// Copyright (c) 2014-2016 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_COMPAT_BYTESWAP_H
6#define BITCOIN_COMPAT_BYTESWAP_H
7
8#include <cstdint>
9#ifdef _MSC_VER
10#include <cstdlib>
11#endif
12
13// All internal_bswap_* functions can be replaced with std::byteswap once we
14// require c++23. Both libstdc++ and libc++ implement std::byteswap via these
15// builtins.
16
17#ifndef DISABLE_BUILTIN_BSWAPS
18#if defined __has_builtin
19#if __has_builtin(__builtin_bswap16)
20#define bitcoin_builtin_bswap16(x) __builtin_bswap16(x)
21#endif
22#if __has_builtin(__builtin_bswap32)
23#define bitcoin_builtin_bswap32(x) __builtin_bswap32(x)
24#endif
25#if __has_builtin(__builtin_bswap64)
26#define bitcoin_builtin_bswap64(x) __builtin_bswap64(x)
27#endif
28#elif defined(_MSC_VER)
29#define bitcoin_builtin_bswap16(x) _byteswap_ushort(x)
30#define bitcoin_builtin_bswap32(x) _byteswap_ulong(x)
31#define bitcoin_builtin_bswap64(x) _byteswap_uint64(x)
32#endif
33#endif
34
35// MSVC's _byteswap_* functions are not constexpr
36
37#ifndef _MSC_VER
38#define BSWAP_CONSTEXPR constexpr
39#else
40#define BSWAP_CONSTEXPR
41#endif
42
43inline BSWAP_CONSTEXPR uint16_t internal_bswap_16(uint16_t x) {
44#ifdef bitcoin_builtin_bswap16
45 return bitcoin_builtin_bswap16(x);
46#else
47 return (x >> 8) | (x << 8);
48#endif
49}
50
51inline BSWAP_CONSTEXPR uint32_t internal_bswap_32(uint32_t x) {
52#ifdef bitcoin_builtin_bswap32
53 return bitcoin_builtin_bswap32(x);
54#else
55 return (((x & 0xff000000U) >> 24) | ((x & 0x00ff0000U) >> 8) |
56 ((x & 0x0000ff00U) << 8) | ((x & 0x000000ffU) << 24));
57#endif
58}
59
60inline BSWAP_CONSTEXPR uint64_t internal_bswap_64(uint64_t x) {
61#ifdef bitcoin_builtin_bswap64
62 return bitcoin_builtin_bswap64(x);
63#else
64 return (((x & 0xff00000000000000ull) >> 56) |
65 ((x & 0x00ff000000000000ull) >> 40) |
66 ((x & 0x0000ff0000000000ull) >> 24) |
67 ((x & 0x000000ff00000000ull) >> 8) |
68 ((x & 0x00000000ff000000ull) << 8) |
69 ((x & 0x0000000000ff0000ull) << 24) |
70 ((x & 0x000000000000ff00ull) << 40) |
71 ((x & 0x00000000000000ffull) << 56));
72#endif
73}
74
75#endif // BITCOIN_COMPAT_BYTESWAP_H
BSWAP_CONSTEXPR uint32_t internal_bswap_32(uint32_t x)
Definition: byteswap.h:51
BSWAP_CONSTEXPR uint16_t internal_bswap_16(uint16_t x)
Definition: byteswap.h:43
BSWAP_CONSTEXPR uint64_t internal_bswap_64(uint64_t x)
Definition: byteswap.h:60
#define BSWAP_CONSTEXPR
Definition: byteswap.h:38