1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef ECMASCRIPT_PLATFORM_ECMA_STRING_HASH_COMMON_H 17 #define ECMASCRIPT_PLATFORM_ECMA_STRING_HASH_COMMON_H 18 19 #include <cstdint> 20 21 #include "ecmascript/platform/ecma_string_hash.h" 22 23 namespace panda::ecmascript { 24 class EcmaStringHashInternal { 25 friend class EcmaStringHashHelper; 26 private: 27 template <typename T> ComputeHashForDataOfLongString(const T * data,size_t size,uint32_t hashSeed)28 static uint32_t ComputeHashForDataOfLongString(const T *data, size_t size, 29 uint32_t hashSeed) 30 { 31 constexpr uint32_t hashShift = static_cast<uint32_t>(EcmaStringHash::HASH_SHIFT); 32 constexpr uint32_t blockSize = static_cast<size_t>(EcmaStringHash::BLOCK_SIZE); 33 uint32_t hash[blockSize] = {0}; 34 uint32_t index = 0; 35 for (; index + blockSize <= size; index += blockSize) { 36 hash[0] = (hash[0] << hashShift) - hash[0] + data[index]; 37 hash[1] = (hash[1] << hashShift) - hash[1] + data[index + 1]; // 1: the second element of the block 38 hash[2] = (hash[2] << hashShift) - hash[2] + data[index + 2]; // 2: the third element of the block 39 hash[3] = (hash[3] << hashShift) - hash[3] + data[index + 3]; // 3: the fourth element of the block 40 } 41 for (; index < size; ++index) { 42 hash[0] = (hash[0] << hashShift) - hash[0] + data[index]; 43 } 44 uint32_t totalHash = hashSeed; 45 for (uint32_t i = 0; i < blockSize; ++i) { 46 totalHash = (totalHash << hashShift) - totalHash + hash[i]; 47 } 48 return totalHash; 49 } 50 }; 51 } // namespace panda::ecmascript 52 #endif // ECMASCRIPT_PLATFORM_ECMA_STRING_HASH_COMMON_H