blob: ff5d252a4f15e2e8f88b121956f87539bd5383da [file] [log] [blame]
Raph Levienb6ea1752012-10-25 23:11:13 -07001/*
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
Nick Kralevich1f286982015-08-22 14:27:03 -070022#include <stdlib.h>
Raph Levienb6ea1752012-10-25 23:11:13 -070023#include <utils/JenkinsHash.h>
24
25namespace android {
26
Nick Kralevich1f286982015-08-22 14:27:03 -070027#ifdef __clang__
28__attribute__((no_sanitize("integer")))
29#endif
Raph Levienb6ea1752012-10-25 23:11:13 -070030hash_t JenkinsHashWhiten(uint32_t hash) {
31 hash += (hash << 3);
32 hash ^= (hash >> 11);
33 hash += (hash << 15);
34 return hash;
35}
36
37uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size) {
Nick Kralevich1f286982015-08-22 14:27:03 -070038 if (size > UINT32_MAX) {
39 abort();
40 }
Raph Levienb6ea1752012-10-25 23:11:13 -070041 hash = JenkinsHashMix(hash, (uint32_t)size);
42 size_t i;
43 for (i = 0; i < (size & -4); i += 4) {
44 uint32_t data = bytes[i] | (bytes[i+1] << 8) | (bytes[i+2] << 16) | (bytes[i+3] << 24);
45 hash = JenkinsHashMix(hash, data);
46 }
47 if (size & 3) {
48 uint32_t data = bytes[i];
49 data |= ((size & 3) > 1) ? (bytes[i+1] << 8) : 0;
50 data |= ((size & 3) > 2) ? (bytes[i+2] << 16) : 0;
51 hash = JenkinsHashMix(hash, data);
52 }
53 return hash;
54}
55
56uint32_t JenkinsHashMixShorts(uint32_t hash, const uint16_t* shorts, size_t size) {
Nick Kralevich1f286982015-08-22 14:27:03 -070057 if (size > UINT32_MAX) {
58 abort();
59 }
Raph Levienb6ea1752012-10-25 23:11:13 -070060 hash = JenkinsHashMix(hash, (uint32_t)size);
61 size_t i;
62 for (i = 0; i < (size & -2); i += 2) {
63 uint32_t data = shorts[i] | (shorts[i+1] << 16);
64 hash = JenkinsHashMix(hash, data);
65 }
66 if (size & 1) {
67 uint32_t data = shorts[i];
68 hash = JenkinsHashMix(hash, data);
69 }
70 return hash;
71}
72
73}
74