BUG-7464: Add a dedicated ImmutableEntrySet
[yangtools.git] / third-party / triemap / src / main / java / org / opendaylight / yangtools / triemap / TrieMap.java
1 /*
2  * (C) Copyright 2016 Pantheon Technologies, s.r.o. and others.
3  *
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  */
16 package org.opendaylight.yangtools.triemap;
17
18 import static com.google.common.base.Preconditions.checkNotNull;
19 import static org.opendaylight.yangtools.triemap.LookupResult.RESTART;
20
21 import com.google.common.annotations.Beta;
22 import java.io.ObjectStreamException;
23 import java.io.Serializable;
24 import java.util.AbstractMap;
25 import java.util.Iterator;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentMap;
29
30 /***
31  * This is a port of Scala's TrieMap class from the Scala Collections library. This implementation does not support
32  * null keys nor null values.
33  *
34  * @author Aleksandar Prokopec (original Scala implementation)
35  * @author Roman Levenstein (original Java 6 port)
36  * @author Robert Varga
37  *
38  * @param <K> the type of keys maintained by this map
39  * @param <V> the type of mapped values
40  */
41 @Beta
42 public abstract class TrieMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K,V>, Serializable {
43     private static final long serialVersionUID = 1L;
44
45     private final Equivalence<? super K> equiv;
46
47     private AbstractEntrySet<K, V> entrySet;
48
49     TrieMap(final Equivalence<? super K> equiv) {
50         this.equiv = equiv;
51     }
52
53     public static <K, V> TrieMap<K, V> create() {
54         return new MutableTrieMap<>(Equivalence.equals());
55     }
56
57     /**
58      * Returns a snapshot of this TrieMap. This operation is lock-free and
59      * linearizable.
60      *
61      * The snapshot is lazily updated - the first time some branch in the
62      * snapshot or this TrieMap are accessed, they are rewritten. This means
63      * that the work of rebuilding both the snapshot and this TrieMap is
64      * distributed across all the threads doing updates or accesses subsequent
65      * to the snapshot creation.
66      */
67     public abstract TrieMap<K, V> mutableSnapshot();
68
69     /**
70      * Returns a read-only snapshot of this TrieMap. This operation is lock-free
71      * and linearizable.
72      *
73      * The snapshot is lazily updated - the first time some branch of this
74      * TrieMap are accessed, it is rewritten. The work of creating the snapshot
75      * is thus distributed across subsequent updates and accesses on this
76      * TrieMap by all threads. Note that the snapshot itself is never rewritten
77      * unlike when calling the `snapshot` method, but the obtained snapshot
78      * cannot be modified.
79      *
80      * This method is used by other methods such as `size` and `iterator`.
81      */
82     public abstract ImmutableTrieMap<K, V> immutableSnapshot();
83
84     @Override
85     public final boolean containsKey(final Object key) {
86         return get(key) != null;
87     }
88
89     @Override
90     public final boolean containsValue(final Object value) {
91         return super.containsValue(checkNotNull(value));
92     }
93
94     @Override
95     public final Set<Entry<K, V>> entrySet() {
96         AbstractEntrySet<K, V> ret = entrySet;
97         if (ret == null) {
98             entrySet = ret = createEntrySet();
99         }
100         return ret;
101     }
102
103     @Override
104     public final V get(final Object key) {
105         @SuppressWarnings("unchecked")
106         final K k = (K) checkNotNull(key);
107         return lookuphc(k, computeHash(k));
108     }
109
110     @Override
111     public abstract void clear();
112
113     @Override
114     public abstract V put(K key, V value);
115
116     @Override
117     public abstract V putIfAbsent(K key, V value);
118
119     @Override
120     public abstract V remove(Object key);
121
122     @Override
123     public abstract boolean remove(Object key, Object value);
124
125     @Override
126     public abstract boolean replace(K key, V oldValue, V newValue);
127
128     @Override
129     public abstract V replace(K key, V value);
130
131     @Override
132     public abstract int size();
133
134     /* internal methods implemented by subclasses */
135
136     abstract AbstractEntrySet<K, V> createEntrySet();
137
138     abstract boolean isReadOnly();
139
140     abstract INode<K, V> RDCSS_READ_ROOT(boolean abort);
141
142     /**
143      * Return an iterator over a TrieMap.
144      *
145      * If this is a read-only snapshot, it would return a read-only iterator.
146      *
147      * If it is the original TrieMap or a non-readonly snapshot, it would return
148      * an iterator that would allow for updates.
149      *
150      * @return
151      */
152     abstract Iterator<Entry<K, V>> iterator();
153
154     /* internal methods provided for subclasses */
155
156     /**
157      * Return an iterator over a TrieMap.
158      * This is a read-only iterator.
159      *
160      * @return
161      */
162     final Iterator<Entry<K, V>> immutableIterator() {
163         return new TrieMapReadOnlyIterator<>(0, immutableSnapshot());
164     }
165
166     @SuppressWarnings("null")
167     static <V> V toNullable(final Optional<V> opt) {
168         return opt.orElse(null);
169     }
170
171     final int computeHash(final K k) {
172         return equiv.hash(k);
173     }
174
175     final Object writeReplace() throws ObjectStreamException {
176         return new SerializationProxy(immutableSnapshot(), isReadOnly());
177     }
178
179     /* package-protected utility methods */
180
181     final Equivalence<? super K> equiv() {
182         return equiv;
183     }
184
185     final INode<K, V> readRoot() {
186         return RDCSS_READ_ROOT(false);
187     }
188
189     // FIXME: abort = false by default
190     final INode<K, V> readRoot(final boolean abort) {
191         return RDCSS_READ_ROOT(abort);
192     }
193
194     final INode<K, V> RDCSS_READ_ROOT() {
195         return RDCSS_READ_ROOT(false);
196     }
197
198     final boolean equal(final K k1, final K k2) {
199         return equiv.equivalent(k1, k2);
200     }
201
202     /* private implementation methods */
203
204     @SuppressWarnings("unchecked")
205     private V lookuphc(final K k, final int hc) {
206         Object res;
207         do {
208             // Keep looping as long as RESTART is being indicated
209             res = RDCSS_READ_ROOT().rec_lookup(k, hc, 0, null, this);
210         } while (res == RESTART);
211
212         return (V) res;
213     }
214 }