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