Use UnsignedLongSet instead of RangeSet in metadata
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / utils / ImmutableUnsignedLongSet.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, 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 java.io.DataInput;
12 import java.io.DataOutput;
13 import java.io.IOException;
14 import java.util.TreeSet;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.concepts.Immutable;
17 import org.opendaylight.yangtools.concepts.WritableObject;
18
19 @Beta
20 public final class ImmutableUnsignedLongSet extends UnsignedLongSet implements Immutable, WritableObject {
21     private static final @NonNull ImmutableUnsignedLongSet EMPTY = new ImmutableUnsignedLongSet(new TreeSet<>());
22
23     private ImmutableUnsignedLongSet(final TreeSet<Entry> ranges) {
24         super(ranges);
25     }
26
27     static @NonNull ImmutableUnsignedLongSet of(final TreeSet<Entry> ranges) {
28         return ranges.isEmpty() ? EMPTY : new ImmutableUnsignedLongSet(ranges);
29     }
30
31     public static @NonNull ImmutableUnsignedLongSet of() {
32         return EMPTY;
33     }
34
35     @Override
36     public ImmutableUnsignedLongSet immutableCopy() {
37         return this;
38     }
39
40     public static @NonNull ImmutableUnsignedLongSet readFrom(final DataInput in) throws IOException {
41         return readFrom(in, in.readInt());
42     }
43
44     public static @NonNull ImmutableUnsignedLongSet readFrom(final DataInput in, final int size) throws IOException {
45         if (size == 0) {
46             return EMPTY;
47         }
48
49         final var ranges = new TreeSet<Entry>();
50         for (int i = 0; i < size; ++i) {
51             ranges.add(Entry.readUnsigned(in));
52         }
53         return new ImmutableUnsignedLongSet(ranges);
54     }
55
56     @Override
57     public void writeTo(final DataOutput out) throws IOException {
58         out.writeInt(size());
59         writeRanges(out);
60     }
61
62     public void writeRangesTo(final @NonNull DataOutput out, final int size) throws IOException {
63         if (size != size()) {
64             throw new IOException("Mismatched size: expected " + size() + ", got " + size);
65         }
66         writeRanges(out);
67     }
68
69     private void writeRanges(final @NonNull DataOutput out) throws IOException {
70         for (var range : trustedRanges()) {
71             range.writeUnsigned(out);
72         }
73     }
74 }