Botan 3.7.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
17#include <botan/compiler.h>
18
19namespace Botan {
20
21/**
22 * Swap the byte order of an unsigned integer
23 */
24template <std::unsigned_integral T>
25 requires(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8)
26inline constexpr T reverse_bytes(T x) {
27 if constexpr(sizeof(T) == 1) {
28 return x;
29 } else if constexpr(sizeof(T) == 2) {
30#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap16)
31 return static_cast<T>(__builtin_bswap16(x));
32#else
33 return static_cast<T>((x << 8) | (x >> 8));
34#endif
35 } else if constexpr(sizeof(T) == 4) {
36#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap32)
37 return static_cast<T>(__builtin_bswap32(x));
38#else
39 // MSVC at least recognizes this as a bswap
40 return static_cast<T>(((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) |
41 ((x & 0xFF000000) >> 24));
42#endif
43 } else if constexpr(sizeof(T) == 8) {
44#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap64)
45 return static_cast<T>(__builtin_bswap64(x));
46#else
47 uint32_t hi = static_cast<uint32_t>(x >> 32);
48 uint32_t lo = static_cast<uint32_t>(x);
49
50 hi = reverse_bytes(hi);
51 lo = reverse_bytes(lo);
52
53 return (static_cast<T>(lo) << 32) | hi;
54#endif
55 }
56}
57
58} // namespace Botan
59
60#endif
FE_25519 T
Definition ge.cpp:34
constexpr T reverse_bytes(T x)
Definition bswap.h:26