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
|
|
|
/**
|
2020-09-25 14:29:23 +02:00
|
|
|
* Generates increasing IDs between two numbers.
|
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
|
|
|
|
*/
|
2021-02-19 11:09:07 +01:00
|
|
|
public final class IDGenerator implements Serializable {
|
2019-12-31 17:10:12 +01:00
|
|
|
|
|
|
|
private final long end;
|
|
|
|
private long current;
|
|
|
|
|
2020-03-24 19:06:56 +01:00
|
|
|
private static final long serialVersionUID = 0L;
|
2020-01-28 17:01:02 +01:00
|
|
|
|
2019-12-31 17:10:12 +01:00
|
|
|
/**
|
2020-03-24 19:06:56 +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-03-24 19:06:56 +01:00
|
|
|
public IDGenerator(long begin, long size) {
|
2020-01-28 17:09:28 +01:00
|
|
|
current = begin;
|
|
|
|
end = begin + size;
|
2019-12-31 17:10:12 +01:00
|
|
|
}
|
|
|
|
|
2020-01-28 17:01:02 +01:00
|
|
|
@Override
|
2020-10-19 18:17:51 +02: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
|
|
|
*/
|
2020-10-19 18:17:51 +02:00
|
|
|
public boolean hasNext() {
|
|
|
|
return current < end;
|
|
|
|
}
|
2019-12-31 17:10:12 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @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() {
|
2020-10-19 18:17:51 +02:00
|
|
|
if (!hasNext())
|
|
|
|
throw new IllegalStateException("All IDs have been used");
|
2019-12-31 17:10:12 +01:00
|
|
|
return current++;
|
|
|
|
}
|
|
|
|
}
|