• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.hash;
16 
17 import com.google.common.annotations.Beta;
18 import com.google.common.base.Preconditions;
19 import com.google.common.primitives.Ints;
20 
21 import java.security.MessageDigest;
22 
23 /**
24  * An immutable hash code of arbitrary bit length.
25  *
26  * @author Dimitris Andreou
27  * @since 11.0
28  */
29 @Beta
30 public abstract class HashCode {
HashCode()31   HashCode() {}
32 
33   /**
34    * Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
35    * an {@code int} value in little-endian order.
36    */
asInt()37   public abstract int asInt();
38 
39   /**
40    * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
41    * a {@code long} value in little-endian order.
42    *
43    * @throws IllegalStateException if {@code bits() < 64}
44    */
asLong()45   public abstract long asLong();
46 
47   /**
48    * Returns the value of this hash code as a byte array. The caller may modify the byte array;
49    * changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays
50    * returned by this method.
51    */
52   // TODO(user): consider ByteString here, when that is available
asBytes()53   public abstract byte[] asBytes();
54 
55   /**
56    * Copies bytes from this hash code into {@code dest}.
57    *
58    * @param dest the byte array into which the hash code will be written
59    * @param offset the start offset in the data
60    * @param maxLength the maximum number of bytes to write
61    * @return the number of bytes written to {@code dest}
62    * @throws IndexOutOfBoundsException if there is not enough room in {@code dest}
63    */
writeBytesTo(byte[] dest, int offset, int maxLength)64   public int writeBytesTo(byte[] dest, int offset, int maxLength) {
65     byte[] hash = asBytes();
66     maxLength = Ints.min(maxLength, hash.length);
67     Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length);
68     System.arraycopy(hash, 0, dest, offset, maxLength);
69     return maxLength;
70   }
71 
72   /**
73    * Returns the number of bits in this hash code; a positive multiple of 32.
74    */
bits()75   public abstract int bits();
76 
equals(Object object)77   @Override public boolean equals(Object object) {
78     if (object instanceof HashCode) {
79       HashCode that = (HashCode) object;
80       // Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic
81       // hash code, in which case we don't want to leak timing information
82       return MessageDigest.isEqual(this.asBytes(), that.asBytes());
83     }
84     return false;
85   }
86 
87   /**
88    * Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined
89    * (so, for example, you can safely put {@code HashCode} instances into a {@code
90    * HashSet}) but is otherwise probably not what you want to use.
91    */
hashCode()92   @Override public int hashCode() {
93     /*
94      * As long as the hash function that produced this isn't of horrible quality, this
95      * won't be of horrible quality either.
96      */
97     return asInt();
98   }
99 
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    */
toString()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 }
121