BUG-8676: add UnsignedLongRangeSet
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / utils / UnsignedLongRangeSet.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore.utils;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableRangeSet;
13 import com.google.common.collect.Range;
14 import com.google.common.collect.RangeSet;
15 import com.google.common.collect.TreeRangeSet;
16 import com.google.common.primitives.UnsignedLong;
17 import org.opendaylight.yangtools.concepts.Mutable;
18
19 /**
20  * Utility {@link RangeSet}-like class, specialized for holding {@link UnsignedLong}. It does not directly implement
21  * the {@link RangeSet} interface, but allows converting to and from it. Internal implementation takes advantage of
22  * knowing that {@link UnsignedLong} is a discrete type and that it can be stored in a long.
23  *
24  * @author Robert Varga
25  */
26 @Beta
27 public final class UnsignedLongRangeSet implements Mutable {
28     // FIXME: this is just to get us started
29     private final RangeSet<UnsignedLong> rangeset;
30
31     private UnsignedLongRangeSet(final RangeSet<UnsignedLong> rangeset) {
32         this.rangeset = Preconditions.checkNotNull(rangeset);
33     }
34
35     public static UnsignedLongRangeSet create() {
36         return new UnsignedLongRangeSet(TreeRangeSet.create());
37     }
38
39     public static UnsignedLongRangeSet create(final RangeSet<UnsignedLong> input) {
40         return new UnsignedLongRangeSet(TreeRangeSet.create(input));
41     }
42
43     public RangeSet<UnsignedLong> toImmutable() {
44         return ImmutableRangeSet.copyOf(rangeset);
45     }
46
47     public void add(final long longBits) {
48         add(UnsignedLong.fromLongBits(longBits));
49     }
50
51     public void add(final UnsignedLong value) {
52         rangeset.add(Range.closedOpen(value, UnsignedLong.ONE.plus(value)));
53     }
54
55     public boolean contains(final UnsignedLong value) {
56         return rangeset.contains(value);
57     }
58
59     public boolean contains(final long longBits) {
60         return contains(UnsignedLong.fromLongBits(longBits));
61     }
62
63     public UnsignedLongRangeSet copy() {
64         return new UnsignedLongRangeSet(TreeRangeSet.create(rangeset));
65     }
66 }