1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /* Implementation of Jenkins one-at-a-time hash function. These choices are
18 * optimized for code size and portability, rather than raw speed. But speed
19 * should still be quite good.
20 **/
21
22 #include <stdlib.h>
23 #include <utils/JenkinsHash.h>
24
25 namespace android {
26
27 #ifdef __clang__
28 __attribute__((no_sanitize("integer")))
29 #endif
30 hash_t
JenkinsHashWhiten(uint32_t hash)31 JenkinsHashWhiten(uint32_t hash) {
32 hash += (hash << 3);
33 hash ^= (hash >> 11);
34 hash += (hash << 15);
35 return hash;
36 }
37
JenkinsHashMixBytes(uint32_t hash,const uint8_t * bytes,size_t size)38 uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size) {
39 if (size > UINT32_MAX) {
40 abort();
41 }
42 hash = JenkinsHashMix(hash, (uint32_t)size);
43 size_t i;
44 for (i = 0; i < (size & -4); i += 4) {
45 uint32_t data = bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) |
46 (bytes[i + 3] << 24);
47 hash = JenkinsHashMix(hash, data);
48 }
49 if (size & 3) {
50 uint32_t data = bytes[i];
51 data |= ((size & 3) > 1) ? (bytes[i + 1] << 8) : 0;
52 data |= ((size & 3) > 2) ? (bytes[i + 2] << 16) : 0;
53 hash = JenkinsHashMix(hash, data);
54 }
55 return hash;
56 }
57
JenkinsHashMixShorts(uint32_t hash,const uint16_t * shorts,size_t size)58 uint32_t JenkinsHashMixShorts(uint32_t hash,
59 const uint16_t* shorts,
60 size_t size) {
61 if (size > UINT32_MAX) {
62 abort();
63 }
64 hash = JenkinsHashMix(hash, (uint32_t)size);
65 size_t i;
66 for (i = 0; i < (size & -2); i += 2) {
67 uint32_t data = shorts[i] | (shorts[i + 1] << 16);
68 hash = JenkinsHashMix(hash, data);
69 }
70 if (size & 1) {
71 uint32_t data = shorts[i];
72 hash = JenkinsHashMix(hash, data);
73 }
74 return hash;
75 }
76
77 } // namespace android
78