File indexing completed on 2024-11-24 04:54:36
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> 0014 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 in toSize 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 0040 // Functor for a hashing function 0041 // Implements a Rabin fingerprint hash function 0042 class HashFn { 0043 public: 0044 // Initialize a HashFn with the prime p which is used as the base of the Rabin 0045 // fingerprint algorithm 0046 explicit HashFn(int p, bool precompute = true) { 0047 this->p = p; 0048 this->precompute = precompute; 0049 if (precompute) { 0050 uint64_t result = 1; 0051 for (int i = 0; i < precomputedArraySize; i++) { 0052 precomputedPowers[i] = result; 0053 result *= p; 0054 } 0055 } 0056 } 0057 0058 virtual uint64_t operator()(const char *input, int len, 0059 unsigned char lastCharCode, uint64_t lastHash); 0060 virtual uint64_t operator()(const char *input, int len); 0061 0062 private: 0063 int p; 0064 bool precompute; 0065 uint64Array precomputedPowers; 0066 }; 0067 0068 #endif // HASHFN_H_