1/*
2 * Copyright (C) 2011 The Guava Authors
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
17package com.google.common.hash;
18
19import static com.google.common.hash.HashTestUtils.ascii;
20import static com.google.common.hash.HashTestUtils.toBytes;
21import static com.google.common.hash.Hashing.murmur3_128;
22import static java.nio.ByteOrder.LITTLE_ENDIAN;
23
24import com.google.common.hash.Funnels;
25import com.google.common.hash.HashTestUtils.HashFn;
26
27import junit.framework.TestCase;
28
29import java.util.Arrays;
30
31/**
32 * Tests for Murmur3Hash128.
33 */
34public class Murmur3Hash128Test extends TestCase {
35  public void testCompatibilityWithCPlusPlus() {
36    assertHash(0, toBytes(LITTLE_ENDIAN, 0x629942693e10f867L, 0x92db0b82baeb5347L),
37        ascii("hell"));
38    assertHash(1, toBytes(LITTLE_ENDIAN, 0xa78ddff5adae8d10L, 0x128900ef20900135L),
39        ascii("hello"));
40    assertHash(2, toBytes(LITTLE_ENDIAN, 0x8a486b23f422e826L, 0xf962a2c58947765fL),
41        ascii("hello "));
42    assertHash(3, toBytes(LITTLE_ENDIAN, 0x2ea59f466f6bed8cL, 0xc610990acc428a17L),
43        ascii("hello w"));
44    assertHash(4, toBytes(LITTLE_ENDIAN, 0x79f6305a386c572cL, 0x46305aed3483b94eL),
45        ascii("hello wo"));
46    assertHash(5, toBytes(LITTLE_ENDIAN, 0xc2219d213ec1f1b5L, 0xa1d8e2e0a52785bdL),
47        ascii("hello wor"));
48    assertHash(0, toBytes(LITTLE_ENDIAN, 0xe34bbc7bbc071b6cL, 0x7a433ca9c49a9347L),
49        ascii("The quick brown fox jumps over the lazy dog"));
50    assertHash(0, toBytes(LITTLE_ENDIAN, 0x658ca970ff85269aL, 0x43fee3eaa68e5c3eL),
51        ascii("The quick brown fox jumps over the lazy cog"));
52  }
53
54  private static void assertHash(int seed, byte[] expectedHash, byte[] input) {
55    byte[] hash = murmur3_128(seed).newHasher().putBytes(input).hash().asBytes();
56    assertTrue(Arrays.equals(expectedHash, hash));
57  }
58
59  public void testParanoid() {
60    HashFn hf = new HashFn() {
61      @Override public byte[] hash(byte[] input, int seed) {
62        Hasher hasher = murmur3_128(seed).newHasher();
63        Funnels.byteArrayFunnel().funnel(input, hasher);
64        return hasher.hash().asBytes();
65      }
66    };
67    // the magic number comes from:
68    // http://code.google.com/p/smhasher/source/browse/trunk/main.cpp, #74
69    HashTestUtils.verifyHashFunction(hf, 128, 0x6384BA69);
70  }
71}
72