1 | /** |
---|
2 | * Licensed to the Apache Software Foundation (ASF) under one |
---|
3 | * or more contributor license agreements. See the NOTICE file |
---|
4 | * distributed with this work for additional information |
---|
5 | * regarding copyright ownership. The ASF licenses this file |
---|
6 | * to you under the Apache License, Version 2.0 (the |
---|
7 | * "License"); you may not use this file except in compliance |
---|
8 | * with the License. You may obtain a copy of the License at |
---|
9 | * |
---|
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
---|
11 | * |
---|
12 | * Unless required by applicable law or agreed to in writing, software |
---|
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
---|
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
15 | * See the License for the specific language governing permissions and |
---|
16 | * limitations under the License. |
---|
17 | */ |
---|
18 | |
---|
19 | package org.apache.hadoop.util.hash; |
---|
20 | |
---|
21 | /** |
---|
22 | * This is a very fast, non-cryptographic hash suitable for general hash-based |
---|
23 | * lookup. See http://murmurhash.googlepages.com/ for more details. |
---|
24 | * |
---|
25 | * <p>The C version of MurmurHash 2.0 found at that site was ported |
---|
26 | * to Java by Andrzej Bialecki (ab at getopt org).</p> |
---|
27 | */ |
---|
28 | public class MurmurHash extends Hash { |
---|
29 | private static MurmurHash _instance = new MurmurHash(); |
---|
30 | |
---|
31 | public static Hash getInstance() { |
---|
32 | return _instance; |
---|
33 | } |
---|
34 | |
---|
35 | public int hash(byte[] data, int length, int seed) { |
---|
36 | int m = 0x5bd1e995; |
---|
37 | int r = 24; |
---|
38 | |
---|
39 | int h = seed ^ length; |
---|
40 | |
---|
41 | int len_4 = length >> 2; |
---|
42 | |
---|
43 | for (int i = 0; i < len_4; i++) { |
---|
44 | int i_4 = i << 2; |
---|
45 | int k = data[i_4 + 3]; |
---|
46 | k = k << 8; |
---|
47 | k = k | (data[i_4 + 2] & 0xff); |
---|
48 | k = k << 8; |
---|
49 | k = k | (data[i_4 + 1] & 0xff); |
---|
50 | k = k << 8; |
---|
51 | k = k | (data[i_4 + 0] & 0xff); |
---|
52 | k *= m; |
---|
53 | k ^= k >>> r; |
---|
54 | k *= m; |
---|
55 | h *= m; |
---|
56 | h ^= k; |
---|
57 | } |
---|
58 | |
---|
59 | // avoid calculating modulo |
---|
60 | int len_m = len_4 << 2; |
---|
61 | int left = length - len_m; |
---|
62 | |
---|
63 | if (left != 0) { |
---|
64 | if (left >= 3) { |
---|
65 | h ^= (int) data[length - 3] << 16; |
---|
66 | } |
---|
67 | if (left >= 2) { |
---|
68 | h ^= (int) data[length - 2] << 8; |
---|
69 | } |
---|
70 | if (left >= 1) { |
---|
71 | h ^= (int) data[length - 1]; |
---|
72 | } |
---|
73 | |
---|
74 | h *= m; |
---|
75 | } |
---|
76 | |
---|
77 | h ^= h >>> 13; |
---|
78 | h *= m; |
---|
79 | h ^= h >>> 15; |
---|
80 | |
---|
81 | return h; |
---|
82 | } |
---|
83 | } |
---|