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