Botan 3.6.1
Crypto and TLS for C&
bswap.h
Go to the documentation of this file.
1/*
2* Byte Swapping Operations
3* (C) 1999-2011,2018 Jack Lloyd
4* (C) 2007 Yves Jerschow
5* (C) 2024 René Meusel - Rohde & Schwarz Cybersecurity
6*
7* TODO: C++23: replace this entire implementation with std::byteswap
8*
9* Botan is released under the Simplified BSD License (see license.txt)
10*/
11
12#ifndef BOTAN_BYTE_SWAP_H_
13#define BOTAN_BYTE_SWAP_H_
14
15#include <botan/types.h>
16
17namespace Botan {
18
19/**
20 * Swap the byte order of an unsigned integer
21 */
22template <std::unsigned_integral T>
23 requires(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8)
24inline constexpr T reverse_bytes(T x) {
25 if constexpr(sizeof(T) == 1) {
26 return x;
27 } else if constexpr(sizeof(T) == 2) {
28#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap16)
29 return static_cast<T>(__builtin_bswap16(x));
30#else
31 return static_cast<T>((x << 8) | (x >> 8));
32#endif
33 } else if constexpr(sizeof(T) == 4) {
34#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap32)
35 return static_cast<T>(__builtin_bswap32(x));
36#else
37 // MSVC at least recognizes this as a bswap
38 return static_cast<T>(((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) |
39 ((x & 0xFF000000) >> 24));
40#endif
41 } else if constexpr(sizeof(T) == 8) {
42#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap64)
43 return static_cast<T>(__builtin_bswap64(x));
44#else
45 uint32_t hi = static_cast<uint32_t>(x >> 32);
46 uint32_t lo = static_cast<uint32_t>(x);
47
48 hi = reverse_bytes(hi);
49 lo = reverse_bytes(lo);
50
51 return (static_cast<T>(lo) << 32) | hi;
52#endif
53 }
54}
55
56} // namespace Botan
57
58#endif
FE_25519 T
Definition ge.cpp:34
constexpr T reverse_bytes(T x)
Definition bswap.h:24