blob: ce418eaef64512812f43f3afcd621440127a89b3 [file] [log] [blame]
Brian O'Connor66630c82014-10-02 21:08:19 -07001package org.onlab.onos.net.intent.impl;
2
3import static com.google.common.base.Preconditions.checkArgument;
4
5import java.util.Objects;
6import java.util.concurrent.atomic.AtomicLong;
7
8import com.google.common.base.MoreObjects;
9
10/**
11 * A class representing an ID space.
12 */
13public final class IdBlock {
14 private final long start;
15 private final long size;
16
17 private final AtomicLong currentId;
18
19 /**
20 * Constructs a new ID block with the specified size and initial value.
21 *
22 * @param start initial value of the block
23 * @param size size of the block
24 * @throws IllegalArgumentException if the size is less than or equal to 0
25 */
26 public IdBlock(long start, long size) {
27 checkArgument(size > 0, "size should be more than 0, but %s", size);
28
29 this.start = start;
30 this.size = size;
31
32 this.currentId = new AtomicLong(start);
33 }
34
35 // TODO: consider if this method is needed or not
36 /**
37 * Returns the initial value.
38 *
39 * @return initial value
40 */
41 public long getStart() {
42 return start;
43 }
44
45 // TODO: consider if this method is needed or not
46 /**
47 * Returns the last value.
48 *
49 * @return last value
50 */
51 public long getEnd() {
52 return start + size - 1;
53 }
54
55 /**
56 * Returns the block size.
57 *
58 * @return block size
59 */
60 public long getSize() {
61 return size;
62 }
63
64 /**
65 * Returns the next ID in the block.
66 *
67 * @return next ID
68 * @throws UnavailableIdException if there is no available ID in the block.
69 */
70 public long getNextId() {
71 final long id = currentId.getAndIncrement();
72 if (id > getEnd()) {
73 throw new UnavailableIdException(String.format(
74 "used all IDs in allocated space (size: %d, end: %d, current: %d)",
75 size, getEnd(), id
76 ));
77 }
78
79 return id;
80 }
81
82 // TODO: Do we really need equals and hashCode? Should it contain currentId?
83 @Override
84 public boolean equals(Object o) {
85 if (this == o) {
86 return true;
87 }
88 if (o == null || getClass() != o.getClass()) {
89 return false;
90 }
91
92 IdBlock that = (IdBlock) o;
93 return Objects.equals(this.start, that.start)
94 && Objects.equals(this.size, that.size)
95 && Objects.equals(this.currentId.get(), that.currentId.get());
96 }
97
98 @Override
99 public int hashCode() {
100 return Objects.hash(start, size, currentId);
101 }
102
103 @Override
104 public String toString() {
105 return MoreObjects.toStringHelper(getClass())
106 .add("start", start)
107 .add("size", size)
108 .add("currentId", currentId)
109 .toString();
110 }
111}