001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.hash; 016 017import com.google.common.annotations.Beta; 018import com.google.common.primitives.Ints; 019import com.google.errorprone.annotations.Immutable; 020import java.nio.ByteBuffer; 021import java.nio.charset.Charset; 022 023/** 024 * A hash function is a collision-averse pure function that maps an arbitrary block of data to a 025 * number called a <i>hash code</i>. 026 * 027 * <h3>Definition</h3> 028 * 029 * <p>Unpacking this definition: 030 * 031 * <ul> 032 * <li><b>block of data:</b> the input for a hash function is always, in concept, an ordered byte 033 * array. This hashing API accepts an arbitrary sequence of byte and multibyte values (via 034 * {@link Hasher}), but this is merely a convenience; these are always translated into raw 035 * byte sequences under the covers. 036 * <li><b>hash code:</b> each hash function always yields hash codes of the same fixed bit length 037 * (given by {@link #bits}). For example, {@link Hashing#sha1} produces a 160-bit number, 038 * while {@link Hashing#murmur3_32()} yields only 32 bits. Because a {@code long} value is 039 * clearly insufficient to hold all hash code values, this API represents a hash code as an 040 * instance of {@link HashCode}. 041 * <li><b>pure function:</b> the value produced must depend only on the input bytes, in the order 042 * they appear. Input data is never modified. {@link HashFunction} instances should always be 043 * stateless, and therefore thread-safe. 044 * <li><b>collision-averse:</b> while it can't be helped that a hash function will sometimes 045 * produce the same hash code for distinct inputs (a "collision"), every hash function strives 046 * to <i>some</i> degree to make this unlikely. (Without this condition, a function that 047 * always returns zero could be called a hash function. It is not.) 048 * </ul> 049 * 050 * <p>Summarizing the last two points: "equal yield equal <i>always</i>; unequal yield unequal 051 * <i>often</i>." This is the most important characteristic of all hash functions. 052 * 053 * <h3>Desirable properties</h3> 054 * 055 * <p>A high-quality hash function strives for some subset of the following virtues: 056 * 057 * <ul> 058 * <li><b>collision-resistant:</b> while the definition above requires making at least <i>some</i> 059 * token attempt, one measure of the quality of a hash function is <i>how well</i> it succeeds 060 * at this goal. Important note: it may be easy to achieve the theoretical minimum collision 061 * rate when using completely <i>random</i> sample input. The true test of a hash function is 062 * how it performs on representative real-world data, which tends to contain many hidden 063 * patterns and clumps. The goal of a good hash function is to stamp these patterns out as 064 * thoroughly as possible. 065 * <li><b>bit-dispersing:</b> masking out any <i>single bit</i> from a hash code should yield only 066 * the expected <i>twofold</i> increase to all collision rates. Informally, the "information" 067 * in the hash code should be as evenly "spread out" through the hash code's bits as possible. 068 * The result is that, for example, when choosing a bucket in a hash table of size 2^8, 069 * <i>any</i> eight bits could be consistently used. 070 * <li><b>cryptographic:</b> certain hash functions such as {@link Hashing#sha512} are designed to 071 * make it as infeasible as possible to reverse-engineer the input that produced a given hash 072 * code, or even to discover <i>any</i> two distinct inputs that yield the same result. These 073 * are called <i>cryptographic hash functions</i>. But, whenever it is learned that either of 074 * these feats has become computationally feasible, the function is deemed "broken" and should 075 * no longer be used for secure purposes. (This is the likely eventual fate of <i>all</i> 076 * cryptographic hashes.) 077 * <li><b>fast:</b> perhaps self-explanatory, but often the most important consideration. We have 078 * published <a href="#noWeHaventYet">microbenchmark results</a> for many common hash 079 * functions. 080 * </ul> 081 * 082 * <h3>Providing input to a hash function</h3> 083 * 084 * <p>The primary way to provide the data that your hash function should act on is via a {@link 085 * Hasher}. Obtain a new hasher from the hash function using {@link #newHasher}, "push" the relevant 086 * data into it using methods like {@link Hasher#putBytes(byte[])}, and finally ask for the {@code 087 * HashCode} when finished using {@link Hasher#hash}. (See an {@linkplain #newHasher example} of 088 * this.) 089 * 090 * <p>If all you want to hash is a single byte array, string or {@code long} value, there are 091 * convenient shortcut methods defined directly on {@link HashFunction} to make this easier. 092 * 093 * <p>Hasher accepts primitive data types, but can also accept any Object of type {@code T} provided 094 * that you implement a {@link Funnel}{@code <T>} to specify how to "feed" data from that object 095 * into the function. (See {@linkplain Hasher#putObject an example} of this.) 096 * 097 * <p><b>Compatibility note:</b> Throughout this API, multibyte values are always interpreted in 098 * <i>little-endian</i> order. That is, hashing the byte array {@code {0x01, 0x02, 0x03, 0x04}} is 099 * equivalent to hashing the {@code int} value {@code 0x04030201}. If this isn't what you need, 100 * methods such as {@link Integer#reverseBytes} and {@link Ints#toByteArray} will help. 101 * 102 * <h3>Relationship to {@link Object#hashCode}</h3> 103 * 104 * <p>Java's baked-in concept of hash codes is constrained to 32 bits, and provides no separation 105 * between hash algorithms and the data they act on, so alternate hash algorithms can't be easily 106 * substituted. Also, implementations of {@code hashCode} tend to be poor-quality, in part because 107 * they end up depending on <i>other</i> existing poor-quality {@code hashCode} implementations, 108 * including those in many JDK classes. 109 * 110 * <p>{@code Object.hashCode} implementations tend to be very fast, but have weak collision 111 * prevention and <i>no</i> expectation of bit dispersion. This leaves them perfectly suitable for 112 * use in hash tables, because extra collisions cause only a slight performance hit, while poor bit 113 * dispersion is easily corrected using a secondary hash function (which all reasonable hash table 114 * implementations in Java use). For the many uses of hash functions beyond data structures, 115 * however, {@code Object.hashCode} almost always falls short -- hence this library. 116 * 117 * @author Kevin Bourrillion 118 * @since 11.0 119 */ 120@Beta 121@Immutable 122public interface HashFunction { 123 /** 124 * Begins a new hash code computation by returning an initialized, stateful {@code Hasher} 125 * instance that is ready to receive data. Example: 126 * 127 * <pre>{@code 128 * HashFunction hf = Hashing.md5(); 129 * HashCode hc = hf.newHasher() 130 * .putLong(id) 131 * .putBoolean(isActive) 132 * .hash(); 133 * }</pre> 134 */ 135 Hasher newHasher(); 136 137 /** 138 * Begins a new hash code computation as {@link #newHasher()}, but provides a hint of the expected 139 * size of the input (in bytes). This is only important for non-streaming hash functions (hash 140 * functions that need to buffer their whole input before processing any of it). 141 */ 142 Hasher newHasher(int expectedInputSize); 143 144 /** 145 * Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code for the given 146 * {@code int} value, interpreted in little-endian byte order. The implementation <i>might</i> 147 * perform better than its longhand equivalent, but should not perform worse. 148 * 149 * @since 12.0 150 */ 151 HashCode hashInt(int input); 152 153 /** 154 * Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code for the given 155 * {@code long} value, interpreted in little-endian byte order. The implementation <i>might</i> 156 * perform better than its longhand equivalent, but should not perform worse. 157 */ 158 HashCode hashLong(long input); 159 160 /** 161 * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation <i>might</i> 162 * perform better than its longhand equivalent, but should not perform worse. 163 */ 164 HashCode hashBytes(byte[] input); 165 166 /** 167 * Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The implementation 168 * <i>might</i> perform better than its longhand equivalent, but should not perform worse. 169 * 170 * @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or 171 * {@code len < 0} 172 */ 173 HashCode hashBytes(byte[] input, int off, int len); 174 175 /** 176 * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation <i>might</i> 177 * perform better than its longhand equivalent, but should not perform worse. 178 * 179 * @since 23.0 180 */ 181 HashCode hashBytes(ByteBuffer input); 182 183 /** 184 * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The implementation 185 * <i>might</i> perform better than its longhand equivalent, but should not perform worse. Note 186 * that no character encoding is performed; the low byte and high byte of each {@code char} are 187 * hashed directly (in that order). 188 * 189 * <p><b>Warning:</b> This method will produce different output than most other languages do when 190 * running the same hash function on the equivalent input. For cross-language compatibility, use 191 * {@link #hashString}, usually with a charset of UTF-8. For other use cases, use {@code 192 * hashUnencodedChars}. 193 * 194 * @since 15.0 (since 11.0 as hashString(CharSequence)). 195 */ 196 HashCode hashUnencodedChars(CharSequence input); 197 198 /** 199 * Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters are encoded using 200 * the given {@link Charset}. The implementation <i>might</i> perform better than its longhand 201 * equivalent, but should not perform worse. 202 * 203 * <p><b>Warning:</b> This method, which reencodes the input before hashing it, is useful only for 204 * cross-language compatibility. For other use cases, prefer {@link #hashUnencodedChars}, which is 205 * faster, produces the same output across Java releases, and hashes every {@code char} in the 206 * input, even if some are invalid. 207 */ 208 HashCode hashString(CharSequence input, Charset charset); 209 210 /** 211 * Shortcut for {@code newHasher().putObject(instance, funnel).hash()}. The implementation 212 * <i>might</i> perform better than its longhand equivalent, but should not perform worse. 213 * 214 * @since 14.0 215 */ 216 <T> HashCode hashObject(T instance, Funnel<? super T> funnel); 217 218 /** 219 * Returns the number of bits (a multiple of 32) that each hash code produced by this hash 220 * function has. 221 */ 222 int bits(); 223}