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