blob: 6788b082eaf196261de7d829d5607530faf5466d [file] [log] [blame]
alshabibab984662014-12-04 18:56:18 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
alshabibab984662014-12-04 18:56:18 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.core;
Brian O'Connor520c0522014-11-23 23:50:47 -080017
18import com.google.common.base.MoreObjects;
19
20import java.util.concurrent.atomic.AtomicLong;
21
22import static com.google.common.base.Preconditions.checkArgument;
23
24/**
25 * A class representing an ID space.
26 */
27public final class IdBlock {
28 private final long start;
29 private final long size;
30
31 private final AtomicLong currentId;
32
33 /**
34 * Constructs a new ID block with the specified size and initial value.
35 *
36 * @param start initial value of the block
37 * @param size size of the block
38 * @throws IllegalArgumentException if the size is less than or equal to 0
39 */
40 public IdBlock(long start, long size) {
41 checkArgument(size > 0, "size should be more than 0, but %s", size);
42
43 this.start = start;
44 this.size = size;
45
46 this.currentId = new AtomicLong(start);
47 }
48
49 /**
50 * Returns the initial value.
51 *
52 * @return initial value
53 */
54 private long getStart() {
55 return start;
56 }
57
58 /**
59 * Returns the last value.
60 *
61 * @return last value
62 */
63 private long getEnd() {
64 return start + size - 1;
65 }
66
67 /**
68 * Returns the block size.
69 *
70 * @return block size
71 */
72 public long getSize() {
73 return size;
74 }
75
76 /**
77 * Returns the next ID in the block.
78 *
79 * @return next ID
80 * @throws UnavailableIdException if there is no available ID in the block.
81 */
82 public long getNextId() {
83 final long id = currentId.getAndIncrement();
84 if (id > getEnd()) {
85 throw new UnavailableIdException(String.format(
86 "used all IDs in allocated space (size: %d, end: %d, current: %d)",
87 size, getEnd(), id
88 ));
89 }
90
91 return id;
92 }
93
94 @Override
95 public String toString() {
96 return MoreObjects.toStringHelper(getClass())
97 .add("start", start)
98 .add("size", size)
99 .add("currentId", currentId)
100 .toString();
101 }
102}