package com.railway.common.utils.snowflake;

import java.util.Random;

/**
 * 算法工具类
 *
 * @author ZhaoMn
 */
public class SnowflakeIdUtils {


  private static final Random RANDOM = new Random();

  public static long nextLong(final long startInclusive, final long endExclusive) {
    isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value.");
    isTrue(startInclusive >= 0, "Both range values must be non-negative.");

    if (startInclusive == endExclusive) {
      return startInclusive;
    }
    return (long) nextDouble(startInclusive, endExclusive);
  }

  public static void isTrue(final boolean expression, final String message,
      final Object... values) {
    if (!expression) {
      throw new IllegalArgumentException(String.format(message, values));
    }
  }

  public static double nextDouble(final double startInclusive, final double endInclusive) {
    isTrue(endInclusive >= startInclusive, "Start value must be smaller or equal to end value.");
    isTrue(startInclusive >= 0, "Both range values must be non-negative.");

    // 指定一个误差范围
    float diff = 1e-6f;
    // 两个浮点数的差值在此范围之内，则认为是相等的
    if (Math.abs(startInclusive - endInclusive) < diff) {
      return startInclusive;
    }

    return startInclusive + ((endInclusive - startInclusive) * RANDOM.nextDouble());
  }


}
