All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.clickzetta.platform.util.HashUtil Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package com.clickzetta.platform.util;

public class HashUtil {
  private static final int HASH_VAL_NULL = 0x58081667;
  private static final byte[] HASH_VAL_NULL_BYTE_BUF = new byte[4];

  private static final int HASH_VAL_EMPTY = 0x7dca7eee;
  private static final byte[] HASH_VAL_EMPTY_BYTE_BUF = new byte[4];

  static {
    HASH_VAL_NULL_BYTE_BUF[0] = (byte) (HASH_VAL_NULL >>> 0);
    HASH_VAL_NULL_BYTE_BUF[1] = (byte) (HASH_VAL_NULL >>> 8);
    HASH_VAL_NULL_BYTE_BUF[2] = (byte) (HASH_VAL_NULL >>> 16);
    HASH_VAL_NULL_BYTE_BUF[3] = (byte) (HASH_VAL_NULL >>> 24);

    HASH_VAL_EMPTY_BYTE_BUF[0] = (byte) (HASH_VAL_EMPTY >>> 0);
    HASH_VAL_EMPTY_BYTE_BUF[1] = (byte) (HASH_VAL_EMPTY >>> 8);
    HASH_VAL_EMPTY_BYTE_BUF[2] = (byte) (HASH_VAL_EMPTY >>> 16);
    HASH_VAL_EMPTY_BYTE_BUF[3] = (byte) (HASH_VAL_EMPTY >>> 24);
  }


  private HashUtil() {
  }


  public static long fastHash64(byte[] buf, long seed) {
    if (buf == null) {
      buf = HASH_VAL_NULL_BYTE_BUF;
    } else if (buf.length == 0) {
      buf = HASH_VAL_EMPTY_BYTE_BUF;
    }
    final int len = buf.length;
    final long m = 0x880355f21e6d1965L;
    long h = seed ^ (len * m);
    long v;

    int len8 = len / 8;
    for (int i = 0; i < len8; ++i) {
      int pos = i * 8;
      v = (buf[pos] & 0xFF) |
          ((long)(buf[pos + 1] & 0xFF) << 8) |  ((long)(buf[pos + 2] & 0xFF) << 16) |
          ((long)(buf[pos + 3] & 0xFF) << 24) | ((long)(buf[pos + 4] & 0xFF) << 32) |
          ((long)(buf[pos + 5] & 0xFF) << 40) | ((long)(buf[pos + 6] & 0xFF) << 48) |
          ((long)(buf[pos + 7] & 0xFF) << 56);
      h ^= fastHashMix(v);
      h *= m;
    }

    v = 0;
    int pos2 = len8 * 8;
    switch (len & 7) {
      case 7:
        v ^= (long)(buf[pos2 + 6] & 0xFF) << 48;
      case 6:
        v ^= (long)(buf[pos2 + 5] & 0xFF) << 40;
      case 5:
        v ^= (long)(buf[pos2 + 4] & 0xFF) << 32;
      case 4:
        v ^= (long)(buf[pos2 + 3] & 0xFF) << 24;
      case 3:
        v ^= (long)(buf[pos2 + 2] & 0xFF) << 16;
      case 2:
        v ^= (long)(buf[pos2 + 1] & 0xFF) << 8;
      case 1:
        v ^= (buf[pos2] & 0xFF);
        h ^= fastHashMix(v);
        h *= m;
    }

    return fastHashMix(h);
  }


  public static int fastHash32(byte[] buf, int seed) {
  long h = fastHash64(buf, seed);
    return (int)(h - (h >>> 32));
}

  private static long fastHashMix(long h) {
    h ^= h >>> 23;
    h *= 0x2127599bf4325c37L;
    h ^= h >>> 47;
    return h;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy