SerialNumber implements Comparable<SerialNumber> { public boolean isBefore(SerialNumber that) { long i1 = Integer.toUnsignedLong(this.value); long i2 = Integer.toUnsignedLong(that.value); return (this.value != that.value && ( i1 < i2 && (i2 - i1) < HALF_SERIAL_NUMBER_RANGE || i1 > i2 && (i1 - i2) > HALF_SERIAL_NUMBER_RANGE )); }  static SerialNumber zero(); SerialNumber next(); SerialNumber previous(); boolean isBefore(SerialNumber that); boolean isAfter(SerialNumber that); @Override int compareTo(SerialNumber that); static final int SERIAL_BITS; static final long HALF_SERIAL_NUMBER_RANGE; }
@Test public void should_be_before_not_after() { assertThat(SerialNumber.of(0).isBefore(SerialNumber.of(0))).isFalse(); assertThat(SerialNumber.of(Integer.MAX_VALUE).isBefore(SerialNumber.of(Integer.MAX_VALUE))).isFalse(); assertBefore(SerialNumber.of(0), SerialNumber.of(1)); assertBefore(SerialNumber.of(Integer.MAX_VALUE - 1), SerialNumber.of(Integer.MAX_VALUE)); assertBefore(SerialNumber.of(Integer.MIN_VALUE - 1), SerialNumber.of(Integer.MIN_VALUE)); for (int i = 0; i < 1000; ++i) { int n = RANDOM.nextInt(); assertThat(SerialNumber.of(n).isBefore(SerialNumber.of(n))).isFalse(); assertBefore(SerialNumber.of(n), SerialNumber.of(n + 1)); assertBefore(SerialNumber.of(n - 1), SerialNumber.of(n)); assertBefore(SerialNumber.of(n), SerialNumber.of(n + Integer.MAX_VALUE)); int d = 1 + RANDOM.nextInt((int) (SerialNumber.HALF_SERIAL_NUMBER_RANGE - 1)); assertBefore(SerialNumber.of(n - d), SerialNumber.of(n)); assertBefore(SerialNumber.of(n), SerialNumber.of(n + d)); } }