Botan 2.19.5 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
14#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
15 #include <stdlib.h>
16#endif
17
18 BOTAN_FUTURE_INTERNAL_HEADER(bswap.h)
19
20namespace Botan {
21
22/**
23* Swap a 16 bit integer
24*/
25 inline uint16_t reverse_bytes(uint16_t val)
26 {
27 return static_cast<uint16_t>((val << 8) | (val >> 8));
28 }
29
30/**
31* Swap a 32 bit integer
32*/
33 inline uint32_t reverse_bytes(uint32_t val)
34 {
35#if defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG) || defined(BOTAN_BUILD_COMPILER_IS_XLC)
36 return __builtin_bswap32(val);
37
38#elif defined(BOTAN_BUILD_COMPILER_IS_MSVC)
39 return _byteswap_ulong(val);
40
41#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
42
43 // GCC-style inline assembly for x86 or x86-64
44 asm("bswapl %0" : "=r" (val) : "0" (val));
45 return val;
46
47#else
48 // Generic implementation
49 uint16_t hi = static_cast<uint16_t>(val >> 16);
50 uint16_t lo = static_cast<uint16_t>(val);
51
52 hi = reverse_bytes(hi);
53 lo = reverse_bytes(lo);
54
55 return (static_cast<uint32_t>(lo) << 16) | hi;
56#endif
57 }
58
59/**
60* Swap a 64 bit integer
61*/
62 inline uint64_t reverse_bytes(uint64_t val)
63 {
64#if defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG) || defined(BOTAN_BUILD_COMPILER_IS_XLC)
65 return __builtin_bswap64(val);
66
67#elif defined(BOTAN_BUILD_COMPILER_IS_MSVC)
68 return _byteswap_uint64(val);
69
70#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_X86_64)
71 // GCC-style inline assembly for x86-64
72 asm("bswapq %0" : "=r" (val) : "0" (val));
73 return val;
74
75#else
76 /* Generic implementation. Defined in terms of 32-bit bswap so any
77 * optimizations in that version can help.
78 */
79
80 uint32_t hi = static_cast<uint32_t>(val >> 32);
81 uint32_t lo = static_cast<uint32_t>(val);
82
83 hi = reverse_bytes(hi);
84 lo = reverse_bytes(lo);
85
86 return (static_cast<uint64_t>(lo) << 32) | hi;
87#endif
88 }
89
90/**
91* Swap 4 Ts in an array
92*/
93 template<typename T>
94 inline void bswap_4(T x[4])
95 {
96 x[0] = reverse_bytes(x[0]);
97 x[1] = reverse_bytes(x[1]);
98 x[2] = reverse_bytes(x[2]);
99 x[3] = reverse_bytes(x[3]);
100 }
101
102}
103
104#endif
BOTAN_FUTURE_INTERNAL_HEADER
#define BOTAN_FUTURE_INTERNAL_HEADER(hdr)
Definition: compiler.h:136
T
fe T
Definition: ge.cpp:37
Botan
Definition: alg_id.cpp:13
Botan::bswap_4
void bswap_4(T x[4])
Definition: bswap.h:94
Botan::reverse_bytes
uint64_t reverse_bytes(uint64_t val)
Definition: bswap.h:62