2019-12-31 17:10:12 +01:00
|
|
|
package envoy.data;
|
|
|
|
|
2020-01-28 17:01:02 +01:00
|
|
|
import java.io.Serializable;
|
|
|
|
|
2019-12-31 17:10:12 +01:00
|
|
|
/**
|
|
|
|
* Generates increasing IDs between two numbers.<br>
|
|
|
|
* <br>
|
|
|
|
* Project: <strong>envoy-common</strong><br>
|
2020-01-28 17:01:02 +01:00
|
|
|
* File: <strong>IdGenerator.java</strong><br>
|
2019-12-31 17:10:12 +01:00
|
|
|
* Created: <strong>31.12.2019</strong><br>
|
2020-01-28 17:01:02 +01:00
|
|
|
*
|
2019-12-31 17:10:12 +01:00
|
|
|
* @author Kai S. K. Engelbart
|
|
|
|
* @since Envoy Common v0.2-alpha
|
|
|
|
*/
|
2020-01-28 17:01:02 +01:00
|
|
|
public class IdGenerator implements Serializable {
|
2019-12-31 17:10:12 +01:00
|
|
|
|
|
|
|
private final long end;
|
|
|
|
private long current;
|
|
|
|
|
2020-01-28 17:01:02 +01:00
|
|
|
private static final long serialVersionUID = -1517378307055845147L;
|
|
|
|
|
2019-12-31 17:10:12 +01:00
|
|
|
/**
|
2020-01-28 17:01:02 +01:00
|
|
|
* Creates an instance of {@link IdGenerator}.
|
2019-12-31 17:10:12 +01:00
|
|
|
*
|
|
|
|
* @param begin the first ID
|
2020-01-28 17:09:28 +01:00
|
|
|
* @param size the amount of IDs to provide
|
2019-12-31 17:10:45 +01:00
|
|
|
* @since Envoy Common v0.2-alpha
|
2019-12-31 17:10:12 +01:00
|
|
|
*/
|
2020-01-28 17:09:28 +01:00
|
|
|
public IdGenerator(long begin, long size) {
|
|
|
|
current = begin;
|
|
|
|
end = begin + size;
|
2019-12-31 17:10:12 +01:00
|
|
|
}
|
|
|
|
|
2020-01-28 17:01:02 +01:00
|
|
|
@Override
|
2020-01-28 19:58:23 +01:00
|
|
|
public String toString() { return String.format("IdGenerator[current=%d,end=%d]", current, end); }
|
2020-01-28 17:01:02 +01:00
|
|
|
|
2019-12-31 17:10:12 +01:00
|
|
|
/**
|
|
|
|
* @return {@code true} if there are unused IDs remaining
|
2019-12-31 17:10:45 +01:00
|
|
|
* @since Envoy Common v0.2-alpha
|
2019-12-31 17:10:12 +01:00
|
|
|
*/
|
|
|
|
public boolean hasNext() { return current < end; }
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return the next ID
|
2019-12-31 17:10:45 +01:00
|
|
|
* @since Envoy Common v0.2-alpha
|
2019-12-31 17:10:12 +01:00
|
|
|
*/
|
|
|
|
public long next() {
|
|
|
|
if (!hasNext()) throw new IllegalStateException("All IDs have been used");
|
|
|
|
return current++;
|
|
|
|
}
|
|
|
|
}
|