package org.opencloudb.route.function;

import org.opencloudb.config.model.rule.RuleAlgorithm;

/**
 * 跳增一致性哈希分片
 * 思想源自Google公开论文，比传统一致性哈希更省资源速度更快数据迁移量更少
 *
 * @author XiaoSK
 */
public final class PartitionByJumpConsistentHash extends AbstractPartitionAlgorithm
        implements RuleAlgorithm  {

    private static final long UNSIGNED_MASK = 0x7fffffffffffffffL;
    private static final long JUMP = 1L << 31;
    private static final long CONSTANT = Long.parseUnsignedLong("2862933555777941757");

    private int totalBuckets;

    @Override
    public Integer calculate(String columnValue) {
        return jumpConsistentHash(columnValue.hashCode(), totalBuckets);
    }

    public static int jumpConsistentHash(final long key, final int buckets) {
        checkBuckets(buckets);
        long k = key;
        long b = -1;
        long j = 0;

        while (j < buckets) {
            b = j;
            k = k * CONSTANT + 1L;

            j = (long) ((b + 1L) * (JUMP / toDouble((k >>> 33) + 1L)));
        }
        return (int) b;
    }

    private static void checkBuckets(final int buckets) {
        if (buckets < 0) {
            throw new IllegalArgumentException("Buckets cannot be less than 0");
        }
    }

    private static double toDouble(final long n) {
        double d = n & UNSIGNED_MASK;
        if (n < 0) {
            d += 0x1.0p63;
        }
        return d;
    }

    public void setTotalBuckets(int totalBuckets) {
        this.totalBuckets = totalBuckets;
    }

    public int getTotalBuckets() {
        return totalBuckets;
    }
}

@@ -107,10 +107,10 @@
 %E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C
-%E5%88%86%E7%89%87
+%E7%AE%97%E6%B3%95
 %0A * 
@@ -416,89 +416,116 @@
     
-private static final long CONSTANT = Long.parseUnsignedLong(%222862933555777941757%22
+// If JDK %3E 1.8, Just use Long.parseUnsignedLong instead.%0A    private static final long CONSTANT = generate(
 );%0A%0A
@@ -1418,32 +1418,300 @@
 eturn d;%0A    %7D%0A%0A
+    public static long generate() %7B%0A        String s = %222862933555777941757%22;%0A        long first = Long.parseLong(s.substring(0, 18), 10);%0A        int second = Character.digit(s.charAt(18), 10);%0A        long result = first * 10 + second;%0A        return result;%0A    %7D%0A%0A
     public void 

Downgrade JDK from 8 to 7