Crypto++  8.2
Free C++ class library of cryptographic schemes
misc.h
Go to the documentation of this file.
1 // misc.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file misc.h
4 /// \brief Utility functions for the Crypto++ library.
5 
6 #ifndef CRYPTOPP_MISC_H
7 #define CRYPTOPP_MISC_H
8 
9 #include "config.h"
10 
11 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
12 
13 #if (CRYPTOPP_MSC_VERSION)
14 # pragma warning(push)
15 # pragma warning(disable: 4146 4514)
16 # if (CRYPTOPP_MSC_VERSION >= 1400)
17 # pragma warning(disable: 6326)
18 # endif
19 #endif
20 
21 // Issue 340 and Issue 793
22 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
23 # pragma GCC diagnostic push
24 # pragma GCC diagnostic ignored "-Wconversion"
25 # pragma GCC diagnostic ignored "-Wsign-conversion"
26 # pragma GCC diagnostic ignored "-Wunused-function"
27 #endif
28 
29 #include "cryptlib.h"
30 #include "stdcpp.h"
31 #include "smartptr.h"
32 
33 #ifdef _MSC_VER
34  #if _MSC_VER >= 1400
35  // VC2005 workaround: disable declarations that conflict with winnt.h
36  #define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
37  #define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
38  #define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
39  #define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
40  #include <intrin.h>
41  #undef _interlockedbittestandset
42  #undef _interlockedbittestandreset
43  #undef _interlockedbittestandset64
44  #undef _interlockedbittestandreset64
45  #define CRYPTOPP_FAST_ROTATE(x) 1
46  #elif _MSC_VER >= 1300
47  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
48  #else
49  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
50  #endif
51 #elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
52  (defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
53  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
54 #elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
55  #define CRYPTOPP_FAST_ROTATE(x) 1
56 #else
57  #define CRYPTOPP_FAST_ROTATE(x) 0
58 #endif
59 
60 #ifdef __BORLANDC__
61 #include <mem.h>
62 #include <stdlib.h>
63 #endif
64 
65 #if (defined(__GNUC__) || defined(__clang__)) && defined(__linux__)
66 #define CRYPTOPP_BYTESWAP_AVAILABLE 1
67 #include <byteswap.h>
68 #endif
69 
70 // Limit to ARM A-32. Aarch64 is failing self tests.
71 #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 6)
72 #define CRYPTOPP_ARM_BYTEREV_AVAILABLE 1
73 #endif
74 
75 // Limit to ARM A-32. Aarch64 is failing self tests.
76 #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 7)
77 #define CRYPTOPP_ARM_BITREV_AVAILABLE 1
78 #endif
79 
80 #if defined(__BMI__)
81 # include <x86intrin.h>
82 # include <immintrin.h>
83 #endif // GCC and BMI
84 
85 // More LLVM bullshit. Apple Clang 6.0 does not define them.
86 // Later version of Clang defines them and results in warnings.
87 #if defined(__clang__)
88 # ifndef _blsr_u32
89 # define _blsr_u32 __blsr_u32
90 # endif
91 # ifndef _blsr_u64
92 # define _blsr_u64 __blsr_u64
93 # endif
94 # ifndef _tzcnt_u32
95 # define _tzcnt_u32 __tzcnt_u32
96 # endif
97 # ifndef _tzcnt_u64
98 # define _tzcnt_u64 __tzcnt_u64
99 # endif
100 #endif
101 
102 #endif // CRYPTOPP_DOXYGEN_PROCESSING
103 
104 #if CRYPTOPP_DOXYGEN_PROCESSING
105 /// \brief The maximum value of a machine word
106 /// \details <tt>SIZE_MAX</tt> provides the maximum value of a machine word. The value
107 /// is <tt>0xffffffff</tt> on 32-bit targets, and <tt>0xffffffffffffffff</tt> on 64-bit
108 /// targets.
109 /// \details If <tt>SIZE_MAX</tt> is not defined, then <tt>__SIZE_MAX__</tt> is used if
110 /// defined. If not defined, then <tt>SIZE_T_MAX</tt> is used if defined. If not defined,
111 /// then the library uses <tt>std::numeric_limits<size_t>::max()</tt>.
112 /// \details The library prefers <tt>__SIZE_MAX__</tt> or <tt>__SIZE_T_MAX__</tt> because
113 /// they are effectively <tt>constexpr</tt> that is optimized well by all compilers.
114 /// <tt>std::numeric_limits<size_t>::max()</tt> is not always a <tt>constexpr</tt>, and
115 /// it is not always optimized well.
116 # define SIZE_MAX ...
117 #else
118 // Its amazing portability problems still plague this simple concept in 2015.
119 // http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
120 // Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
121 #ifndef SIZE_MAX
122 # if defined(__SIZE_MAX__)
123 # define SIZE_MAX __SIZE_MAX__
124 # elif defined(SIZE_T_MAX)
125 # define SIZE_MAX SIZE_T_MAX
126 # elif defined(__SIZE_TYPE__)
127 # define SIZE_MAX (~(__SIZE_TYPE__)0)
128 # else
129 # define SIZE_MAX ((std::numeric_limits<size_t>::max)())
130 # endif
131 #endif
132 
133 #endif // CRYPTOPP_DOXYGEN_PROCESSING
134 
135 NAMESPACE_BEGIN(CryptoPP)
136 
137 // Forward declaration for IntToString specialization
138 class Integer;
139 
140 // ************** compile-time assertion ***************
141 
142 #if CRYPTOPP_DOXYGEN_PROCESSING
143 /// \brief Compile time assertion
144 /// \param expr the expression to evaluate
145 /// \details Asserts the expression expr though a dummy struct.
146 #define CRYPTOPP_COMPILE_ASSERT(expr) { ... }
147 #else // CRYPTOPP_DOXYGEN_PROCESSING
148 template <bool b>
149 struct CompileAssert
150 {
151  static char dummy[2*b-1];
152 };
153 
154 #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
155 #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
156 #define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
157 #else
158 # if defined(__GNUC__)
159 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
160  static CompileAssert<(assertion)> \
161  CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused))
162 # else
163 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
164  static CompileAssert<(assertion)> \
165  CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)
166 # endif // __GNUC__
167 #endif
168 #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
169 #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
170 
171 #endif // CRYPTOPP_DOXYGEN_PROCESSING
172 
173 // ************** count elements in an array ***************
174 
175 #if CRYPTOPP_DOXYGEN_PROCESSING
176 /// \brief Counts elements in an array
177 /// \param arr an array of elements
178 /// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined
179 /// to <tt>_countof(x)</tt> to ensure correct results for pointers.
180 /// \note COUNTOF does not produce correct results with pointers, and an array must be used.
181 /// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using
182 /// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms.
183 # define COUNTOF(arr)
184 #else
185 // VS2005 added _countof
186 #ifndef COUNTOF
187 # if defined(_MSC_VER) && (_MSC_VER >= 1400)
188 # define COUNTOF(x) _countof(x)
189 # else
190 # define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
191 # endif
192 #endif // COUNTOF
193 #endif // CRYPTOPP_DOXYGEN_PROCESSING
194 
195 // ************** misc classes ***************
196 
197 /// \brief An Empty class
198 /// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists.
199 class CRYPTOPP_DLL Empty
200 {
201 };
202 
203 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
204 template <class BASE1, class BASE2>
205 class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
206 {
207 };
208 
209 template <class BASE1, class BASE2, class BASE3>
210 class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
211 {
212 };
213 #endif // CRYPTOPP_DOXYGEN_PROCESSING
214 
215 /// \tparam T class or type
216 /// \brief Uses encapsulation to hide an object in derived classes
217 /// \details The object T is declared as protected.
218 template <class T>
220 {
221 protected:
222  T m_object;
223 };
224 
225 /// \brief Ensures an object is not copyable
226 /// \details NotCopyable ensures an object is not copyable by making the
227 /// copy constructor and assignment operator private. Deleters are used
228 /// under C++11.
229 /// \sa Clonable class
231 {
232 public:
233  NotCopyable() {}
234 #if CRYPTOPP_CXX11_DELETED_FUNCTIONS
235  NotCopyable(const NotCopyable &) = delete;
236  void operator=(const NotCopyable &) = delete;
237 #else
238 private:
239  NotCopyable(const NotCopyable &);
240  void operator=(const NotCopyable &);
241 #endif
242 };
243 
244 /// \brief An object factory function
245 /// \tparam T class or type
246 /// \details NewObject overloads operator()().
247 template <class T>
248 struct NewObject
249 {
250  T* operator()() const {return new T;}
251 };
252 
253 #if CRYPTOPP_DOXYGEN_PROCESSING
254 /// \brief A memory barrier
255 /// \details MEMORY_BARRIER attempts to ensure reads and writes are completed
256 /// in the absence of a language synchronization point. It is used by the
257 /// Singleton class if the compiler supports it. The barrier is provided at the
258 /// customary places in a double-checked initialization.
259 /// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if
260 /// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>,
261 /// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used.
262 #define MEMORY_BARRIER ...
263 #else
264 #if defined(CRYPTOPP_CXX11_ATOMICS)
265 # define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel)
266 #elif (_MSC_VER >= 1400)
267 # pragma intrinsic(_ReadWriteBarrier)
268 # define MEMORY_BARRIER() _ReadWriteBarrier()
269 #elif defined(__INTEL_COMPILER)
270 # define MEMORY_BARRIER() __memory_barrier()
271 #elif defined(__GNUC__) || defined(__clang__)
272 # define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
273 #else
274 # define MEMORY_BARRIER()
275 #endif
276 #endif // CRYPTOPP_DOXYGEN_PROCESSING
277 
278 /// \brief Restricts the instantiation of a class to one static object without locks
279 /// \tparam T the class or type
280 /// \tparam F the object factory for T
281 /// \tparam instance an instance counter for the class object
282 /// \details This class safely initializes a static object in a multithreaded environment. For C++03
283 /// and below it will do so without using locks for portability. If two threads call Ref() at the same
284 /// time, they may get back different references, and one object may end up being memory leaked. This
285 /// is by design and it avoids a subltle initialization problem ina multithreaded environment with thread
286 /// local storage on early Windows platforms, like Windows XP and Windows 2003.
287 /// \details For C++11 and above, a standard double-checked locking pattern with thread fences
288 /// are used. The locks and fences are standard and do not hinder portability.
289 /// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and
290 /// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should
291 /// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015.
292 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking
293 /// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic
294 /// Initialization and Destruction with Concurrency</A> and
295 /// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN.
296 /// \since Crypto++ 5.2
297 template <class T, class F = NewObject<T>, int instance=0>
299 {
300 public:
301  Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
302 
303  // prevent this function from being inlined
304  CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
305 
306 private:
307  F m_objectFactory;
308 };
309 
310 /// \brief Return a reference to the inner Singleton object
311 /// \tparam T the class or type
312 /// \tparam F the object factory for T
313 /// \tparam instance an instance counter for the class object
314 /// \details Ref() is used to create the object using the object factory. The
315 /// object is only created once with the limitations discussed in the class documentation.
316 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A>
317 /// \since Crypto++ 5.2
318 template <class T, class F, int instance>
319  const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
320 {
321 #if defined(CRYPTOPP_CXX11_ATOMICS) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_DYNAMIC_INIT)
322  static std::mutex s_mutex;
323  static std::atomic<T*> s_pObject;
324 
325  T *p = s_pObject.load(std::memory_order_relaxed);
326  std::atomic_thread_fence(std::memory_order_acquire);
327 
328  if (p)
329  return *p;
330 
331  std::lock_guard<std::mutex> lock(s_mutex);
332  p = s_pObject.load(std::memory_order_relaxed);
333  std::atomic_thread_fence(std::memory_order_acquire);
334 
335  if (p)
336  return *p;
337 
338  T *newObject = m_objectFactory();
339  s_pObject.store(newObject, std::memory_order_relaxed);
340  std::atomic_thread_fence(std::memory_order_release);
341 
342  return *newObject;
343 #else
344  static volatile simple_ptr<T> s_pObject;
345  T *p = s_pObject.m_p;
346  MEMORY_BARRIER();
347 
348  if (p)
349  return *p;
350 
351  T *newObject = m_objectFactory();
352  p = s_pObject.m_p;
353  MEMORY_BARRIER();
354 
355  if (p)
356  {
357  delete newObject;
358  return *p;
359  }
360 
361  s_pObject.m_p = newObject;
362  MEMORY_BARRIER();
363 
364  return *newObject;
365 #endif
366 }
367 
368 // ************** misc functions ***************
369 
370 /// \brief Create a pointer with an offset
371 /// \tparam PTR a pointer type
372 /// \tparam OFF a size type
373 /// \param pointer a pointer
374 /// \param offset a offset into the pointer
375 /// \details PtrAdd can be used to squash Clang and GCC
376 /// UBsan findings for pointer addition and subtraction.
377 template <typename PTR, typename OFF>
378 inline PTR PtrAdd(PTR pointer, OFF offset)
379 {
380  return pointer+static_cast<ptrdiff_t>(offset);
381 }
382 
383 /// \brief Create a pointer with an offset
384 /// \tparam PTR a pointer type
385 /// \tparam OFF a size type
386 /// \param pointer a pointer
387 /// \param offset a offset into the pointer
388 /// \details PtrSub can be used to squash Clang and GCC
389 /// UBsan findings for pointer addition and subtraction.
390 template <typename PTR, typename OFF>
391 inline PTR PtrSub(PTR pointer, OFF offset)
392 {
393  return pointer-static_cast<ptrdiff_t>(offset);
394 }
395 
396 /// \brief Determine pointer difference
397 /// \tparam PTR a pointer type
398 /// \param pointer1 the first pointer
399 /// \param pointer2 the second pointer
400 /// \details PtrDiff can be used to squash Clang and GCC
401 /// UBsan findings for pointer addition and subtraction.
402 /// pointer1 and pointer2 must point to the same object or
403 /// array (or one past the end), and yields the number of
404 /// elements (not bytes) difference.
405 template <typename PTR>
406 inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
407 {
408  return pointer1 - pointer2;
409 }
410 
411 /// \brief Determine pointer difference
412 /// \tparam PTR a pointer type
413 /// \param pointer1 the first pointer
414 /// \param pointer2 the second pointer
415 /// \details PtrByteDiff can be used to squash Clang and GCC
416 /// UBsan findings for pointer addition and subtraction.
417 /// pointer1 and pointer2 must point to the same object or
418 /// array (or one past the end), and yields the number of
419 /// bytes (not elements) difference.
420 template <typename PTR>
421 inline size_t PtrByteDiff(const PTR pointer1, const PTR pointer2)
422 {
423  return (size_t)(reinterpret_cast<uintptr_t>(pointer1) - reinterpret_cast<uintptr_t>(pointer2));
424 }
425 
426 /// \brief Pointer to the first element of a string
427 /// \param str std::string
428 /// \details BytePtr returns NULL pointer for an empty string.
429 /// \return Pointer to the first element of a string
430 inline byte* BytePtr(std::string& str)
431 {
432  // Caller wants a writeable pointer
433  CRYPTOPP_ASSERT(str.empty() == false);
434 
435  if (str.empty())
436  return NULLPTR;
437  return reinterpret_cast<byte*>(&str[0]);
438 }
439 
440 /// \brief Const pointer to the first element of a string
441 /// \param str std::string
442 /// \details ConstBytePtr returns non-NULL pointer for an empty string.
443 /// \return Pointer to the first element of a string
444 inline const byte* ConstBytePtr(const std::string& str)
445 {
446  // Use c_str() so a pointer is always available
447  return reinterpret_cast<const byte*>(str.c_str());
448 }
449 
450 /// \brief Size of a string
451 /// \param str std::string
452 /// \return size of a string
453 inline size_t BytePtrSize(const std::string& str)
454 {
455  return str.size();
456 }
457 
458 #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
459 
460 /// \brief Bounds checking replacement for memcpy()
461 /// \param dest pointer to the desination memory block
462 /// \param sizeInBytes size of the desination memory block, in bytes
463 /// \param src pointer to the source memory block
464 /// \param count the number of bytes to copy
465 /// \throws InvalidArgument
466 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
467 /// unsafe functions like memcpy(), strcpy() and memmove(). However,
468 /// not all standard libraries provides them, like Glibc. The library's
469 /// memcpy_s() is a near-drop in replacement. Its only a near-replacement
470 /// because the library's version throws an InvalidArgument on a bounds violation.
471 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
472 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
473 /// makes memcpy_s() and memmove_s() available. The library will also optionally
474 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
475 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
476 /// \details memcpy_s() will assert the pointers src and dest are not NULL
477 /// in debug builds. Passing NULL for either pointer is undefined behavior.
478 inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
479 {
480  // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
481 
482  // Pointers must be valid; otherwise undefined behavior
483  CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
484  // Restricted pointers. We want to check ranges, but it is not clear how to do it.
485  CRYPTOPP_ASSERT(src != dest);
486  // Destination buffer must be large enough to satsify request
487  CRYPTOPP_ASSERT(sizeInBytes >= count);
488 
489  if (count > sizeInBytes)
490  throw InvalidArgument("memcpy_s: buffer overflow");
491 
492 #if CRYPTOPP_MSC_VERSION
493 # pragma warning(push)
494 # pragma warning(disable: 4996)
495 # if (CRYPTOPP_MSC_VERSION >= 1400)
496 # pragma warning(disable: 6386)
497 # endif
498 #endif
499  memcpy(dest, src, count);
500 #if CRYPTOPP_MSC_VERSION
501 # pragma warning(pop)
502 #endif
503 }
504 
505 /// \brief Bounds checking replacement for memmove()
506 /// \param dest pointer to the desination memory block
507 /// \param sizeInBytes size of the desination memory block, in bytes
508 /// \param src pointer to the source memory block
509 /// \param count the number of bytes to copy
510 /// \throws InvalidArgument
511 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
512 /// unsafe functions like memcpy(), strcpy() and memmove(). However,
513 /// not all standard libraries provides them, like Glibc. The library's
514 /// memmove_s() is a near-drop in replacement. Its only a near-replacement
515 /// because the library's version throws an InvalidArgument on a bounds violation.
516 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
517 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
518 /// makes memcpy_s() and memmove_s() available. The library will also optionally
519 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
520 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
521 /// \details memmove_s() will assert the pointers src and dest are not NULL
522 /// in debug builds. Passing NULL for either pointer is undefined behavior.
523 inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
524 {
525  // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
526 
527  // Pointers must be valid; otherwise undefined behavior
528  CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
529  // Destination buffer must be large enough to satsify request
530  CRYPTOPP_ASSERT(sizeInBytes >= count);
531 
532  if (count > sizeInBytes)
533  throw InvalidArgument("memmove_s: buffer overflow");
534 
535 #if CRYPTOPP_MSC_VERSION
536 # pragma warning(push)
537 # pragma warning(disable: 4996)
538 # if (CRYPTOPP_MSC_VERSION >= 1400)
539 # pragma warning(disable: 6386)
540 # endif
541 #endif
542  memmove(dest, src, count);
543 #if CRYPTOPP_MSC_VERSION
544 # pragma warning(pop)
545 #endif
546 }
547 
548 #if __BORLANDC__ >= 0x620
549 // C++Builder 2010 workaround: can't use std::memcpy_s because it doesn't allow 0 lengths
550 # define memcpy_s CryptoPP::memcpy_s
551 # define memmove_s CryptoPP::memmove_s
552 #endif
553 
554 #endif // __STDC_WANT_SECURE_LIB__
555 
556 /// \brief Swaps two variables which are arrays
557 /// \tparam T class or type
558 /// \param a the first value
559 /// \param b the second value
560 /// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt>
561 /// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers
562 /// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.
563 /// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables
564 /// in C++03 given its an opaque type and an array?</A> on Stack Overflow.
565 template <class T>
566 inline void vec_swap(T& a, T& b)
567 {
568  // __m128i is an unsigned long long[2], and support for swapping it was
569  // not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while
570  // SunCC 12.4 consumes it without -std=c++11.
571 #if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
572  T t;
573  t=a, a=b, b=t;
574 #else
575  std::swap(a, b);
576 #endif
577 }
578 
579 /// \brief Memory block initializer and eraser that attempts to survive optimizations
580 /// \param ptr pointer to the memory block being written
581 /// \param value the integer value to write for each byte
582 /// \param num the size of the source memory block, in bytes
583 /// \details Internally the function calls memset with the value value, and receives the
584 /// return value from memset as a <tt>volatile</tt> pointer.
585 inline void * memset_z(void *ptr, int value, size_t num)
586 {
587 // avoid extranous warning on GCC 4.3.2 Ubuntu 8.10
588 #if CRYPTOPP_GCC_VERSION >= 30001
589  if (__builtin_constant_p(num) && num==0)
590  return ptr;
591 #endif
592  volatile void* x = memset(ptr, value, num);
593  return const_cast<void*>(x);
594 }
595 
596 /// \brief Replacement function for std::min
597 /// \tparam T class or type
598 /// \param a the first value
599 /// \param b the second value
600 /// \returns the minimum value based on a comparison of <tt>b < a</tt> using <tt>operator<</tt>
601 /// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
602 template <class T> inline const T& STDMIN(const T& a, const T& b)
603 {
604  return b < a ? b : a;
605 }
606 
607 /// \brief Replacement function for std::max
608 /// \tparam T class or type
609 /// \param a the first value
610 /// \param b the second value
611 /// \returns the minimum value based on a comparison of <tt>a < b</tt> using <tt>operator<</tt>
612 /// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
613 template <class T> inline const T& STDMAX(const T& a, const T& b)
614 {
615  return a < b ? b : a;
616 }
617 
618 #if CRYPTOPP_MSC_VERSION
619 # pragma warning(push)
620 # pragma warning(disable: 4389)
621 #endif
622 
623 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
624 # pragma GCC diagnostic push
625 # pragma GCC diagnostic ignored "-Wsign-compare"
626 # pragma GCC diagnostic ignored "-Wstrict-overflow"
627 # if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
628 # pragma GCC diagnostic ignored "-Wtautological-compare"
629 # elif (CRYPTOPP_GCC_VERSION >= 40300)
630 # pragma GCC diagnostic ignored "-Wtype-limits"
631 # endif
632 #endif
633 
634 /// \brief Safe comparison of values that could be neagtive and incorrectly promoted
635 /// \tparam T1 class or type
636 /// \tparam T2 class or type
637 /// \param a the first value
638 /// \param b the second value
639 /// \returns the minimum value based on a comparison a and b using <tt>operator&lt;</tt>.
640 /// \details The comparison <tt>b < a</tt> is performed and the value returned is a's type T1.
641 template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
642 {
643  CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
644  if (sizeof(T1)<=sizeof(T2))
645  return b < (T2)a ? (T1)b : a;
646  else
647  return (T1)b < a ? (T1)b : a;
648 }
649 
650 /// \brief Tests whether a conversion from -> to is safe to perform
651 /// \tparam T1 class or type
652 /// \tparam T2 class or type
653 /// \param from the first value
654 /// \param to the second value
655 /// \returns true if its safe to convert from into to, false otherwise.
656 template <class T1, class T2>
657 inline bool SafeConvert(T1 from, T2 &to)
658 {
659  to = static_cast<T2>(from);
660  if (from != to || (from > 0) != (to > 0))
661  return false;
662  return true;
663 }
664 
665 /// \brief Converts a value to a string
666 /// \tparam T class or type
667 /// \param value the value to convert
668 /// \param base the base to use during the conversion
669 /// \returns the string representation of value in base.
670 template <class T>
671 std::string IntToString(T value, unsigned int base = 10)
672 {
673  // Hack... set the high bit for uppercase.
674  const unsigned int HIGH_BIT = (1U << 31);
675  const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
676  base &= ~HIGH_BIT;
677 
678  CRYPTOPP_ASSERT(base >= 2);
679  if (value == 0)
680  return "0";
681 
682  bool negate = false;
683  if (value < 0)
684  {
685  negate = true;
686  value = 0-value; // VC .NET does not like -a
687  }
688  std::string result;
689  while (value > 0)
690  {
691  T digit = value % base;
692  result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
693  value /= base;
694  }
695  if (negate)
696  result = "-" + result;
697  return result;
698 }
699 
700 /// \brief Converts an unsigned value to a string
701 /// \param value the value to convert
702 /// \param base the base to use during the conversion
703 /// \returns the string representation of value in base.
704 /// \details this template function specialization was added to suppress
705 /// Coverity findings on IntToString() with unsigned types.
706 template <> CRYPTOPP_DLL
707 std::string IntToString<word64>(word64 value, unsigned int base);
708 
709 /// \brief Converts an Integer to a string
710 /// \param value the Integer to convert
711 /// \param base the base to use during the conversion
712 /// \returns the string representation of value in base.
713 /// \details This is a template specialization of IntToString(). Use it
714 /// like IntToString():
715 /// <pre>
716 /// // Print integer in base 10
717 /// Integer n...
718 /// std::string s = IntToString(n, 10);
719 /// </pre>
720 /// \details The string is presented with lowercase letters by default. A
721 /// hack is available to switch to uppercase letters without modifying
722 /// the function signature.
723 /// <pre>
724 /// // Print integer in base 16, uppercase letters
725 /// Integer n...
726 /// const unsigned int UPPER = (1 << 31);
727 /// std::string s = IntToString(n, (UPPER | 16));</pre>
728 template <> CRYPTOPP_DLL
729 std::string IntToString<Integer>(Integer value, unsigned int base);
730 
731 #if CRYPTOPP_MSC_VERSION
732 # pragma warning(pop)
733 #endif
734 
735 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
736 # pragma GCC diagnostic pop
737 #endif
738 
739 #define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
740 
741 // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
742 #define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
743 // these may be faster on other CPUs/compilers
744 // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
745 // #define GETBYTE(x, y) (((byte *)&(x))[y])
746 
747 #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
748 
749 /// \brief Returns the parity of a value
750 /// \tparam T class or type
751 /// \param value the value to provide the parity
752 /// \returns 1 if the number 1-bits in the value is odd, 0 otherwise
753 template <class T>
754 unsigned int Parity(T value)
755 {
756  for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
757  value ^= value >> i;
758  return (unsigned int)value&1;
759 }
760 
761 /// \brief Returns the number of 8-bit bytes or octets required for a value
762 /// \tparam T class or type
763 /// \param value the value to test
764 /// \returns the minimum number of 8-bit bytes or octets required to represent a value
765 template <class T>
766 unsigned int BytePrecision(const T &value)
767 {
768  if (!value)
769  return 0;
770 
771  unsigned int l=0, h=8*sizeof(value);
772  while (h-l > 8)
773  {
774  unsigned int t = (l+h)/2;
775  if (value >> t)
776  l = t;
777  else
778  h = t;
779  }
780 
781  return h/8;
782 }
783 
784 /// \brief Returns the number of bits required for a value
785 /// \tparam T class or type
786 /// \param value the value to test
787 /// \returns the maximum number of bits required to represent a value.
788 template <class T>
789 unsigned int BitPrecision(const T &value)
790 {
791  if (!value)
792  return 0;
793 
794  unsigned int l=0, h=8*sizeof(value);
795 
796  while (h-l > 1)
797  {
798  unsigned int t = (l+h)/2;
799  if (value >> t)
800  l = t;
801  else
802  h = t;
803  }
804 
805  return h;
806 }
807 
808 /// Determines the number of trailing 0-bits in a value
809 /// \param v the 32-bit value to test
810 /// \returns the number of trailing 0-bits in v, starting at the least significant bit position
811 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
812 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
813 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
814 inline unsigned int TrailingZeros(word32 v)
815 {
816  // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
817  // We don't enable for Microsoft because it requires a runtime check.
818  // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
819  CRYPTOPP_ASSERT(v != 0);
820 #if defined(__BMI__)
821  return (unsigned int)_tzcnt_u32(v);
822 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
823  return (unsigned int)__builtin_ctz(v);
824 #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
825  unsigned long result;
826  _BitScanForward(&result, v);
827  return static_cast<unsigned int>(result);
828 #else
829  // from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
830  static const int MultiplyDeBruijnBitPosition[32] =
831  {
832  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
833  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
834  };
835  return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
836 #endif
837 }
838 
839 /// Determines the number of trailing 0-bits in a value
840 /// \param v the 64-bit value to test
841 /// \returns the number of trailing 0-bits in v, starting at the least significant bit position
842 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
843 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
844 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
845 inline unsigned int TrailingZeros(word64 v)
846 {
847  // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
848  // We don't enable for Microsoft because it requires a runtime check.
849  // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
850  CRYPTOPP_ASSERT(v != 0);
851 #if defined(__BMI__) && defined(__x86_64__)
852  return (unsigned int)_tzcnt_u64(v);
853 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
854  return (unsigned int)__builtin_ctzll(v);
855 #elif defined(_MSC_VER) && (_MSC_VER >= 1400) && (defined(_M_X64) || defined(_M_IA64))
856  unsigned long result;
857  _BitScanForward64(&result, v);
858  return static_cast<unsigned int>(result);
859 #else
860  return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
861 #endif
862 }
863 
864 /// \brief Truncates the value to the specified number of bits.
865 /// \tparam T class or type
866 /// \param value the value to truncate or mask
867 /// \param bits the number of bits to truncate or mask
868 /// \returns the value truncated to the specified number of bits, starting at the least
869 /// significant bit position
870 /// \details This function masks the low-order bits of value and returns the result. The
871 /// mask is created with <tt>(1 << bits) - 1</tt>.
872 template <class T>
873 inline T Crop(T value, size_t bits)
874 {
875  if (bits < 8*sizeof(value))
876  return T(value & ((T(1) << bits) - 1));
877  else
878  return value;
879 }
880 
881 /// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
882 /// \param bitCount the number of bits
883 /// \returns the minimum number of 8-bit bytes or octets required by bitCount
884 /// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
885 inline size_t BitsToBytes(size_t bitCount)
886 {
887  return ((bitCount+7)/(8));
888 }
889 
890 /// \brief Returns the number of words required for the specified number of bytes
891 /// \param byteCount the number of bytes
892 /// \returns the minimum number of words required by byteCount
893 /// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
894 /// <tt>WORD_SIZE</tt> is defined in config.h
895 inline size_t BytesToWords(size_t byteCount)
896 {
897  return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
898 }
899 
900 /// \brief Returns the number of words required for the specified number of bits
901 /// \param bitCount the number of bits
902 /// \returns the minimum number of words required by bitCount
903 /// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
904 /// <tt>WORD_BITS</tt> is defined in config.h
905 inline size_t BitsToWords(size_t bitCount)
906 {
907  return ((bitCount+WORD_BITS-1)/(WORD_BITS));
908 }
909 
910 /// \brief Returns the number of double words required for the specified number of bits
911 /// \param bitCount the number of bits
912 /// \returns the minimum number of double words required by bitCount
913 /// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
914 /// <tt>WORD_BITS</tt> is defined in config.h
915 inline size_t BitsToDwords(size_t bitCount)
916 {
917  return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
918 }
919 
920 /// Performs an XOR of a buffer with a mask
921 /// \param buf the buffer to XOR with the mask
922 /// \param mask the mask to XOR with the buffer
923 /// \param count the size of the buffers, in bytes
924 /// \details The function effectively visits each element in the buffers and performs
925 /// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
926 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
927 
928 /// Performs an XOR of an input buffer with a mask and stores the result in an output buffer
929 /// \param output the destination buffer
930 /// \param input the source buffer to XOR with the mask
931 /// \param mask the mask buffer to XOR with the input buffer
932 /// \param count the size of the buffers, in bytes
933 /// \details The function effectively visits each element in the buffers and performs
934 /// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
935 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
936 
937 /// \brief Performs a near constant-time comparison of two equally sized buffers
938 /// \param buf1 the first buffer
939 /// \param buf2 the second buffer
940 /// \param count the size of the buffers, in bytes
941 /// \details VerifyBufsEqual performs an XOR of the elements in two equally sized
942 /// buffers and retruns a result based on the XOR operation. A count of 0 returns
943 /// true because two empty buffers are considered equal.
944 /// \details The function is near constant-time because CPU micro-code timings could
945 /// affect the "constant-ness". Calling code is responsible for mitigating timing
946 /// attacks if the buffers are not equally sized.
947 /// \sa ModPowerOf2
948 CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
949 
950 /// \brief Tests whether a value is a power of 2
951 /// \param value the value to test
952 /// \returns true if value is a power of 2, false otherwise
953 /// \details The function creates a mask of <tt>value - 1</tt> and returns the result
954 /// of an AND operation compared to 0. If value is 0 or less than 0, then the function
955 /// returns false.
956 template <class T>
957 inline bool IsPowerOf2(const T &value)
958 {
959  return value > 0 && (value & (value-1)) == 0;
960 }
961 
962 #if defined(__BMI__)
963 template <>
964 inline bool IsPowerOf2<word32>(const word32 &value)
965 {
966  return value > 0 && _blsr_u32(value) == 0;
967 }
968 
969 # if defined(__x86_64__)
970 template <>
971 inline bool IsPowerOf2<word64>(const word64 &value)
972 {
973  return value > 0 && _blsr_u64(value) == 0;
974 }
975 # endif // __x86_64__
976 #endif // __BMI__
977 
978 /// \brief Provide the minimum value for a type
979 /// \tparam T type of class
980 /// \returns the minimum value of the type or class
981 /// \details NumericLimitsMin() was introduced for Clang at <A
982 /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364,
983 /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>.
984 /// \details NumericLimitsMin() requires a specialization for <tt>T</tt>,
985 /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return
986 /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize
987 /// <tt>numeric_limits</tt> for the type.
988 /// \since Crypto++ 8.1
989 template<class T>
991 {
992  CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
993  return (std::numeric_limits<T>::min)();
994 }
995 
996 /// \brief Provide the maximum value for a type
997 /// \tparam T type of class
998 /// \returns the maximum value of the type or class
999 /// \details NumericLimitsMax() was introduced for Clang at <A
1000 /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364,
1001 /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>.
1002 /// \details NumericLimitsMax() requires a specialization for <tt>T</tt>,
1003 /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return
1004 /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize
1005 /// <tt>numeric_limits</tt> for the type.
1006 /// \since Crypto++ 8.1
1007 template<class T>
1009 {
1010  CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
1011  return (std::numeric_limits<T>::max)();
1012 }
1013 
1014 // NumericLimitsMin and NumericLimitsMax added for word128 types,
1015 // see http://github.com/weidai11/cryptopp/issues/364
1016 #if defined(CRYPTOPP_WORD128_AVAILABLE)
1017 template<>
1018 inline word128 NumericLimitsMin()
1019 {
1020  return 0;
1021 }
1022 template<>
1023 inline word128 NumericLimitsMax()
1024 {
1025  return (static_cast<word128>(LWORD_MAX) << 64U) | LWORD_MAX;
1026 }
1027 #endif
1028 
1029 /// \brief Performs a saturating subtract clamped at 0
1030 /// \tparam T1 class or type
1031 /// \tparam T2 class or type
1032 /// \param a the minuend
1033 /// \param b the subtrahend
1034 /// \returns the difference produced by the saturating subtract
1035 /// \details Saturating arithmetic restricts results to a fixed range. Results that are
1036 /// less than 0 are clamped at 0.
1037 /// \details Use of saturating arithmetic in places can be advantageous because it can
1038 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
1039 template <class T1, class T2>
1040 inline T1 SaturatingSubtract(const T1 &a, const T2 &b)
1041 {
1042  // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
1043  return T1((a > b) ? (a - b) : 0);
1044 }
1045 
1046 /// \brief Performs a saturating subtract clamped at 1
1047 /// \tparam T1 class or type
1048 /// \tparam T2 class or type
1049 /// \param a the minuend
1050 /// \param b the subtrahend
1051 /// \returns the difference produced by the saturating subtract
1052 /// \details Saturating arithmetic restricts results to a fixed range. Results that are
1053 /// less than 1 are clamped at 1.
1054 /// \details Use of saturating arithmetic in places can be advantageous because it can
1055 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
1056 template <class T1, class T2>
1057 inline T1 SaturatingSubtract1(const T1 &a, const T2 &b)
1058 {
1059  // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
1060  return T1((a > b) ? (a - b) : 1);
1061 }
1062 
1063 /// \brief Reduces a value to a power of 2
1064 /// \tparam T1 class or type
1065 /// \tparam T2 class or type
1066 /// \param a the first value
1067 /// \param b the second value
1068 /// \returns ModPowerOf2() returns <tt>a & (b-1)</tt>. <tt>b</tt> must be a power of 2.
1069 /// Use IsPowerOf2() to determine if <tt>b</tt> is a suitable candidate.
1070 /// \sa IsPowerOf2
1071 template <class T1, class T2>
1072 inline T2 ModPowerOf2(const T1 &a, const T2 &b)
1073 {
1075  // Coverity finding CID 170383 Overflowed return value (INTEGER_OVERFLOW)
1076  return T2(a) & SaturatingSubtract(b,1U);
1077 }
1078 
1079 /// \brief Rounds a value down to a multiple of a second value
1080 /// \tparam T1 class or type
1081 /// \tparam T2 class or type
1082 /// \param n the value to reduce
1083 /// \param m the value to reduce \n to to a multiple
1084 /// \returns the possibly unmodified value \n
1085 /// \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns
1086 /// the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned.
1087 /// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
1088 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
1089 /// debug builds when practical, but allows you to perform the operation in release builds.
1090 template <class T1, class T2>
1091 inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
1092 {
1093  // http://github.com/weidai11/cryptopp/issues/364
1094 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
1095  CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
1096  CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
1097 #endif
1098 
1099  CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
1100  CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
1101 
1102  if (IsPowerOf2(m))
1103  return n - ModPowerOf2(n, m);
1104  else
1105  return n - n%m;
1106 }
1107 
1108 /// \brief Rounds a value up to a multiple of a second value
1109 /// \tparam T1 class or type
1110 /// \tparam T2 class or type
1111 /// \param n the value to reduce
1112 /// \param m the value to reduce \n to to a multiple
1113 /// \returns the possibly unmodified value \n
1114 /// \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function
1115 /// returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is
1116 /// returned. If the value n would overflow, then an InvalidArgument exception is thrown.
1117 /// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
1118 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
1119 /// debug builds when practical, but allows you to perform the operation in release builds.
1120 template <class T1, class T2>
1121 inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
1122 {
1123  // http://github.com/weidai11/cryptopp/issues/364
1124 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
1125  CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
1126  CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
1127 #endif
1128 
1129  CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
1130  CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
1131 
1132  if (NumericLimitsMax<T1>() - m + 1 < n)
1133  throw InvalidArgument("RoundUpToMultipleOf: integer overflow");
1134  return RoundDownToMultipleOf(T1(n+m-1), m);
1135 }
1136 
1137 /// \brief Returns the minimum alignment requirements of a type
1138 /// \tparam T class or type
1139 /// \returns the minimum alignment requirements of <tt>T</tt>, in bytes
1140 /// \details Internally the function calls C++11's <tt>alignof</tt> if available. If not
1141 /// available, then the function uses compiler specific extensions such as
1142 /// <tt>__alignof</tt> and <tt>_alignof_</tt>. If an extension is not available, then
1143 /// the function uses <tt>__BIGGEST_ALIGNMENT__</tt> if <tt>__BIGGEST_ALIGNMENT__</tt>
1144 /// is smaller than <tt>sizeof(T)</tt>. <tt>sizeof(T)</tt> is used if all others are
1145 /// not available.
1146 template <class T>
1147 inline unsigned int GetAlignmentOf()
1148 {
1149 #if defined(CRYPTOPP_CXX11_ALIGNOF)
1150  return alignof(T);
1151 #elif (_MSC_VER >= 1300)
1152  return __alignof(T);
1153 #elif defined(__GNUC__)
1154  return __alignof__(T);
1155 #elif defined(__SUNPRO_CC)
1156  return __alignof__(T);
1157 #elif defined(__IBM_ALIGNOF__)
1158  return __alignof__(T);
1159 #elif CRYPTOPP_BOOL_SLOW_WORD64
1160  return UnsignedMin(4U, sizeof(T));
1161 #else
1162 # if __BIGGEST_ALIGNMENT__
1163  if (__BIGGEST_ALIGNMENT__ < sizeof(T))
1164  return __BIGGEST_ALIGNMENT__;
1165  else
1166 # endif
1167  return sizeof(T);
1168 #endif
1169 }
1170 
1171 /// \brief Determines whether ptr is aligned to a minimum value
1172 /// \param ptr the pointer being checked for alignment
1173 /// \param alignment the alignment value to test the pointer against
1174 /// \returns true if <tt>ptr</tt> is aligned on at least <tt>alignment</tt>
1175 /// boundary, false otherwise
1176 /// \details Internally the function tests whether alignment is 1. If so,
1177 /// the function returns true. If not, then the function effectively
1178 /// performs a modular reduction and returns true if the residue is 0.
1179 inline bool IsAlignedOn(const void *ptr, unsigned int alignment)
1180 {
1181  const uintptr_t x = reinterpret_cast<uintptr_t>(ptr);
1182  return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2(x, alignment) == 0 : x % alignment == 0);
1183 }
1184 
1185 /// \brief Determines whether ptr is minimally aligned
1186 /// \tparam T class or type
1187 /// \param ptr the pointer to check for alignment
1188 /// \returns true if <tt>ptr</tt> is aligned to at least <tt>T</tt>
1189 /// boundary, false otherwise
1190 /// \details Internally the function calls IsAlignedOn with a second
1191 /// parameter of GetAlignmentOf<T>.
1192 template <class T>
1193 inline bool IsAligned(const void *ptr)
1194 {
1195  return IsAlignedOn(ptr, GetAlignmentOf<T>());
1196 }
1197 
1198 #if (CRYPTOPP_LITTLE_ENDIAN)
1199  typedef LittleEndian NativeByteOrder;
1200 #elif (CRYPTOPP_BIG_ENDIAN)
1201  typedef BigEndian NativeByteOrder;
1202 #else
1203 # error "Unable to determine endian-ness"
1204 #endif
1205 
1206 /// \brief Returns NativeByteOrder as an enumerated ByteOrder value
1207 /// \returns LittleEndian if the native byte order is little-endian,
1208 /// and BigEndian if the native byte order is big-endian
1209 /// \details NativeByteOrder is a typedef depending on the platform.
1210 /// If CRYPTOPP_LITTLE_ENDIAN is set in config.h, then
1211 /// GetNativeByteOrder returns LittleEndian. If CRYPTOPP_BIG_ENDIAN
1212 /// is set, then GetNativeByteOrder returns BigEndian.
1213 /// \note There are other byte orders besides little- and big-endian,
1214 /// and they include bi-endian and PDP-endian. If a system is neither
1215 /// little-endian nor big-endian, then a compile time error occurs.
1217 {
1218  return NativeByteOrder::ToEnum();
1219 }
1220 
1221 /// \brief Determines whether order follows native byte ordering
1222 /// \param order the ordering being tested against native byte ordering
1223 /// \returns true if order follows native byte ordering, false otherwise
1224 inline bool NativeByteOrderIs(ByteOrder order)
1225 {
1226  return order == GetNativeByteOrder();
1227 }
1228 
1229 /// \brief Returns the direction the cipher is being operated
1230 /// \tparam T class or type
1231 /// \param obj the cipher object being queried
1232 /// \returns ENCRYPTION if the cipher obj is being operated in its forward direction,
1233 /// DECRYPTION otherwise
1234 /// \details A cipher can be operated in a "forward" direction (encryption) or a "reverse"
1235 /// direction (decryption). The operations do not have to be symmetric, meaning a second
1236 /// application of the transformation does not necessariy return the original message.
1237 /// That is, <tt>E(D(m))</tt> may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not
1238 /// equal <tt>D(D(m))</tt>.
1239 template <class T>
1240 inline CipherDir GetCipherDir(const T &obj)
1241 {
1242  return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
1243 }
1244 
1245 /// \brief Attempts to reclaim unused memory
1246 /// \throws bad_alloc
1247 /// \details In the normal course of running a program, a request for memory normally succeeds. If a
1248 /// call to AlignedAllocate or UnalignedAllocate fails, then CallNewHandler is called in
1249 /// an effort to recover. Internally, CallNewHandler calls set_new_handler(NULLPTR) in an effort
1250 /// to free memory. There is no guarantee CallNewHandler will be able to procure more memory so
1251 /// an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler throws
1252 /// a bad_alloc exception.
1253 /// \sa AlignedAllocate, AlignedDeallocate, UnalignedAllocate, UnalignedDeallocate
1254 CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler();
1255 
1256 /// \brief Performs an addition with carry on a block of bytes
1257 /// \param inout the byte block
1258 /// \param size the size of the block, in bytes
1259 /// \details Performs an addition with carry by adding 1 on a block of bytes starting at the least
1260 /// significant byte. Once carry is 0, the function terminates and returns to the caller.
1261 /// \note The function is not constant time because it stops processing when the carry is 0.
1262 inline void IncrementCounterByOne(byte *inout, unsigned int size)
1263 {
1264  CRYPTOPP_ASSERT(inout != NULLPTR);
1265 
1266  unsigned int carry=1;
1267  while (carry && size != 0)
1268  {
1269  // On carry inout[n] equals 0
1270  carry = ! ++inout[size-1];
1271  size--;
1272  }
1273 }
1274 
1275 /// \brief Performs an addition with carry on a block of bytes
1276 /// \param output the destination block of bytes
1277 /// \param input the source block of bytes
1278 /// \param size the size of the block
1279 /// \details Performs an addition with carry on a block of bytes starting at the least significant
1280 /// byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.
1281 /// \details The function is close to near-constant time because it operates on all the bytes in the blocks.
1282 inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size)
1283 {
1284  CRYPTOPP_ASSERT(output != NULLPTR);
1285  CRYPTOPP_ASSERT(input != NULLPTR);
1286 
1287  unsigned int carry=1;
1288  while (carry && size != 0)
1289  {
1290  // On carry output[n] equals 0
1291  carry = ! (output[size-1] = input[size-1] + 1);
1292  size--;
1293  }
1294 
1295  while (size != 0)
1296  {
1297  output[size-1] = input[size-1];
1298  size--;
1299  }
1300 }
1301 
1302 /// \brief Performs a branchless swap of values a and b if condition c is true
1303 /// \tparam T class or type
1304 /// \param c the condition to perform the swap
1305 /// \param a the first value
1306 /// \param b the second value
1307 template <class T>
1308 inline void ConditionalSwap(bool c, T &a, T &b)
1309 {
1310  T t = c * (a ^ b);
1311  a ^= t;
1312  b ^= t;
1313 }
1314 
1315 /// \brief Performs a branchless swap of pointers a and b if condition c is true
1316 /// \tparam T class or type
1317 /// \param c the condition to perform the swap
1318 /// \param a the first pointer
1319 /// \param b the second pointer
1320 template <class T>
1321 inline void ConditionalSwapPointers(bool c, T &a, T &b)
1322 {
1323  ptrdiff_t t = size_t(c) * (a - b);
1324  a -= t;
1325  b += t;
1326 }
1327 
1328 // see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
1329 // and http://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data
1330 
1331 /// \brief Sets each element of an array to 0
1332 /// \tparam T class or type
1333 /// \param buf an array of elements
1334 /// \param n the number of elements in the array
1335 /// \details The operation performs a wipe or zeroization. The function
1336 /// attempts to survive optimizations and dead code removal.
1337 template <class T>
1338 void SecureWipeBuffer(T *buf, size_t n)
1339 {
1340  // GCC 4.3.2 on Cygwin optimizes away the first store if this
1341  // loop is done in the forward direction
1342  volatile T *p = buf+n;
1343  while (n--)
1344  *(--p) = 0;
1345 }
1346 
1347 #if !defined(CRYPTOPP_DISABLE_ASM) && \
1348  (_MSC_VER >= 1400 || defined(__GNUC__)) && \
1349  (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
1350 
1351 /// \brief Sets each byte of an array to 0
1352 /// \param buf an array of bytes
1353 /// \param n the number of elements in the array
1354 /// \details The operation performs a wipe or zeroization. The function
1355 /// attempts to survive optimizations and dead code removal.
1356 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1357 {
1358  volatile byte *p = buf;
1359 #ifdef __GNUC__
1360  asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1361 #else
1362  __stosb(reinterpret_cast<byte *>(reinterpret_cast<size_t>(p)), 0, n);
1363 #endif
1364 }
1365 
1366 /// \brief Sets each 16-bit element of an array to 0
1367 /// \param buf an array of 16-bit words
1368 /// \param n the number of elements in the array
1369 /// \details The operation performs a wipe or zeroization. The function
1370 /// attempts to survive optimizations and dead code removal.
1371 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1372 {
1373  volatile word16 *p = buf;
1374 #ifdef __GNUC__
1375  asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1376 #else
1377  __stosw(reinterpret_cast<word16 *>(reinterpret_cast<size_t>(p)), 0, n);
1378 #endif
1379 }
1380 
1381 /// \brief Sets each 32-bit element of an array to 0
1382 /// \param buf an array of 32-bit words
1383 /// \param n the number of elements in the array
1384 /// \details The operation performs a wipe or zeroization. The function
1385 /// attempts to survive optimizations and dead code removal.
1386 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1387 {
1388  volatile word32 *p = buf;
1389 #ifdef __GNUC__
1390  asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1391 #else
1392  __stosd(reinterpret_cast<unsigned long *>(reinterpret_cast<size_t>(p)), 0, n);
1393 #endif
1394 }
1395 
1396 /// \brief Sets each 64-bit element of an array to 0
1397 /// \param buf an array of 64-bit words
1398 /// \param n the number of elements in the array
1399 /// \details The operation performs a wipe or zeroization. The function
1400 /// attempts to survive optimizations and dead code removal.
1401 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1402 {
1403 #if CRYPTOPP_BOOL_X64
1404  volatile word64 *p = buf;
1405 # ifdef __GNUC__
1406  asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1407 # else
1408  __stosq(const_cast<word64 *>(p), 0, n);
1409 # endif
1410 #else
1411  SecureWipeBuffer(reinterpret_cast<word32 *>(buf), 2*n);
1412 #endif
1413 }
1414 
1415 #endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86
1416 
1417 #if !defined(CRYPTOPP_DISABLE_ASM) && (_MSC_VER >= 1700) && defined(_M_ARM)
1418 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1419 {
1420  char *p = reinterpret_cast<char*>(buf+n);
1421  while (n--)
1422  __iso_volatile_store8(--p, 0);
1423 }
1424 
1425 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1426 {
1427  short *p = reinterpret_cast<short*>(buf+n);
1428  while (n--)
1429  __iso_volatile_store16(--p, 0);
1430 }
1431 
1432 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1433 {
1434  int *p = reinterpret_cast<int*>(buf+n);
1435  while (n--)
1436  __iso_volatile_store32(--p, 0);
1437 }
1438 
1439 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1440 {
1441  __int64 *p = reinterpret_cast<__int64*>(buf+n);
1442  while (n--)
1443  __iso_volatile_store64(--p, 0);
1444 }
1445 #endif
1446 
1447 /// \brief Sets each element of an array to 0
1448 /// \tparam T class or type
1449 /// \param buf an array of elements
1450 /// \param n the number of elements in the array
1451 /// \details The operation performs a wipe or zeroization. The function
1452 /// attempts to survive optimizations and dead code removal.
1453 template <class T>
1454 inline void SecureWipeArray(T *buf, size_t n)
1455 {
1456  if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
1457  SecureWipeBuffer(reinterpret_cast<word64 *>(static_cast<void *>(buf)), n * (sizeof(T)/8));
1458  else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
1459  SecureWipeBuffer(reinterpret_cast<word32 *>(static_cast<void *>(buf)), n * (sizeof(T)/4));
1460  else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
1461  SecureWipeBuffer(reinterpret_cast<word16 *>(static_cast<void *>(buf)), n * (sizeof(T)/2));
1462  else
1463  SecureWipeBuffer(reinterpret_cast<byte *>(static_cast<void *>(buf)), n * sizeof(T));
1464 }
1465 
1466 /// \brief Converts a wide character C-string to a multibyte string
1467 /// \param str C-string consisting of wide characters
1468 /// \param throwOnError flag indicating the function should throw on error
1469 /// \returns str converted to a multibyte string or an empty string.
1470 /// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under
1471 /// the executing thread's locale. A locale must be set before using this function, and it can be
1472 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1473 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1474 /// throwOnError as true, the function throws an InvalidArgument() exception.
1475 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
1476 /// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available,
1477 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1478 std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
1479 
1480 /// \brief Converts a multibyte C-string to a wide character string
1481 /// \param str C-string consisting of wide characters
1482 /// \param throwOnError flag indicating the function should throw on error
1483 /// \returns str converted to a multibyte string or an empty string.
1484 /// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under
1485 /// the executing thread's locale. A locale must be set before using this function, and it can be
1486 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1487 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1488 /// throwOnError as true, the function throws an InvalidArgument() exception.
1489 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8)
1490 /// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available,
1491 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1492 std::wstring StringWiden(const char *str, bool throwOnError = true);
1493 
1494 /// \brief Allocates a buffer on 16-byte boundary
1495 /// \param size the size of the buffer
1496 /// \details AlignedAllocate is primarily used when the data will be
1497 /// proccessed by SSE, NEON, ARMv8 or PowerPC instructions. The assembly
1498 /// language routines rely on the alignment. If the alignment is not
1499 /// respected, then a SIGBUS could be generated on Unix and Linux, and an
1500 /// EXCEPTION_DATATYPE_MISALIGNMENT could be generated on Windows.
1501 /// \details Formerly, AlignedAllocate and AlignedDeallocate were only
1502 /// available on certain platforms when CRYTPOPP_DISABLE_ASM was not in
1503 /// effect. However, Android and iOS debug simulator builds got into a
1504 /// state where the aligned allocator was not available and caused link
1505 /// failures.
1506 /// \since AlignedAllocate for SIMD since Crypto++ 1.0, AlignedAllocate
1507 /// for all builds since Crypto++ 8.1
1508 /// \sa AlignedDeallocate, UnalignedAllocate, UnalignedDeallocate, CallNewHandler,
1509 /// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
1510 CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
1511 
1512 /// \brief Frees a buffer allocated with AlignedAllocate
1513 /// \param ptr the buffer to free
1514 /// \since AlignedDeallocate for SIMD since Crypto++ 1.0, AlignedAllocate
1515 /// for all builds since Crypto++ 8.1
1516 /// \sa AlignedAllocate, UnalignedAllocate, UnalignedDeallocate, CallNewHandler,
1517 /// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
1518 CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
1519 
1520 /// \brief Allocates a buffer
1521 /// \param size the size of the buffer
1522 /// \since Crypto++ 1.0
1523 /// \sa AlignedAllocate, AlignedDeallocate, UnalignedDeallocate, CallNewHandler,
1524 /// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
1525 CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
1526 
1527 /// \brief Frees a buffer allocated with UnalignedAllocate
1528 /// \param ptr the buffer to free
1529 /// \since Crypto++ 1.0
1530 /// \sa AlignedAllocate, AlignedDeallocate, UnalignedAllocate, CallNewHandler,
1531 /// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
1532 CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
1533 
1534 // ************** rotate functions ***************
1535 
1536 /// \brief Performs a left rotate
1537 /// \tparam R the number of bit positions to rotate the value
1538 /// \tparam T the word type
1539 /// \param x the value to rotate
1540 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1541 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1542 /// Use rotlMod if the rotate amount R is outside the range.
1543 /// \details Use rotlConstant when the rotate amount is constant. The template function was added
1544 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1545 /// need for a constexpr meant rotlFixed failed to compile on occassion.
1546 /// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1547 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1548 /// counterparts.
1549 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1550 /// \since Crypto++ 6.0
1551 template <unsigned int R, class T> inline T rotlConstant(T x)
1552 {
1553  // Portable rotate that reduces to single instruction...
1554  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1555  // http://software.intel.com/en-us/forums/topic/580884
1556  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1557  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1558  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1559  CRYPTOPP_ASSERT(R < THIS_SIZE);
1560  return T((x<<R)|(x>>(-R&MASK)));
1561 }
1562 
1563 /// \brief Performs a right rotate
1564 /// \tparam R the number of bit positions to rotate the value
1565 /// \tparam T the word type
1566 /// \param x the value to rotate
1567 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1568 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1569 /// Use rotrMod if the rotate amount R is outside the range.
1570 /// \details Use rotrConstant when the rotate amount is constant. The template function was added
1571 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1572 /// need for a constexpr meant rotrFixed failed to compile on occassion.
1573 /// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1574 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1575 /// counterparts.
1576 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1577 template <unsigned int R, class T> inline T rotrConstant(T x)
1578 {
1579  // Portable rotate that reduces to single instruction...
1580  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1581  // http://software.intel.com/en-us/forums/topic/580884
1582  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1583  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1584  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1585  CRYPTOPP_ASSERT(R < THIS_SIZE);
1586  return T((x >> R)|(x<<(-R&MASK)));
1587 }
1588 
1589 /// \brief Performs a left rotate
1590 /// \tparam T the word type
1591 /// \param x the value to rotate
1592 /// \param y the number of bit positions to rotate the value
1593 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1594 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1595 /// Use rotlMod if the rotate amount y is outside the range.
1596 /// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1597 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1598 /// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a
1599 /// template parameter.
1600 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1601 /// \since Crypto++ 6.0
1602 template <class T> inline T rotlFixed(T x, unsigned int y)
1603 {
1604  // Portable rotate that reduces to single instruction...
1605  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1606  // http://software.intel.com/en-us/forums/topic/580884
1607  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1608  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1609  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1610  CRYPTOPP_ASSERT(y < THIS_SIZE);
1611  return T((x<<y)|(x>>(-y&MASK)));
1612 }
1613 
1614 /// \brief Performs a right rotate
1615 /// \tparam T the word type
1616 /// \param x the value to rotate
1617 /// \param y the number of bit positions to rotate the value
1618 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1619 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1620 /// Use rotrMod if the rotate amount y is outside the range.
1621 /// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1622 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1623 /// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a
1624 /// template parameter.
1625 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1626 /// \since Crypto++ 3.0
1627 template <class T> inline T rotrFixed(T x, unsigned int y)
1628 {
1629  // Portable rotate that reduces to single instruction...
1630  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1631  // http://software.intel.com/en-us/forums/topic/580884
1632  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1633  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1634  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1635  CRYPTOPP_ASSERT(y < THIS_SIZE);
1636  return T((x >> y)|(x<<(-y&MASK)));
1637 }
1638 
1639 /// \brief Performs a left rotate
1640 /// \tparam T the word type
1641 /// \param x the value to rotate
1642 /// \param y the number of bit positions to rotate the value
1643 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1644 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1645 /// Use rotlMod if the rotate amount y is outside the range.
1646 /// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1647 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1648 /// counterparts.
1649 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1650 /// \since Crypto++ 3.0
1651 template <class T> inline T rotlVariable(T x, unsigned int y)
1652 {
1653  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1654  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1655  CRYPTOPP_ASSERT(y < THIS_SIZE);
1656  return T((x<<y)|(x>>(-y&MASK)));
1657 }
1658 
1659 /// \brief Performs a right rotate
1660 /// \tparam T the word type
1661 /// \param x the value to rotate
1662 /// \param y the number of bit positions to rotate the value
1663 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1664 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1665 /// Use rotrMod if the rotate amount y is outside the range.
1666 /// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1667 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1668 /// counterparts.
1669 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1670 /// \since Crypto++ 3.0
1671 template <class T> inline T rotrVariable(T x, unsigned int y)
1672 {
1673  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1674  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1675  CRYPTOPP_ASSERT(y < THIS_SIZE);
1676  return T((x>>y)|(x<<(-y&MASK)));
1677 }
1678 
1679 /// \brief Performs a left rotate
1680 /// \tparam T the word type
1681 /// \param x the value to rotate
1682 /// \param y the number of bit positions to rotate the value
1683 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1684 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1685 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1686 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1687 /// \since Crypto++ 3.0
1688 template <class T> inline T rotlMod(T x, unsigned int y)
1689 {
1690  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1691  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1692  return T((x<<(y&MASK))|(x>>(-y&MASK)));
1693 }
1694 
1695 /// \brief Performs a right rotate
1696 /// \tparam T the word type
1697 /// \param x the value to rotate
1698 /// \param y the number of bit positions to rotate the value
1699 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1700 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1701 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1702 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1703 /// \since Crypto++ 3.0
1704 template <class T> inline T rotrMod(T x, unsigned int y)
1705 {
1706  CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8)
1707  CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1)
1708  return T((x>>(y&MASK))|(x<<(-y&MASK)));
1709 }
1710 
1711 #ifdef _MSC_VER
1712 
1713 /// \brief Performs a left rotate
1714 /// \tparam T the word type
1715 /// \param x the 32-bit value to rotate
1716 /// \param y the number of bit positions to rotate the value
1717 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1718 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1719 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1720 /// \note rotlFixed will assert in Debug builds if is outside the allowed range.
1721 /// \since Crypto++ 3.0
1722 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1723 {
1724  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1725  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1726  return y ? _lrotl(x, static_cast<byte>(y)) : x;
1727 }
1728 
1729 /// \brief Performs a right rotate
1730 /// \tparam T the word type
1731 /// \param x the 32-bit value to rotate
1732 /// \param y the number of bit positions to rotate the value
1733 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1734 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1735 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1736 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1737 /// \since Crypto++ 3.0
1738 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1739 {
1740  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1741  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1742  return y ? _lrotr(x, static_cast<byte>(y)) : x;
1743 }
1744 
1745 /// \brief Performs a left rotate
1746 /// \tparam T the word type
1747 /// \param x the 32-bit value to rotate
1748 /// \param y the number of bit positions to rotate the value
1749 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1750 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1751 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1752 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1753 /// \since Crypto++ 3.0
1754 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1755 {
1756  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1757  return _lrotl(x, static_cast<byte>(y));
1758 }
1759 
1760 /// \brief Performs a right rotate
1761 /// \tparam T the word type
1762 /// \param x the 32-bit value to rotate
1763 /// \param y the number of bit positions to rotate the value
1764 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1765 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1766 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1767 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1768 /// \since Crypto++ 3.0
1769 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1770 {
1771  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1772  return _lrotr(x, static_cast<byte>(y));
1773 }
1774 
1775 /// \brief Performs a left rotate
1776 /// \tparam T the word type
1777 /// \param x the 32-bit value to rotate
1778 /// \param y the number of bit positions to rotate the value
1779 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1780 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1781 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1782 /// \since Crypto++ 3.0
1783 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1784 {
1785  y %= 8*sizeof(x);
1786  return _lrotl(x, static_cast<byte>(y));
1787 }
1788 
1789 /// \brief Performs a right rotate
1790 /// \tparam T the word type
1791 /// \param x the 32-bit value to rotate
1792 /// \param y the number of bit positions to rotate the value
1793 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1794 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1795 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1796 /// \since Crypto++ 3.0
1797 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
1798 {
1799  y %= 8*sizeof(x);
1800  return _lrotr(x, static_cast<byte>(y));
1801 }
1802 
1803 #endif // #ifdef _MSC_VER
1804 
1805 #if (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1806 // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
1807 
1808 /// \brief Performs a left rotate
1809 /// \tparam T the word type
1810 /// \param x the 64-bit value to rotate
1811 /// \param y the number of bit positions to rotate the value
1812 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1813 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1814 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1815 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1816 /// \since Crypto++ 3.0
1817 template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
1818 {
1819  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1820  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1821  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1822 }
1823 
1824 /// \brief Performs a right rotate
1825 /// \tparam T the word type
1826 /// \param x the 64-bit value to rotate
1827 /// \param y the number of bit positions to rotate the value
1828 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1829 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1830 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1831 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1832 /// \since Crypto++ 3.0
1833 template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
1834 {
1835  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1836  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1837  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1838 }
1839 
1840 /// \brief Performs a left rotate
1841 /// \tparam T the word type
1842 /// \param x the 64-bit value to rotate
1843 /// \param y the number of bit positions to rotate the value
1844 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1845 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1846 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1847 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1848 /// \since Crypto++ 3.0
1849 template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
1850 {
1851  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1852  return _rotl64(x, static_cast<byte>(y));
1853 }
1854 
1855 /// \brief Performs a right rotate
1856 /// \tparam T the word type
1857 /// \param x the 64-bit value to rotate
1858 /// \param y the number of bit positions to rotate the value
1859 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1860 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1861 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1862 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1863 /// \since Crypto++ 3.0
1864 template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
1865 {
1866  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1867  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1868 }
1869 
1870 /// \brief Performs a left rotate
1871 /// \tparam T the word type
1872 /// \param x the 64-bit value to rotate
1873 /// \param y the number of bit positions to rotate the value
1874 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1875 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1876 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1877 /// \since Crypto++ 3.0
1878 template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
1879 {
1880  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1881  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1882 }
1883 
1884 /// \brief Performs a right rotate
1885 /// \tparam T the word type
1886 /// \param x the 64-bit value to rotate
1887 /// \param y the number of bit positions to rotate the value
1888 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1889 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1890 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1891 /// \since Crypto++ 3.0
1892 template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
1893 {
1894  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1895  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1896 }
1897 
1898 #endif // #if _MSC_VER >= 1310
1899 
1900 #if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
1901 // Intel C++ Compiler 10.0 gives undefined externals with these
1902 template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
1903 {
1904  // Intrinsic, not bound to C/C++ language rules.
1905  return _rotl16(x, static_cast<byte>(y));
1906 }
1907 
1908 template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
1909 {
1910  // Intrinsic, not bound to C/C++ language rules.
1911  return _rotr16(x, static_cast<byte>(y));
1912 }
1913 
1914 template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
1915 {
1916  return _rotl16(x, static_cast<byte>(y));
1917 }
1918 
1919 template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
1920 {
1921  return _rotr16(x, static_cast<byte>(y));
1922 }
1923 
1924 template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
1925 {
1926  return _rotl16(x, static_cast<byte>(y));
1927 }
1928 
1929 template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
1930 {
1931  return _rotr16(x, static_cast<byte>(y));
1932 }
1933 
1934 template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
1935 {
1936  // Intrinsic, not bound to C/C++ language rules.
1937  return _rotl8(x, static_cast<byte>(y));
1938 }
1939 
1940 template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
1941 {
1942  // Intrinsic, not bound to C/C++ language rules.
1943  return _rotr8(x, static_cast<byte>(y));
1944 }
1945 
1946 template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
1947 {
1948  return _rotl8(x, static_cast<byte>(y));
1949 }
1950 
1951 template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
1952 {
1953  return _rotr8(x, static_cast<byte>(y));
1954 }
1955 
1956 template<> inline byte rotlMod<byte>(byte x, unsigned int y)
1957 {
1958  return _rotl8(x, static_cast<byte>(y));
1959 }
1960 
1961 template<> inline byte rotrMod<byte>(byte x, unsigned int y)
1962 {
1963  return _rotr8(x, static_cast<byte>(y));
1964 }
1965 
1966 #endif // #if _MSC_VER >= 1400
1967 
1968 #if (defined(__MWERKS__) && TARGET_CPU_PPC)
1969 
1970 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1971 {
1972  CRYPTOPP_ASSERT(y < 32);
1973  return y ? __rlwinm(x,y,0,31) : x;
1974 }
1975 
1976 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1977 {
1978  CRYPTOPP_ASSERT(y < 32);
1979  return y ? __rlwinm(x,32-y,0,31) : x;
1980 }
1981 
1982 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1983 {
1984  CRYPTOPP_ASSERT(y < 32);
1985  return (__rlwnm(x,y,0,31));
1986 }
1987 
1988 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1989 {
1990  CRYPTOPP_ASSERT(y < 32);
1991  return (__rlwnm(x,32-y,0,31));
1992 }
1993 
1994 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1995 {
1996  return (__rlwnm(x,y,0,31));
1997 }
1998 
1999 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
2000 {
2001  return (__rlwnm(x,32-y,0,31));
2002 }
2003 
2004 #endif // __MWERKS__ && TARGET_CPU_PPC
2005 
2006 // ************** endian reversal ***************
2007 
2008 /// \brief Gets a byte from a value
2009 /// \param order the ByteOrder of the value
2010 /// \param value the value to retrieve the byte
2011 /// \param index the location of the byte to retrieve
2012 template <class T>
2013 inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
2014 {
2015  if (order == LITTLE_ENDIAN_ORDER)
2016  return GETBYTE(value, index);
2017  else
2018  return GETBYTE(value, sizeof(T)-index-1);
2019 }
2020 
2021 /// \brief Reverses bytes in a 8-bit value
2022 /// \param value the 8-bit value to reverse
2023 /// \note ByteReverse returns the value passed to it since there is nothing to
2024 /// reverse.
2025 inline byte ByteReverse(byte value)
2026 {
2027  return value;
2028 }
2029 
2030 /// \brief Reverses bytes in a 16-bit value
2031 /// \param value the 16-bit value to reverse
2032 /// \details ByteReverse calls bswap if available. Otherwise the function
2033 /// performs a 8-bit rotate on the word16.
2034 inline word16 ByteReverse(word16 value)
2035 {
2036 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
2037  return bswap_16(value);
2038 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
2039  return _byteswap_ushort(value);
2040 #else
2041  return rotlFixed(value, 8U);
2042 #endif
2043 }
2044 
2045 /// \brief Reverses bytes in a 32-bit value
2046 /// \param value the 32-bit value to reverse
2047 /// \details ByteReverse calls bswap if available. Otherwise the function uses
2048 /// a combination of rotates on the word32.
2049 inline word32 ByteReverse(word32 value)
2050 {
2051 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
2052  return bswap_32(value);
2053 #elif defined(CRYPTOPP_ARM_BYTEREV_AVAILABLE)
2054  word32 rvalue;
2055  __asm__ ("rev %0, %1" : "=r" (rvalue) : "r" (value));
2056  return rvalue;
2057 #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2058  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
2059  return value;
2060 #elif defined(__MWERKS__) && TARGET_CPU_PPC
2061  return (word32)__lwbrx(&value,0);
2062 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
2063  return _byteswap_ulong(value);
2064 #elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__)
2065  // 5 instructions with rotate instruction, 9 without
2066  return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
2067 #else
2068  // 6 instructions with rotate instruction, 8 without
2069  value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
2070  return rotlFixed(value, 16U);
2071 #endif
2072 }
2073 
2074 /// \brief Reverses bytes in a 64-bit value
2075 /// \param value the 64-bit value to reverse
2076 /// \details ByteReverse calls bswap if available. Otherwise the function uses
2077 /// a combination of rotates on the word64.
2078 inline word64 ByteReverse(word64 value)
2079 {
2080 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
2081  return bswap_64(value);
2082 #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
2083  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
2084  return value;
2085 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
2086  return _byteswap_uint64(value);
2087 #elif CRYPTOPP_BOOL_SLOW_WORD64
2088  return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
2089 #else
2090  value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
2091  value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
2092  return rotlFixed(value, 32U);
2093 #endif
2094 }
2095 
2096 /// \brief Reverses bits in a 8-bit value
2097 /// \param value the 8-bit value to reverse
2098 /// \details BitReverse performs a combination of shifts on the byte.
2099 inline byte BitReverse(byte value)
2100 {
2101  value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1);
2102  value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2);
2103  return rotlFixed(value, 4U);
2104 }
2105 
2106 /// \brief Reverses bits in a 16-bit value
2107 /// \param value the 16-bit value to reverse
2108 /// \details BitReverse performs a combination of shifts on the word16.
2109 inline word16 BitReverse(word16 value)
2110 {
2111 #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE)
2112  // 4 instructions on ARM.
2113  word32 rvalue;
2114  __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value));
2115  return word16(rvalue >> 16);
2116 #else
2117  // 15 instructions on ARM.
2118  value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1);
2119  value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2);
2120  value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4);
2121  return ByteReverse(value);
2122 #endif
2123 }
2124 
2125 /// \brief Reverses bits in a 32-bit value
2126 /// \param value the 32-bit value to reverse
2127 /// \details BitReverse performs a combination of shifts on the word32.
2128 inline word32 BitReverse(word32 value)
2129 {
2130 #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE)
2131  // 2 instructions on ARM.
2132  word32 rvalue;
2133  __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value));
2134  return rvalue;
2135 #else
2136  // 19 instructions on ARM.
2137  value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1);
2138  value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2);
2139  value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4);
2140  return ByteReverse(value);
2141 #endif
2142 }
2143 
2144 /// \brief Reverses bits in a 64-bit value
2145 /// \param value the 64-bit value to reverse
2146 /// \details BitReverse performs a combination of shifts on the word64.
2147 inline word64 BitReverse(word64 value)
2148 {
2149 #if CRYPTOPP_BOOL_SLOW_WORD64
2150  return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
2151 #else
2152  value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1);
2153  value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2);
2154  value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
2155  return ByteReverse(value);
2156 #endif
2157 }
2158 
2159 /// \brief Reverses bits in a value
2160 /// \param value the value to reverse
2161 /// \details The template overload of BitReverse operates on signed and unsigned values.
2162 /// Internally the size of T is checked, and then value is cast to a byte,
2163 /// word16, word32 or word64. After the cast, the appropriate BitReverse
2164 /// overload is called.
2165 template <class T>
2166 inline T BitReverse(T value)
2167 {
2168  if (sizeof(T) == 1)
2169  return (T)BitReverse((byte)value);
2170  else if (sizeof(T) == 2)
2171  return (T)BitReverse((word16)value);
2172  else if (sizeof(T) == 4)
2173  return (T)BitReverse((word32)value);
2174  else if (sizeof(T) == 8)
2175  return (T)BitReverse((word64)value);
2176  else
2177  {
2178  CRYPTOPP_ASSERT(0);
2179  return (T)BitReverse((word64)value);
2180  }
2181 }
2182 
2183 /// \brief Reverses bytes in a value depending upon endianness
2184 /// \tparam T the class or type
2185 /// \param order the ByteOrder of the data
2186 /// \param value the value to conditionally reverse
2187 /// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
2188 /// If order matches native byte order, then the original value is returned.
2189 /// If not, then ByteReverse is called on the value before returning to the caller.
2190 template <class T>
2191 inline T ConditionalByteReverse(ByteOrder order, T value)
2192 {
2193  return NativeByteOrderIs(order) ? value : ByteReverse(value);
2194 }
2195 
2196 /// \brief Reverses bytes in an element from an array of elements
2197 /// \tparam T the class or type
2198 /// \param out the output array of elements
2199 /// \param in the input array of elements
2200 /// \param byteCount the total number of bytes in the array
2201 /// \details Internally, ByteReverse visits each element in the in array
2202 /// calls ByteReverse on it, and writes the result to out.
2203 /// \details ByteReverse does not process tail byes, or bytes that are
2204 /// not part of a full element. If T is int (and int is 4 bytes), then
2205 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
2206 /// reversed.
2207 /// \details The following program should help illustrate the behavior.
2208 /// <pre>vector<word32> v1, v2;
2209 ///
2210 /// v1.push_back(1);
2211 /// v1.push_back(2);
2212 /// v1.push_back(3);
2213 /// v1.push_back(4);
2214 ///
2215 /// v2.resize(v1.size());
2216 /// ByteReverse<word32>(&v2[0], &v1[0], 16);
2217 ///
2218 /// cout << "V1: ";
2219 /// for(unsigned int i = 0; i < v1.size(); i++)
2220 /// cout << std::hex << v1[i] << " ";
2221 /// cout << endl;
2222 ///
2223 /// cout << "V2: ";
2224 /// for(unsigned int i = 0; i < v2.size(); i++)
2225 /// cout << std::hex << v2[i] << " ";
2226 /// cout << endl;</pre>
2227 /// The program above results in the following output.
2228 /// <pre>V1: 00000001 00000002 00000003 00000004
2229 /// V2: 01000000 02000000 03000000 04000000</pre>
2230 /// \sa ConditionalByteReverse
2231 template <class T>
2232 void ByteReverse(T *out, const T *in, size_t byteCount)
2233 {
2234  // Alignment check due to Issues 690
2235  CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0);
2236  CRYPTOPP_ASSERT(IsAligned<T>(in));
2237  CRYPTOPP_ASSERT(IsAligned<T>(out));
2238 
2239  size_t count = byteCount/sizeof(T);
2240  for (size_t i=0; i<count; i++)
2241  out[i] = ByteReverse(in[i]);
2242 }
2243 
2244 /// \brief Conditionally reverses bytes in an element from an array of elements
2245 /// \tparam T the class or type
2246 /// \param order the ByteOrder of the data
2247 /// \param out the output array of elements
2248 /// \param in the input array of elements
2249 /// \param byteCount the byte count of the arrays
2250 /// \details Internally, ByteReverse visits each element in the in array
2251 /// calls ByteReverse on it depending on the desired endianness, and writes the result to out.
2252 /// \details ByteReverse does not process tail byes, or bytes that are
2253 /// not part of a full element. If T is int (and int is 4 bytes), then
2254 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
2255 /// reversed.
2256 /// \sa ByteReverse
2257 template <class T>
2258 inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
2259 {
2260  if (!NativeByteOrderIs(order))
2261  ByteReverse(out, in, byteCount);
2262  else if (in != out)
2263  memcpy_s(out, byteCount, in, byteCount);
2264 }
2265 
2266 template <class T>
2267 inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
2268 {
2269  const size_t U = sizeof(T);
2270  CRYPTOPP_ASSERT(inlen <= outlen*U);
2271  memcpy_s(out, outlen*U, in, inlen);
2272  memset_z((byte *)out+inlen, 0, outlen*U-inlen);
2273  ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
2274 }
2275 
2276 inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *)
2277 {
2278  CRYPTOPP_UNUSED(order);
2279  return block[0];
2280 }
2281 
2282 inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *)
2283 {
2284  return (order == BIG_ENDIAN_ORDER)
2285  ? block[1] | (block[0] << 8)
2286  : block[0] | (block[1] << 8);
2287 }
2288 
2289 inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *)
2290 {
2291  return (order == BIG_ENDIAN_ORDER)
2292  ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
2293  : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
2294 }
2295 
2296 inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *)
2297 {
2298  return (order == BIG_ENDIAN_ORDER)
2299  ?
2300  (word64(block[7]) |
2301  (word64(block[6]) << 8) |
2302  (word64(block[5]) << 16) |
2303  (word64(block[4]) << 24) |
2304  (word64(block[3]) << 32) |
2305  (word64(block[2]) << 40) |
2306  (word64(block[1]) << 48) |
2307  (word64(block[0]) << 56))
2308  :
2309  (word64(block[0]) |
2310  (word64(block[1]) << 8) |
2311  (word64(block[2]) << 16) |
2312  (word64(block[3]) << 24) |
2313  (word64(block[4]) << 32) |
2314  (word64(block[5]) << 40) |
2315  (word64(block[6]) << 48) |
2316  (word64(block[7]) << 56));
2317 }
2318 
2319 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
2320 {
2321  CRYPTOPP_UNUSED(order);
2322  block[0] = static_cast<byte>(xorBlock ? (value ^ xorBlock[0]) : value);
2323 }
2324 
2325 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
2326 {
2327  if (order == BIG_ENDIAN_ORDER)
2328  {
2329  if (xorBlock)
2330  {
2331  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2332  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2333  }
2334  else
2335  {
2336  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2337  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2338  }
2339  }
2340  else
2341  {
2342  if (xorBlock)
2343  {
2344  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2345  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2346  }
2347  else
2348  {
2349  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2350  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2351  }
2352  }
2353 }
2354 
2355 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
2356 {
2357  if (order == BIG_ENDIAN_ORDER)
2358  {
2359  if (xorBlock)
2360  {
2361  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2362  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2363  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2364  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2365  }
2366  else
2367  {
2368  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2369  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2370  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2371  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2372  }
2373  }
2374  else
2375  {
2376  if (xorBlock)
2377  {
2378  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2379  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2380  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2381  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2382  }
2383  else
2384  {
2385  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2386  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2387  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2388  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2389  }
2390  }
2391 }
2392 
2393 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
2394 {
2395  if (order == BIG_ENDIAN_ORDER)
2396  {
2397  if (xorBlock)
2398  {
2399  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2400  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2401  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2402  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2403  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2404  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2405  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2406  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2407  }
2408  else
2409  {
2410  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2411  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2412  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2413  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2414  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2415  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2416  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2417  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2418  }
2419  }
2420  else
2421  {
2422  if (xorBlock)
2423  {
2424  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2425  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2426  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2427  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2428  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2429  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2430  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2431  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2432  }
2433  else
2434  {
2435  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2436  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2437  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2438  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2439  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2440  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2441  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2442  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2443  }
2444  }
2445 }
2446 
2447 /// \brief Access a block of memory
2448 /// \tparam T class or type
2449 /// \param assumeAligned flag indicating alignment
2450 /// \param order the ByteOrder of the data
2451 /// \param block the byte buffer to be processed
2452 /// \returns the word in the specified byte order
2453 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2454 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2455 /// LITTLE_ENDIAN_ORDER.
2456 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2457 /// will be <tt>0x03020100</tt>.
2458 /// <pre>
2459 /// word32 w;
2460 /// byte buffer[4] = {0,1,2,3};
2461 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2462 /// </pre>
2463 template <class T>
2464 inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
2465 {
2466  CRYPTOPP_UNUSED(assumeAligned);
2467 
2468  T temp;
2469  memcpy(&temp, block, sizeof(T));
2470  return ConditionalByteReverse(order, temp);
2471 }
2472 
2473 /// \brief Access a block of memory
2474 /// \tparam T class or type
2475 /// \param assumeAligned flag indicating alignment
2476 /// \param order the ByteOrder of the data
2477 /// \param result the word in the specified byte order
2478 /// \param block the byte buffer to be processed
2479 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2480 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2481 /// LITTLE_ENDIAN_ORDER.
2482 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2483 /// will be <tt>0x03020100</tt>.
2484 /// <pre>
2485 /// word32 w;
2486 /// byte buffer[4] = {0,1,2,3};
2487 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2488 /// </pre>
2489 template <class T>
2490 inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
2491 {
2492  result = GetWord<T>(assumeAligned, order, block);
2493 }
2494 
2495 /// \brief Access a block of memory
2496 /// \tparam T class or type
2497 /// \param assumeAligned flag indicating alignment
2498 /// \param order the ByteOrder of the data
2499 /// \param block the destination byte buffer
2500 /// \param value the word in the specified byte order
2501 /// \param xorBlock an optional byte buffer to xor
2502 /// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates
2503 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2504 /// LITTLE_ENDIAN_ORDER.
2505 template <class T>
2506 inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR)
2507 {
2508  CRYPTOPP_UNUSED(assumeAligned);
2509 
2510  T t1, t2;
2511  t1 = ConditionalByteReverse(order, value);
2512  if (xorBlock) {memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;}
2513  memcpy(block, &t1, sizeof(T));
2514 }
2515 
2516 /// \brief Access a block of memory
2517 /// \tparam T class or type
2518 /// \tparam B enumeration indicating endianness
2519 /// \tparam A flag indicating alignment
2520 /// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is
2521 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2522 /// Repeatedly applying operator() results in advancing in the block of memory.
2523 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt>
2524 /// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>.
2525 /// <pre>
2526 /// word32 w1, w2;
2527 /// byte buffer[8] = {0,1,2,3,4,5,6,7};
2528 /// GetBlock<word32, LittleEndian> block(buffer);
2529 /// block(w1)(w2);
2530 /// </pre>
2531 template <class T, class B, bool A=false>
2533 {
2534 public:
2535  /// \brief Construct a GetBlock
2536  /// \param block the memory block
2537  GetBlock(const void *block)
2538  : m_block((const byte *)block) {}
2539 
2540  /// \brief Access a block of memory
2541  /// \tparam U class or type
2542  /// \param x the value to read
2543  /// \returns pointer to the remainder of the block after reading x
2544  template <class U>
2546  {
2547  CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
2548  x = GetWord<T>(A, B::ToEnum(), m_block);
2549  m_block += sizeof(T);
2550  return *this;
2551  }
2552 
2553 private:
2554  const byte *m_block;
2555 };
2556 
2557 /// \brief Access a block of memory
2558 /// \tparam T class or type
2559 /// \tparam B enumeration indicating endianness
2560 /// \tparam A flag indicating alignment
2561 /// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is
2562 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2563 /// Repeatedly applying operator() results in advancing in the block of memory.
2564 /// \details An example of writing two word32 values from a block of memory is shown below. After the code
2565 /// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>.
2566 /// <pre>
2567 /// word32 w1=0x03020100, w2=0x07060504;
2568 /// byte buffer[8];
2569 /// PutBlock<word32, LittleEndian> block(NULLPTR, buffer);
2570 /// block(w1)(w2);
2571 /// </pre>
2572 template <class T, class B, bool A=false>
2574 {
2575 public:
2576  /// \brief Construct a PutBlock
2577  /// \param block the memory block
2578  /// \param xorBlock optional mask
2579  PutBlock(const void *xorBlock, void *block)
2580  : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
2581 
2582  /// \brief Access a block of memory
2583  /// \tparam U class or type
2584  /// \param x the value to write
2585  /// \returns pointer to the remainder of the block after writing x
2586  template <class U>
2588  {
2589  PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
2590  m_block += sizeof(T);
2591  if (m_xorBlock)
2592  m_xorBlock += sizeof(T);
2593  return *this;
2594  }
2595 
2596 private:
2597  const byte *m_xorBlock;
2598  byte *m_block;
2599 };
2600 
2601 /// \brief Access a block of memory
2602 /// \tparam T class or type
2603 /// \tparam B enumeration indicating endianness
2604 /// \tparam GA flag indicating alignment for the Get operation
2605 /// \tparam PA flag indicating alignment for the Put operation
2606 /// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is
2607 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2608 /// \sa GetBlock() and PutBlock().
2609 template <class T, class B, bool GA=false, bool PA=false>
2611 {
2612  // function needed because of C++ grammatical ambiguity between expression-statements and declarations
2613  static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
2614  typedef PutBlock<T, B, PA> Put;
2615 };
2616 
2617 /// \brief Convert a word to a string
2618 /// \tparam T class or type
2619 /// \param value the word to convert
2620 /// \param order byte order
2621 /// \returns a string representing the value of the word
2622 template <class T>
2623 std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
2624 {
2625  if (!NativeByteOrderIs(order))
2626  value = ByteReverse(value);
2627 
2628  return std::string((char *)&value, sizeof(value));
2629 }
2630 
2631 /// \brief Convert a string to a word
2632 /// \tparam T class or type
2633 /// \param str the string to convert
2634 /// \param order byte order
2635 /// \returns a word representing the value of the string
2636 template <class T>
2637 T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
2638 {
2639  T value = 0;
2640  memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
2641  return NativeByteOrderIs(order) ? value : ByteReverse(value);
2642 }
2643 
2644 // ************** help remove warning on g++ ***************
2645 
2646 /// \brief Safely shift values when undefined behavior could occur
2647 /// \tparam overflow boolean flag indicating if overflow is present
2648 /// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules.
2649 /// The class behaves much like a saturating arithmetic class, clamping values rather than allowing
2650 /// the compiler to remove undefined behavior.
2651 /// \sa SafeShifter<true>, SafeShifter<false>
2652 template <bool overflow> struct SafeShifter;
2653 
2654 /// \brief Shifts a value in the presence of overflow
2655 /// \details the true template parameter indicates overflow would occur.
2656 /// In this case, SafeShifter clamps the value and returns 0.
2657 template<> struct SafeShifter<true>
2658 {
2659  /// \brief Right shifts a value that overflows
2660  /// \tparam T class or type
2661  /// \return 0
2662  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2663  /// \sa SafeLeftShift
2664  template <class T>
2665  static inline T RightShift(T value, unsigned int bits)
2666  {
2667  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2668  return 0;
2669  }
2670 
2671  /// \brief Left shifts a value that overflows
2672  /// \tparam T class or type
2673  /// \return 0
2674  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2675  /// \sa SafeRightShift
2676  template <class T>
2677  static inline T LeftShift(T value, unsigned int bits)
2678  {
2679  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2680  return 0;
2681  }
2682 };
2683 
2684 /// \brief Shifts a value in the absence of overflow
2685 /// \details the false template parameter indicates overflow would not occur.
2686 /// In this case, SafeShifter returns the shfted value.
2687 template<> struct SafeShifter<false>
2688 {
2689  /// \brief Right shifts a value that does not overflow
2690  /// \tparam T class or type
2691  /// \return the shifted value
2692  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2693  /// \sa SafeLeftShift
2694  template <class T>
2695  static inline T RightShift(T value, unsigned int bits)
2696  {
2697  return value >> bits;
2698  }
2699 
2700  /// \brief Left shifts a value that does not overflow
2701  /// \tparam T class or type
2702  /// \return the shifted value
2703  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2704  /// \sa SafeRightShift
2705  template <class T>
2706  static inline T LeftShift(T value, unsigned int bits)
2707  {
2708  return value << bits;
2709  }
2710 };
2711 
2712 /// \brief Safely right shift values when undefined behavior could occur
2713 /// \tparam bits the number of bit positions to shift the value
2714 /// \tparam T class or type
2715 /// \param value the value to right shift
2716 /// \result the shifted value or 0
2717 /// \details SafeRightShift safely shifts the value to the right when undefined behavior
2718 /// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0
2719 /// if undefined behavior would occur.
2720 template <unsigned int bits, class T>
2721 inline T SafeRightShift(T value)
2722 {
2723  return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
2724 }
2725 
2726 /// \brief Safely left shift values when undefined behavior could occur
2727 /// \tparam bits the number of bit positions to shift the value
2728 /// \tparam T class or type
2729 /// \param value the value to left shift
2730 /// \result the shifted value or 0
2731 /// \details SafeLeftShift safely shifts the value to the left when undefined behavior
2732 /// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0
2733 /// if undefined behavior would occur.
2734 template <unsigned int bits, class T>
2735 inline T SafeLeftShift(T value)
2736 {
2737  return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
2738 }
2739 
2740 /// \brief Finds first element not in a range
2741 /// \tparam InputIt Input iterator type
2742 /// \tparam T class or type
2743 /// \param first iterator to first element
2744 /// \param last iterator to last element
2745 /// \param value the value used as a predicate
2746 /// \returns iterator to the first element in the range that is not value
2747 template<typename InputIt, typename T>
2748 inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) {
2749 #ifdef CRYPTOPP_CXX11_LAMBDA
2750  return std::find_if(first, last, [&value](const T &o) {
2751  return value!=o;
2752  });
2753 #else
2754  return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value));
2755 #endif
2756 }
2757 
2758 // ************** use one buffer for multiple data members ***************
2759 
2760 #define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2761 #define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2762 #define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2763 #define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2764 #define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2765 #define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2766 #define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2767 #define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2768 #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
2769 
2770 NAMESPACE_END
2771 
2772 #if (CRYPTOPP_MSC_VERSION)
2773 # pragma warning(pop)
2774 #endif
2775 
2776 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
2777 # pragma GCC diagnostic pop
2778 #endif
2779 
2780 #endif
void SecureWipeBuffer(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1338
InputIt FindIfNot(InputIt first, InputIt last, const T &value)
Finds first element not in a range.
Definition: misc.h:2748
the cipher is performing decryption
Definition: cryptlib.h:127
An invalid argument was detected.
Definition: cryptlib.h:202
CRYPTOPP_DLL std::string IntToString< Integer >(Integer value, unsigned int base)
Converts an Integer to a string.
Definition: integer.cpp:4738
std::string StringNarrow(const wchar_t *str, bool throwOnError=true)
Converts a wide character C-string to a multibyte string.
Definition: misc.cpp:140
bool NativeByteOrderIs(ByteOrder order)
Determines whether order follows native byte ordering.
Definition: misc.h:1224
void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memmove()
Definition: misc.h:523
CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr)
Frees a buffer allocated with AlignedAllocate.
Definition: misc.cpp:312
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:657
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
Restricts the instantiation of a class to one static object without locks.
Definition: misc.h:298
void IncrementCounterByOne(byte *inout, unsigned int size)
Performs an addition with carry on a block of bytes.
Definition: misc.h:1262
T2 ModPowerOf2(const T1 &a, const T2 &b)
Reduces a value to a power of 2.
Definition: misc.h:1072
T SafeRightShift(T value)
Safely right shift values when undefined behavior could occur.
Definition: misc.h:2721
size_t BitsToBytes(size_t bitCount)
Returns the number of 8-bit bytes or octets required for the specified number of bits.
Definition: misc.h:885
T StringToWord(const std::string &str, ByteOrder order=BIG_ENDIAN_ORDER)
Convert a string to a word.
Definition: misc.h:2637
ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
Determine pointer difference.
Definition: misc.h:406
bool IsAligned(const void *ptr)
Determines whether ptr is minimally aligned.
Definition: misc.h:1193
T rotlFixed(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1602
size_t BitsToWords(size_t bitCount)
Returns the number of words required for the specified number of bits.
Definition: misc.h:905
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2506
unsigned int BytePrecision(const T &value)
Returns the number of 8-bit bytes or octets required for a value.
Definition: misc.h:766
PutBlock(const void *xorBlock, void *block)
Construct a PutBlock.
Definition: misc.h:2579
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:135
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:123
byte * BytePtr(std::string &str)
Pointer to the first element of a string.
Definition: misc.h:430
Abstract base classes that provide a uniform interface to this library.
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:478
unsigned int GetAlignmentOf()
Returns the minimum alignment requirements of a type.
Definition: misc.h:1147
static T LeftShift(T value, unsigned int bits)
Left shifts a value that does not overflow.
Definition: misc.h:2706
An object factory function.
Definition: misc.h:248
Classes for automatic resource management.
Library configuration file.
size_t BytesToWords(size_t byteCount)
Returns the number of words required for the specified number of bytes.
Definition: misc.h:895
Common C++ header files.
std::string WordToString(T value, ByteOrder order=BIG_ENDIAN_ORDER)
Convert a word to a string.
Definition: misc.h:2623
T rotlVariable(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1651
Access a block of memory.
Definition: misc.h:2610
byte BitReverse(byte value)
Reverses bits in a 8-bit value.
Definition: misc.h:2099
byte order is little-endian
Definition: cryptlib.h:145
the cipher is performing encryption
Definition: cryptlib.h:125
T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
Access a block of memory.
Definition: misc.h:2464
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1454
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:1179
Uses encapsulation to hide an object in derived classes.
Definition: misc.h:219
T NumericLimitsMin()
Provide the minimum value for a type.
Definition: misc.h:990
size_t PtrByteDiff(const PTR pointer1, const PTR pointer2)
Determine pointer difference.
Definition: misc.h:421
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:100
CRYPTOPP_DLL void *CRYPTOPP_API UnalignedAllocate(size_t size)
Allocates a buffer.
Definition: misc.cpp:324
Manages resources for a single object.
Definition: smartptr.h:18
unsigned int TrailingZeros(word32 v)
Determines the number of trailing 0-bits in a value.
Definition: misc.h:814
T rotlConstant(T x)
Performs a left rotate.
Definition: misc.h:1551
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:146
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:873
T ConditionalByteReverse(ByteOrder order, T value)
Reverses bytes in a value depending upon endianness.
Definition: misc.h:2191
CRYPTOPP_DLL std::string IntToString< word64 >(word64 value, unsigned int base)
Converts an unsigned value to a string.
Definition: integer.cpp:4804
void ConditionalSwapPointers(bool c, T &a, T &b)
Performs a branchless swap of pointers a and b if condition c is true.
Definition: misc.h:1321
CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr)
Frees a buffer allocated with UnalignedAllocate.
Definition: misc.cpp:332
const byte * ConstBytePtr(const std::string &str)
Const pointer to the first element of a string.
Definition: misc.h:444
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
T1 SaturatingSubtract(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 0.
Definition: misc.h:1040
CipherDir GetCipherDir(const T &obj)
Returns the direction the cipher is being operated.
Definition: misc.h:1240
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
Definition: misc.h:641
bool IsPowerOf2(const T &value)
Tests whether a value is a power of 2.
Definition: misc.h:957
CRYPTOPP_DLL void *CRYPTOPP_API AlignedAllocate(size_t size)
Allocates a buffer on 16-byte boundary.
Definition: misc.cpp:283
static T RightShift(T value, unsigned int bits)
Right shifts a value that does not overflow.
Definition: misc.h:2695
#define MEMORY_BARRIER
A memory barrier.
Definition: misc.h:262
void * memset_z(void *ptr, int value, size_t num)
Memory block initializer and eraser that attempts to survive optimizations.
Definition: misc.h:585
unsigned int Parity(T value)
Returns the parity of a value.
Definition: misc.h:754
byte order is big-endian
Definition: cryptlib.h:147
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:602
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
T NumericLimitsMax()
Provide the maximum value for a type.
Definition: misc.h:1008
std::wstring StringWiden(const char *str, bool throwOnError=true)
Converts a multibyte C-string to a wide character string.
Definition: misc.cpp:204
CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler()
Attempts to reclaim unused memory.
Definition: misc.cpp:268
PutBlock< T, B, A > & operator()(U x)
Access a block of memory.
Definition: misc.h:2587
void ConditionalSwap(bool c, T &a, T &b)
Performs a branchless swap of values a and b if condition c is true.
Definition: misc.h:1308
PTR PtrSub(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition: misc.h:391
T1 SaturatingSubtract1(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 1.
Definition: misc.h:1057
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition: misc.h:378
GetBlock(const void *block)
Construct a GetBlock.
Definition: misc.h:2537
T SafeLeftShift(T value)
Safely left shift values when undefined behavior could occur.
Definition: misc.h:2735
static T RightShift(T value, unsigned int bits)
Right shifts a value that overflows.
Definition: misc.h:2665
T rotrConstant(T x)
Performs a right rotate.
Definition: misc.h:1577
Access a block of memory.
Definition: misc.h:2532
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:671
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
Definition: misc.cpp:32
GetBlock< T, B, A > & operator()(U &x)
Access a block of memory.
Definition: misc.h:2545
An Empty class.
Definition: misc.h:199
ByteOrder GetNativeByteOrder()
Returns NativeByteOrder as an enumerated ByteOrder value.
Definition: misc.h:1216
T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
Rounds a value up to a multiple of a second value.
Definition: misc.h:1121
Safely shift values when undefined behavior could occur.
Definition: misc.h:2652
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:613
Access a block of memory.
Definition: misc.h:2573
Crypto++ library namespace.
T rotrVariable(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1671
size_t BytePtrSize(const std::string &str)
Size of a string.
Definition: misc.h:453
T rotlMod(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1688
unsigned int GetByte(ByteOrder order, T value, unsigned int index)
Gets a byte from a value.
Definition: misc.h:2013
T rotrMod(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1704
T rotrFixed(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1627
Ensures an object is not copyable.
Definition: misc.h:230
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:2025
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
Definition: misc.h:789
const T & Ref(...) const
Return a reference to the inner Singleton object.
Definition: misc.h:319
size_t BitsToDwords(size_t bitCount)
Returns the number of double words required for the specified number of bits.
Definition: misc.h:915
static T LeftShift(T value, unsigned int bits)
Left shifts a value that overflows.
Definition: misc.h:2677
T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
Rounds a value down to a multiple of a second value.
Definition: misc.h:1091
void vec_swap(T &a, T &b)
Swaps two variables which are arrays.
Definition: misc.h:566