1 /*
2  * Copyright (c) 2021 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 #include "hash.h"
17 
18 namespace DistributedDB {
HashFunc(const std::string & input)19 uint64_t Hash::HashFunc(const std::string &input)
20 {
21     uint64_t hash = 0;
22     size_t idx = 0;
23 
24     for (idx = 0; idx < input.size(); idx++) {
25         hash = (hash * PRIME_SEED) + input.at(idx);
26     }
27 
28     return hash;
29 }
30 
Hash32Func(const std::string & input)31 uint32_t Hash::Hash32Func(const std::string &input)
32 {
33     uint32_t hash = 0;
34     size_t idx = 0;
35 
36     for (idx = 0; idx < input.size(); idx++) {
37         hash = (hash << 4) + input.at(idx); // left shift the lowest 4 bits for 4 bits.
38         uint32_t x = (hash & 0xf0000000);
39         if (x != 0) {
40             hash ^= (x >> 24); // right shift the high byte for 24 bits.
41         }
42         hash &= ~x;
43     }
44     return (hash & 0x7fffffff);
45 }
46 } // namespace DistributedDB
47