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