File indexing completed on 2024-11-17 04:55:18

0001 /*
0002     SPDX-License-Identifier: MPL-2.0
0003 */
0004 
0005 /* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
0006  * This Source Code Form is subject to the terms of the Mozilla Public
0007  * License, v. 2.0. If a copy of the MPL was not distributed with this
0008  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
0009 
0010 #ifndef HASHFN_H_
0011 #define HASHFN_H_
0012 
0013 #include <cstdint>  // Add this line for uint64_t
0014 #include <functional>  // Add this line for std::hash
0015 #include "./base.h"
0016 
0017 typedef uint64_t uint64Array[30];
0018 static int precomputedArraySize = sizeof(uint64Array) / sizeof(uint64_t);
0019 
0020 inline uint64_t customPow(uint64Array *precomputedPowers, bool usePrecomputed,
0021     uint64_t base, int exp) {
0022   if (usePrecomputed && exp < precomputedArraySize) {
0023     return (*precomputedPowers)[exp];
0024   }
0025 
0026   // TOOD: Optimization possible here when passed intoSize which is bigger
0027   // than precomputedArraySize, we can start from the value of the last
0028   // precomputed value.
0029   uint64_t result = 1;
0030   while (exp) {
0031     if (exp & 1)
0032       result *= base;
0033     exp >>= 1;
0034     base *= base;
0035   }
0036   return result;
0037 }
0038 
0039 // Functor for a hashing function
0040 // Implements a Rabin fingerprint hash function
0041 class HashFn {
0042  public:
0043   // Initialize a HashFn with the prime p which is used as the base of the Rabin
0044   // fingerprint algorithm
0045   explicit HashFn(int p, bool precompute = true) {
0046     this->p = p;
0047     this->precompute = precompute;
0048     if (precompute) {
0049       uint64_t result = 1;
0050       for (int i = 0; i < precomputedArraySize; i++) {
0051         precomputedPowers[i] = result;
0052         result *= p;
0053       }
0054     }
0055   }
0056 
0057   virtual uint64_t operator()(const char *input, int len,
0058       unsigned char lastCharCode, uint64_t lastHash);
0059 
0060   virtual uint64_t operator()(const char *input, int len);
0061 
0062   virtual ~HashFn() {}
0063 
0064  private:
0065   int p;
0066   bool precompute;
0067   uint64Array precomputedPowers;
0068 };
0069 
0070 #endif  // HASHFN_H_