Brian O'Connor | 520c052 | 2014-11-23 23:50:47 -0800 | [diff] [blame^] | 1 | package org.onlab.onos.core; |
| 2 | |
| 3 | import com.google.common.base.MoreObjects; |
| 4 | |
| 5 | import java.util.concurrent.atomic.AtomicLong; |
| 6 | |
| 7 | import static com.google.common.base.Preconditions.checkArgument; |
| 8 | |
| 9 | /** |
| 10 | * A class representing an ID space. |
| 11 | */ |
| 12 | public final class IdBlock { |
| 13 | private final long start; |
| 14 | private final long size; |
| 15 | |
| 16 | private final AtomicLong currentId; |
| 17 | |
| 18 | /** |
| 19 | * Constructs a new ID block with the specified size and initial value. |
| 20 | * |
| 21 | * @param start initial value of the block |
| 22 | * @param size size of the block |
| 23 | * @throws IllegalArgumentException if the size is less than or equal to 0 |
| 24 | */ |
| 25 | public IdBlock(long start, long size) { |
| 26 | checkArgument(size > 0, "size should be more than 0, but %s", size); |
| 27 | |
| 28 | this.start = start; |
| 29 | this.size = size; |
| 30 | |
| 31 | this.currentId = new AtomicLong(start); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Returns the initial value. |
| 36 | * |
| 37 | * @return initial value |
| 38 | */ |
| 39 | private long getStart() { |
| 40 | return start; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Returns the last value. |
| 45 | * |
| 46 | * @return last value |
| 47 | */ |
| 48 | private long getEnd() { |
| 49 | return start + size - 1; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Returns the block size. |
| 54 | * |
| 55 | * @return block size |
| 56 | */ |
| 57 | public long getSize() { |
| 58 | return size; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Returns the next ID in the block. |
| 63 | * |
| 64 | * @return next ID |
| 65 | * @throws UnavailableIdException if there is no available ID in the block. |
| 66 | */ |
| 67 | public long getNextId() { |
| 68 | final long id = currentId.getAndIncrement(); |
| 69 | if (id > getEnd()) { |
| 70 | throw new UnavailableIdException(String.format( |
| 71 | "used all IDs in allocated space (size: %d, end: %d, current: %d)", |
| 72 | size, getEnd(), id |
| 73 | )); |
| 74 | } |
| 75 | |
| 76 | return id; |
| 77 | } |
| 78 | |
| 79 | @Override |
| 80 | public String toString() { |
| 81 | return MoreObjects.toStringHelper(getClass()) |
| 82 | .add("start", start) |
| 83 | .add("size", size) |
| 84 | .add("currentId", currentId) |
| 85 | .toString(); |
| 86 | } |
| 87 | } |