Teuchos - Trilinos Tools Package  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Teuchos_HashUtils.cpp
1 // @HEADER
2 // *****************************************************************************
3 // Teuchos: Common Tools Package
4 //
5 // Copyright 2004 NTESS and the Teuchos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9 
10 #include "Teuchos_HashUtils.hpp"
11 #include "Teuchos_Assert.hpp"
12 #include "Teuchos_CompilerCodeTweakMacros.hpp"
13 
14 using namespace Teuchos;
15 
16 
17 const int HashUtils::primeCount_ = 33;
18 const int HashUtils::primes_[]
19 = {11, 19, 37, 59, 101, 163, 271, 443, 733, 1187, 1907, 3061,
20  4919, 7759, 12379, 19543, 30841, 48487, 75989,
21  119089, 185971, 290347, 452027, 703657, 1093237,
22  1695781, 2627993, 4067599, 6290467, 9718019,
23  15000607, 23133937, 35650091};
24 
25 
26 int HashUtils::nextPrime(int newCapacity)
27 {
28  TEUCHOS_TEST_FOR_EXCEPTION(newCapacity > primes_[primeCount_-1],
29  std::logic_error,
30  "HashUtils::nextPrime() overflow");
31 
32  for (int i=0; i<primeCount_; i++)
33  {
34  if (newCapacity <= primes_[i])
35  {
36  return primes_[i];
37  }
38  }
39 
41  std::logic_error,
42  "unexpected case in HashUtils::nextPrime()");
44 }
45 
52 int HashUtils::getHashCode(const unsigned char *a, size_t len)
53 {
54  int total=0;
55  unsigned char *to = reinterpret_cast<unsigned char *>(&total);
56  int c=0;
57  for (size_t i=0; i < len; i++){
58  to[c++] += a[i];
59  if (c == sizeof(int))
60  c = 0;
61  }
62  if (total < 0)
63  {
64  /* Convert the largest -ve int to zero and -1 to
65  * std::numeric_limits<int>::max()
66  * */
67  size_t maxIntBeforeWrap = std::numeric_limits<int>::max();
68  maxIntBeforeWrap ++;
69  total += maxIntBeforeWrap;
70  }
71  return total;
72 }
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
static int getHashCode(const unsigned char *a, size_t len)
#define TEUCHOS_UNREACHABLE_RETURN(dummyReturnVal)
Avoid warning about unreachable or missing return from function.
Utilities for generating hashcodes.