Botan 3.0.0
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*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#ifndef BOTAN_BYTE_SWAP_H_
10#define BOTAN_BYTE_SWAP_H_
11
12#include <botan/types.h>
13
14namespace Botan {
15
16/**
17* Swap a 16 bit integer
18*/
19inline constexpr uint16_t reverse_bytes(uint16_t x)
20 {
21#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap16)
22 return __builtin_bswap16(x);
23#else
24 return static_cast<uint16_t>((x << 8) | (x >> 8));
25#endif
26 }
27
28/**
29* Swap a 32 bit integer
30*
31* We cannot use MSVC's _byteswap_ulong because it does not consider
32* the builtin to be constexpr.
33*/
34inline constexpr uint32_t reverse_bytes(uint32_t x)
35 {
36#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap32)
37 return __builtin_bswap32(x);
38#else
39 // MSVC at least recognizes this as a bswap
40 return ((x & 0x000000FF) << 24) |
41 ((x & 0x0000FF00) << 8) |
42 ((x & 0x00FF0000) >> 8) |
43 ((x & 0xFF000000) >> 24);
44#endif
45 }
46
47/**
48* Swap a 64 bit integer
49*
50* We cannot use MSVC's _byteswap_uint64 because it does not consider
51* the builtin to be constexpr.
52*/
53inline constexpr uint64_t reverse_bytes(uint64_t x)
54 {
55#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap64)
56 return __builtin_bswap64(x);
57#else
58 uint32_t hi = static_cast<uint32_t>(x >> 32);
59 uint32_t lo = static_cast<uint32_t>(x);
60
61 hi = reverse_bytes(hi);
62 lo = reverse_bytes(lo);
63
64 return (static_cast<uint64_t>(lo) << 32) | hi;
65#endif
66 }
67
68/**
69* Swap 4 Ts in an array
70*/
71template<typename T>
72inline constexpr void bswap_4(T x[4])
73 {
74 x[0] = reverse_bytes(x[0]);
75 x[1] = reverse_bytes(x[1]);
76 x[2] = reverse_bytes(x[2]);
77 x[3] = reverse_bytes(x[3]);
78 }
79
80}
81
82#endif
FE_25519 T
Definition: ge.cpp:36
Definition: alg_id.cpp:12
constexpr void bswap_4(T x[4])
Definition: bswap.h:72
constexpr uint16_t reverse_bytes(uint16_t x)
Definition: bswap.h:19