1 /* 2 * Copyright (C) 2008 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 17 package com.google.common.collect; 18 19 import com.google.common.annotations.GwtCompatible; 20 import com.google.common.primitives.Ints; 21 import org.checkerframework.checker.nullness.compatqual.NullableDecl; 22 23 /** 24 * Static methods for implementing hash-based collections. 25 * 26 * @author Kevin Bourrillion 27 * @author Jesse Wilson 28 * @author Austin Appleby 29 */ 30 @GwtCompatible 31 final class Hashing { Hashing()32 private Hashing() {} 33 34 /* 35 * These should be ints, but we need to use longs to force GWT to do the multiplications with 36 * enough precision. 37 */ 38 private static final long C1 = 0xcc9e2d51; 39 private static final long C2 = 0x1b873593; 40 41 /* 42 * This method was rewritten in Java from an intermediate step of the Murmur hash function in 43 * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the 44 * following header: 45 * 46 * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author 47 * hereby disclaims copyright to this source code. 48 */ smear(int hashCode)49 static int smear(int hashCode) { 50 return (int) (C2 * Integer.rotateLeft((int) (hashCode * C1), 15)); 51 } 52 smearedHash(@ullableDecl Object o)53 static int smearedHash(@NullableDecl Object o) { 54 return smear((o == null) ? 0 : o.hashCode()); 55 } 56 57 private static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; 58 closedTableSize(int expectedEntries, double loadFactor)59 static int closedTableSize(int expectedEntries, double loadFactor) { 60 // Get the recommended table size. 61 // Round down to the nearest power of 2. 62 expectedEntries = Math.max(expectedEntries, 2); 63 int tableSize = Integer.highestOneBit(expectedEntries); 64 // Check to make sure that we will not exceed the maximum load factor. 65 if (expectedEntries > (int) (loadFactor * tableSize)) { 66 tableSize <<= 1; 67 return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE; 68 } 69 return tableSize; 70 } 71 needsResizing(int size, int tableSize, double loadFactor)72 static boolean needsResizing(int size, int tableSize, double loadFactor) { 73 return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE; 74 } 75 } 76