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.base.Preconditions;
019import com.google.common.primitives.Ints;
020
021import java.security.MessageDigest;
022
023import javax.annotation.Nullable;
024
025/**
026 * An immutable hash code of arbitrary bit length.
027 *
028 * @author Dimitris Andreou
029 * @since 11.0
030 */
031@Beta
032public abstract class HashCode {
033  HashCode() {}
034
035  /**
036   * Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
037   * an {@code int} value in little-endian order.
038   *
039   * @throws IllegalStateException if {@code bits() < 32}
040   */
041  public abstract int asInt();
042
043  /**
044   * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
045   * a {@code long} value in little-endian order.
046   *
047   * @throws IllegalStateException if {@code bits() < 64}
048   */
049  public abstract long asLong();
050
051  /**
052   * If this hashcode has enough bits, returns {@code asLong()}, otherwise returns a {@code long}
053   * value with {@code asInt()} as the least-significant four bytes and {@code 0x00} as
054   * each of the most-significant four bytes.
055   *
056   * @since 14.0 (since 11.0 as {@code Hashing.padToLong(HashCode)})
057   */
058  public abstract long padToLong();
059
060  /**
061   * Returns the value of this hash code as a byte array. The caller may modify the byte array;
062   * changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays
063   * returned by this method.
064   */
065  // TODO(user): consider ByteString here, when that is available
066  public abstract byte[] asBytes();
067
068  /**
069   * Copies bytes from this hash code into {@code dest}.
070   *
071   * @param dest the byte array into which the hash code will be written
072   * @param offset the start offset in the data
073   * @param maxLength the maximum number of bytes to write
074   * @return the number of bytes written to {@code dest}
075   * @throws IndexOutOfBoundsException if there is not enough room in {@code dest}
076   */
077  public int writeBytesTo(byte[] dest, int offset, int maxLength) {
078    byte[] hash = asBytes();
079    maxLength = Ints.min(maxLength, hash.length);
080    Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length);
081    System.arraycopy(hash, 0, dest, offset, maxLength);
082    return maxLength;
083  }
084
085  /**
086   * Returns the number of bits in this hash code; a positive multiple of 8.
087   */
088  public abstract int bits();
089
090  @Override public boolean equals(@Nullable Object object) {
091    if (object instanceof HashCode) {
092      HashCode that = (HashCode) object;
093      // Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic
094      // hash code, in which case we don't want to leak timing information
095      return MessageDigest.isEqual(this.asBytes(), that.asBytes());
096    }
097    return false;
098  }
099
100  /**
101   * Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined
102   * (so, for example, you can safely put {@code HashCode} instances into a {@code
103   * HashSet}) but is otherwise probably not what you want to use.
104   */
105  @Override public int hashCode() {
106    /*
107     * As long as the hash function that produced this isn't of horrible quality, this
108     * won't be of horrible quality either.
109     */
110    return asInt();
111  }
112
113  /**
114   * Returns a string containing each byte of {@link #asBytes}, in order, as a two-digit unsigned
115   * hexadecimal number in lower case.
116   *
117   * <p>Note that if the output is considered to be a single hexadecimal number, this hash code's
118   * bytes are the <i>big-endian</i> representation of that number. This may be surprising since
119   * everything else in the hashing API uniformly treats multibyte values as little-endian. But
120   * this format conveniently matches that of utilities such as the UNIX {@code md5sum} command.
121   */
122  @Override public String toString() {
123    byte[] bytes = asBytes();
124    StringBuilder sb = new StringBuilder(2 * bytes.length);
125    for (byte b : bytes) {
126      sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]);
127    }
128    return sb.toString();
129  }
130
131  private static final char[] hexDigits = "0123456789abcdef".toCharArray();
132}