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 "./base.h"
0014 
0015 typedef uint64_t uint64Array[30];
0016 static int precomputedArraySize = sizeof(uint64Array) / sizeof(uint64_t);
0017 
0018 inline uint64_t customPow(uint64Array *precomputedPowers, bool usePrecomputed,
0019     uint64_t base, int exp) {
0020   if (usePrecomputed && exp < precomputedArraySize) {
0021     return (*precomputedPowers)[exp];
0022   }
0023 
0024   // TOOD: Optimization possible here when passed in toSize which is bigger
0025   // than precomputedArraySize, we can start from the value of the last
0026   // precomputed value.
0027   uint64_t result = 1;
0028   while (exp) {
0029     if (exp & 1)
0030       result *= base;
0031     exp >>= 1;
0032     base *= base;
0033   }
0034   return result;
0035 }
0036 
0037 
0038 // Functor for a hashing function
0039 // Implements a Rabin fingerprint hash function
0040 class HashFn {
0041  public:
0042   // Initialize a HashFn with the prime p which is used as the base of the Rabin
0043   // fingerprint algorithm
0044   explicit HashFn(int p, bool precompute = true) {
0045     this->p = p;
0046     this->precompute = precompute;
0047     if (precompute) {
0048       uint64_t result = 1;
0049       for (int i = 0; i < precomputedArraySize; i++) {
0050         precomputedPowers[i] = result;
0051         result *= p;
0052       }
0053     }
0054   }
0055 
0056   virtual uint64_t operator()(const char *input, int len,
0057       unsigned char lastCharCode, uint64_t lastHash);
0058 
0059   virtual uint64_t operator()(const char *input, int len);
0060 
0061  private:
0062   int p;
0063   bool precompute;
0064   uint64Array precomputedPowers;
0065 };
0066 
0067 #endif  // HASHFN_H_