Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
   * in compliance with the License. You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software distributed under the License
  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
 
 package com.google.common.hash;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 
 
 
 import  javax.annotation.Nullable;

An immutable hash code of arbitrary bit length.

Author(s):
Dimitris Andreou
Kurt Alfred Kluever
Since:
11.0
 
 public abstract class HashCode {
   HashCode() {}

  
Returns the first four bytes of this hashcode's bytes, converted to an int value in little-endian order.

Throws:
IllegalStateException if bits() < 32
 
   public abstract int asInt();

  
Returns the first eight bytes of this hashcode's bytes, converted to a long value in little-endian order.

Throws:
IllegalStateException if bits() < 64
 
   public abstract long asLong();

  
If this hashcode has enough bits, returns asLong(), otherwise returns a long value with asBytes() as the least-significant bytes and 0x00 as the remaining most-significant bytes.

Since:
14.0 (since 11.0 as Hashing.padToLong(HashCode))
 
   public abstract long padToLong();

  
Returns the value of this hash code as a byte array. The caller may modify the byte array; changes to it will not be reflected in this HashCode object or any other arrays returned by this method.
 
   // TODO(user): consider ByteString here, when that is available
   public abstract byte[] asBytes();

  
Creates a 32-bit HashCode representation of the given int value. The underlying bytes are interpreted in little endian order.

Since:
15.0 (since 12.0 in HashCodes)
 
   public static HashCode fromInt(int hash) {
     return new IntHashCode(hash);
   }
 
   private static final class IntHashCode extends HashCode implements Serializable {
     final int hash;
 
     IntHashCode(int hash) {
       this. = hash;
     }
 
     @Override
     public int bits() {
       return 32;
     }
 
     @Override
     public byte[] asBytes() {
       return new byte[] {
          (byte,
          (byte) ( >> 8),
          (byte) ( >> 16),
          (byte) ( >> 24)};
    }
    @Override
    public int asInt() {
      return ;
    }
    @Override
    public long asLong() {
      throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long");
    }
    @Override
    public long padToLong() {
      return UnsignedInts.toLong();
    }
    private static final long serialVersionUID = 0;
  }

  
Creates a 64-bit HashCode representation of the given long value. The underlying bytes are interpreted in little endian order.

Since:
15.0 (since 12.0 in HashCodes)
  public static HashCode fromLong(long hash) {
    return new LongHashCode(hash);
  }
  private static final class LongHashCode extends HashCode implements Serializable {
    final long hash;
    LongHashCode(long hash) {
      this. = hash;
    }
    @Override
    public int bits() {
      return 64;
    }
    @Override
    public byte[] asBytes() {
      return new byte[] {
          (byte,
          (byte) ( >> 8),
          (byte) ( >> 16),
          (byte) ( >> 24),
          (byte) ( >> 32),
          (byte) ( >> 40),
          (byte) ( >> 48),
          (byte) ( >> 56)};
    }
    @Override
    public int asInt() {
      return (int;
    }
    @Override
    public long asLong() {
      return ;
    }
    @Override
    public long padToLong() {
      return ;
    }
    private static final long serialVersionUID = 0;
  }

  
Creates a HashCode from a byte array. The array is defensively copied to preserve the immutability contract of HashCode. The array cannot be empty.

Since:
15.0 (since 12.0 in HashCodes)
  public static HashCode fromBytes(byte[] bytes) {
    checkArgument(bytes.length >= 1, "A HashCode must contain at least 1 byte.");
    return fromBytesNoCopy(bytes.clone());
  }

  
Creates a HashCode from a byte array. The array is not copied defensively, so it must be handed-off so as to preserve the immutability contract of HashCode.
  static HashCode fromBytesNoCopy(byte[] bytes) {
    return new BytesHashCode(bytes);
  }
  private static final class BytesHashCode extends HashCode implements Serializable {
    final byte[] bytes;
    BytesHashCode(byte[] bytes) {
      this. = checkNotNull(bytes);
    }
    @Override
    public int bits() {
      return . * 8;
    }
    @Override
    public byte[] asBytes() {
      return .clone();
    }
    @Override
    public int asInt() {
      checkState(. >= 4,
          "HashCode#asInt() requires >= 4 bytes (it only has %s bytes).".);
      return ([0] & 0xFF)
          | (([1] & 0xFF) << 8)
          | (([2] & 0xFF) << 16)
          | (([3] & 0xFF) << 24);
    }
    @Override
    public long asLong() {
      checkState(. >= 8,
          "HashCode#asLong() requires >= 8 bytes (it only has %s bytes).".);
      return padToLong();
    }
    @Override
    public long padToLong() {
      long retVal = ([0] & 0xFF);
      for (int i = 1; i < Math.min(., 8); i++) {
        retVal |= ([i] & 0xFFL) << (i * 8);
      }
      return retVal;
    }
    private static final long serialVersionUID = 0;
  }

  
Returns the number of bits in this hash code; a positive multiple of 8.
  public abstract int bits();

  
Creates a HashCode from a hexadecimal (base 16) encoded string. The string must be at least 2 characters long, and contain only valid, lower-cased hexadecimal characters.

This method accepts the exact format generated by toString. If you require more lenient base 16 decoding, please use com.google.common.io.BaseEncoding.decode (and pass the result to fromBytes).

Since:
15.0
  public static HashCode fromString(String string) {
    checkArgument(string.length() >= 2,
        "input string (%s) must have at least 2 characters"string);
    checkArgument(string.length() % 2 == 0,
        "input string (%s) must have an even number of characters"string);
    byte[] bytes = new byte[string.length() / 2];
    for (int i = 0; i < string.length(); i += 2) {
      int ch1 = decode(string.charAt(i)) << 4;
      int ch2 = decode(string.charAt(i + 1));
      bytes[i / 2] = (byte) (ch1 + ch2);
    }
    return fromBytesNoCopy(bytes);
  }
  private static int decode(char ch) {
    if (ch >= '0' && ch <= '9') {
      return ch - '0';
    }
    if (ch >= 'a' && ch <= 'f') {
      return ch - 'a' + 10;
    }
    throw new IllegalArgumentException("Illegal hexadecimal character: " + ch);
  }

  
Copies bytes from this hash code into dest.

Parameters:
dest the byte array into which the hash code will be written
offset the start offset in the data
maxLength the maximum number of bytes to write
Returns:
the number of bytes written to dest
Throws:
IndexOutOfBoundsException if there is not enough room in dest
  public final int writeBytesTo(byte[] destint offsetint maxLength) {
    maxLength = Ints.min(maxLengthbits() / 8);
    Preconditions.checkPositionIndexes(offsetoffset + maxLengthdest.length);
    // TODO(user): Consider avoiding the array creation in asBytes() by stepping through
    // the bytes individually.
    byte[] hash = asBytes();
    System.arraycopy(hash, 0, destoffsetmaxLength);
    return maxLength;
  }
  public final boolean equals(@Nullable Object object) {
    if (object instanceof HashCode) {
      HashCode that = (HashCodeobject;
      // Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic
      // hash code, in which case we don't want to leak timing information
      return MessageDigest.isEqual(this.asBytes(), that.asBytes());
    }
    return false;
  }

  
Returns a "Java hash code" for this HashCode instance; this is well-defined (so, for example, you can safely put HashCode instances into a HashSet) but is otherwise probably not what you want to use.
  public final int hashCode() {
    // If we have at least 4 bytes (32 bits), just take the first 4 bytes. Since this is
    // already a (presumably) high-quality hash code, any four bytes of it will do.
    if (bits() >= 32) {
      return asInt();
    }
    // If we have less than 4 bytes, use them all.
    byte[] bytes = asBytes();
    int val = (bytes[0] & 0xFF);
    for (int i = 1; i < bytes.lengthi++) {
      val |= ((bytes[i] & 0xFF) << (i * 8));
    }
    return val;
  }

  
Returns a string containing each byte of asBytes, in order, as a two-digit unsigned hexadecimal number in lower case.

Note that if the output is considered to be a single hexadecimal number, this hash code's bytes are the big-endian representation of that number. This may be surprising since everything else in the hashing API uniformly treats multibyte values as little-endian. But this format conveniently matches that of utilities such as the UNIX md5sum command.

To create a HashCode from its string representation, see fromString.

  public final String toString() {
    byte[] bytes = asBytes();
    StringBuilder sb = new StringBuilder(2 * bytes.length);
    for (byte b : bytes) {
      sb.append([(b >> 4) & 0xf]).append([b & 0xf]);
    }
    return sb.toString();
  }
  private static final char[] hexDigits = "0123456789abcdef".toCharArray();
New to GrepCode? Check out our FAQ X