2 * (C) Copyright 2016 Pantheon Technologies, s.r.o. and others.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.opendaylight.yangtools.triemap;
18 import static org.opendaylight.yangtools.triemap.LookupResult.RESTART;
19 import static org.opendaylight.yangtools.triemap.PresencePredicate.ABSENT;
20 import static org.opendaylight.yangtools.triemap.PresencePredicate.PRESENT;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
23 import java.util.Optional;
24 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
26 final class INode<K, V> extends BasicNode {
27 @SuppressWarnings("rawtypes")
28 private static final AtomicReferenceFieldUpdater<INode, MainNode> MAINNODE_UPDATER =
29 AtomicReferenceFieldUpdater.newUpdater(INode.class, MainNode.class, "mainnode");
31 private final Gen gen;
33 private volatile MainNode<K, V> mainnode;
35 INode(final Gen gen, final MainNode<K, V> mainnode) {
37 this.mainnode = mainnode;
40 MainNode<K, V> gcasRead(final TrieMap<?, ?> ct) {
44 private MainNode<K, V> GCAS_READ(final TrieMap<?, ?> ct) {
45 MainNode<K, V> m = /* READ */ mainnode;
46 MainNode<K, V> prevval = /* READ */ m.READ_PREV();
47 if (prevval == null) {
51 return GCAS_Complete(m, ct);
54 private MainNode<K, V> GCAS_Complete(MainNode<K, V> m, final TrieMap<?, ?> ct) {
61 final MainNode<K, V> prev = /* READ */ m.READ_PREV();
62 final Gen rdgen = ct.readRoot(true).gen;
67 if (prev instanceof FailedNode) {
68 // try to commit to previous value
69 FailedNode<K, V> fn = (FailedNode<K, V>) prev;
70 if (MAINNODE_UPDATER.compareAndSet(this, m, fn.READ_PREV())) {
71 return fn.READ_PREV();
74 // Tail recursion: return GCAS_Complete (/* READ */ mainnode, ct);
75 m = /* READ */ mainnode;
79 // Assume that you've read the root from the generation G.
80 // Assume that the snapshot algorithm is correct.
81 // ==> you can only reach nodes in generations <= G.
83 // We know that `ctr.gen` is >= G.
84 // ==> if `ctr.gen` = `gen` then they are both equal to G.
85 // ==> otherwise, we know that either `ctr.gen` > G, `gen` < G,
87 if (rdgen == gen && !ct.isReadOnly()) {
89 if (m.CAS_PREV(prev, null)) {
93 // Tail recursion: return GCAS_Complete (m, ct);
98 m.CAS_PREV(prev, new FailedNode<>(prev));
100 // Tail recursion: return GCAS_Complete(/* READ */ mainnode, ct);
101 m = /* READ */ mainnode;
105 private boolean GCAS(final MainNode<K, V> old, final MainNode<K, V> n, final TrieMap<?, ?> ct) {
107 if (MAINNODE_UPDATER.compareAndSet(this, old, n)) {
108 GCAS_Complete(n, ct);
109 return /* READ */ n.READ_PREV() == null;
115 private INode<K, V> inode(final MainNode<K, V> cn) {
116 return new INode<>(gen, cn);
119 INode<K, V> copyToGen(final Gen ngen, final TrieMap<?, ?> ct) {
120 return new INode<>(ngen, GCAS_READ(ct));
124 * Inserts a key value pair, overwriting the old pair if the keys match.
126 * @return true if successful, false otherwise
128 boolean rec_insert(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
129 final TrieMap<K, V> ct) {
130 return rec_insert(k, v, hc, lev, parent, gen, ct);
133 private boolean rec_insert(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
134 final Gen startgen, final TrieMap<K, V> ct) {
136 final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
138 if (m instanceof CNode) {
139 // 1) a multiway node
140 final CNode<K, V> cn = (CNode<K, V>) m;
141 final int idx = (hc >>> lev) & 0x1f;
142 final int flag = 1 << idx;
143 final int bmp = cn.bitmap;
144 final int mask = flag - 1;
145 final int pos = Integer.bitCount(bmp & mask);
147 if ((bmp & flag) != 0) {
149 final BasicNode cnAtPos = cn.array[pos];
150 if (cnAtPos instanceof INode) {
151 final INode<K, V> in = (INode<K, V>) cnAtPos;
152 if (startgen == in.gen) {
153 return in.rec_insert(k, v, hc, lev + 5, this, startgen, ct);
155 if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
156 // Tail recursion: return rec_insert (k, v, hc, lev, parent, startgen, ct);
161 } else if (cnAtPos instanceof SNode) {
162 final SNode<K, V> sn = (SNode<K, V>) cnAtPos;
163 if (sn.hc == hc && ct.equal(sn.k, k)) {
164 return GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct);
167 final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
168 final MainNode<K, V> nn = rn.updatedAt(pos, inode(CNode.dual(sn, k, v, hc, lev + 5, gen)), gen);
169 return GCAS (cn, nn, ct);
172 final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
173 final MainNode<K, V> ncnode = rn.insertedAt(pos, flag, new SNode<>(k, v, hc), gen);
174 return GCAS (cn, ncnode, ct);
176 } else if (m instanceof TNode) {
177 clean(parent, ct, lev - 5);
179 } else if (m instanceof LNode) {
180 final LNode<K, V> ln = (LNode<K, V>) m;
181 final LNodeEntry<K, V> entry = ln.get(ct.equiv(), k);
182 return entry != null ? replaceln(ln, entry, v, ct) : insertln(ln, k, v, ct);
184 throw new IllegalStateException("Unhandled node " + m);
187 throw new RuntimeException ("Should not happen");
192 * Inserts a new key value pair, given that a specific condition is met.
195 * null - don't care if the key was there
196 * KEY_ABSENT - key wasn't there
197 * KEY_PRESENT - key was there
198 * other value `v` - key must be bound to `v`
199 * @return null if unsuccessful, Option[V] otherwise (indicating
200 * previous value bound to the key)
202 Optional<V> rec_insertif(final K k, final V v, final int hc, final Object cond, final int lev,
203 final INode<K, V> parent, final TrieMap<K, V> ct) {
204 return rec_insertif(k, v, hc, cond, lev, parent, gen, ct);
207 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
208 justification = "Returning null Optional indicates the need to restart.")
209 private Optional<V> insertDual(final TrieMap<K, V> ct, final CNode<K, V> cn, final int pos, final SNode<K, V> sn,
210 final K k, final V v, final int hc, final int lev) {
211 final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
212 final MainNode<K, V> nn = rn.updatedAt(pos, inode(CNode.dual(sn, k, v, hc, lev + 5, gen)), gen);
213 return GCAS(cn, nn, ct) ? Optional.empty() : null;
216 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
217 justification = "Returning null Optional indicates the need to restart.")
218 private Optional<V> rec_insertif(final K k, final V v, final int hc, final Object cond, final int lev,
219 final INode<K, V> parent, final Gen startgen, final TrieMap<K, V> ct) {
221 final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
223 if (m instanceof CNode) {
224 // 1) a multiway node
225 final CNode<K, V> cn = (CNode<K, V>) m;
226 final int idx = (hc >>> lev) & 0x1f;
227 final int flag = 1 << idx;
228 final int bmp = cn.bitmap;
229 final int mask = flag - 1;
230 final int pos = Integer.bitCount(bmp & mask);
232 if ((bmp & flag) != 0) {
234 final BasicNode cnAtPos = cn.array[pos];
235 if (cnAtPos instanceof INode) {
236 final INode<K, V> in = (INode<K, V>) cnAtPos;
237 if (startgen == in.gen) {
238 return in.rec_insertif(k, v, hc, cond, lev + 5, this, startgen, ct);
241 if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
242 // Tail recursion: return rec_insertif (k, v, hc, cond, lev, parent, startgen, ct);
247 } else if (cnAtPos instanceof SNode) {
248 final SNode<K, V> sn = (SNode<K, V>) cnAtPos;
250 if (sn.hc == hc && ct.equal(sn.k, k)) {
251 if (GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct)) {
252 return Optional.of(sn.v);
258 return insertDual(ct, cn, pos, sn, k, v, hc, lev);
259 } else if (cond == ABSENT) {
260 if (sn.hc == hc && ct.equal(sn.k, k)) {
261 return Optional.of(sn.v);
264 return insertDual(ct, cn, pos, sn, k, v, hc, lev);
265 } else if (cond == PRESENT) {
266 if (sn.hc == hc && ct.equal(sn.k, k)) {
267 if (GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct)) {
268 return Optional.of(sn.v);
273 return Optional.empty();
275 if (sn.hc == hc && ct.equal(sn.k, k) && cond.equals(sn.v)) {
276 if (GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct)) {
277 return Optional.of(sn.v);
283 return Optional.empty();
286 } else if (cond == null || cond == ABSENT) {
287 final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
288 final CNode<K, V> ncnode = rn.insertedAt (pos, flag, new SNode<>(k, v, hc), gen);
289 if (GCAS(cn, ncnode, ct)) {
290 return Optional.empty();
295 return Optional.empty();
297 } else if (m instanceof TNode) {
298 clean(parent, ct, lev - 5);
300 } else if (m instanceof LNode) {
302 final LNode<K, V> ln = (LNode<K, V>) m;
303 final LNodeEntry<K, V> entry = ln.get(ct.equiv(), k);
307 return replaceln(ln, entry, v, ct) ? Optional.of(entry.getValue()) : null;
310 return insertln(ln, k, v, ct) ? Optional.empty() : null;
311 } else if (cond == ABSENT) {
313 return Optional.of(entry.getValue());
316 return insertln(ln, k, v, ct) ? Optional.empty() : null;
317 } else if (cond == PRESENT) {
319 return Optional.empty();
322 return replaceln(ln, entry, v, ct) ? Optional.of(entry.getValue()) : null;
324 if (entry == null || !cond.equals(entry.getValue())) {
325 return Optional.empty();
328 return replaceln(ln, entry, v, ct) ? Optional.of(entry.getValue()) : null;
331 throw new IllegalStateException("Unhandled node " + m);
334 throw new RuntimeException("Should never happen");
338 private boolean insertln(final LNode<K, V> ln, final K k, final V v, final TrieMap<K, V> ct) {
339 return GCAS(ln, ln.insertChild(k, v), ct);
342 private boolean replaceln(final LNode<K, V> ln, final LNodeEntry<K, V> entry, final V v, final TrieMap<K, V> ct) {
343 return GCAS(ln, ln.replaceChild(entry, v), ct);
347 * Looks up the value associated with the key.
349 * @return null if no value has been found, RESTART if the operation
350 * wasn't successful, or any other value otherwise
352 Object rec_lookup(final K k, final int hc, final int lev, final INode<K, V> parent, final TrieMap<K, V> ct) {
353 return rec_lookup(k, hc, lev, parent, gen, ct);
356 private Object rec_lookup(final K k, final int hc, final int lev, final INode<K, V> parent, final Gen startgen,
357 final TrieMap<K, V> ct) {
359 final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
361 if (m instanceof CNode) {
363 final CNode<K, V> cn = (CNode<K, V>) m;
364 final int idx = (hc >>> lev) & 0x1f;
365 final int flag = 1 << idx;
366 final int bmp = cn.bitmap;
368 if ((bmp & flag) == 0) {
369 // 1a) bitmap shows no binding
373 // 1b) bitmap contains a value - descend
374 final int pos = (bmp == 0xffffffff) ? idx : Integer.bitCount(bmp & (flag - 1));
375 final BasicNode sub = cn.array[pos];
376 if (sub instanceof INode) {
377 final INode<K, V> in = (INode<K, V>) sub;
378 if (ct.isReadOnly() || (startgen == in.gen)) {
379 return in.rec_lookup(k, hc, lev + 5, this, startgen, ct);
382 if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
383 // Tail recursion: return rec_lookup(k, hc, lev, parent, startgen, ct);
388 } else if (sub instanceof SNode) {
390 final SNode<K, V> sn = (SNode<K, V>) sub;
391 if (sn.hc == hc && ct.equal(sn.k, k)) {
397 } else if (m instanceof TNode) {
399 return cleanReadOnly((TNode<K, V>) m, lev, parent, ct, k, hc);
400 } else if (m instanceof LNode) {
402 final LNodeEntry<K, V> entry = ((LNode<K, V>) m).get(ct.equiv(), k);
403 return entry != null ? entry.getValue() : null;
405 throw new IllegalStateException("Unhandled node " + m);
408 throw new RuntimeException ("Should not happen");
412 private Object cleanReadOnly(final TNode<K, V> tn, final int lev, final INode<K, V> parent,
413 final TrieMap<K, V> ct, final K k, final int hc) {
414 if (ct.isReadOnly()) {
415 if (tn.hc == hc && ct.equal(tn.k, k)) {
422 clean(parent, ct, lev - 5);
427 * Removes the key associated with the given value.
430 * if null, will remove the key regardless of the value;
431 * otherwise removes only if binding contains that exact key
433 * @return null if not successful, an Optional indicating the previous
436 Optional<V> rec_remove(final K k, final Object cond, final int hc, final int lev, final INode<K, V> parent,
437 final TrieMap<K, V> ct) {
438 return rec_remove(k, cond, hc, lev, parent, gen, ct);
441 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
442 justification = "Returning null Optional indicates the need to restart.")
443 private Optional<V> rec_remove(final K k, final Object cond, final int hc, final int lev, final INode<K, V> parent,
444 final Gen startgen, final TrieMap<K, V> ct) {
445 final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
447 if (m instanceof CNode) {
448 final CNode<K, V> cn = (CNode<K, V>) m;
449 final int idx = (hc >>> lev) & 0x1f;
450 final int bmp = cn.bitmap;
451 final int flag = 1 << idx;
452 if ((bmp & flag) == 0) {
453 return Optional.empty();
456 final int pos = Integer.bitCount(bmp & (flag - 1));
457 final BasicNode sub = cn.array[pos];
458 Optional<V> res = null;
459 if (sub instanceof INode) {
460 final INode<K, V> in = (INode<K, V>) sub;
461 if (startgen == in.gen) {
462 res = in.rec_remove(k, cond, hc, lev + 5, this, startgen, ct);
464 if (GCAS(cn, cn.renewed (startgen, ct), ct)) {
465 res = rec_remove(k, cond, hc, lev, parent, startgen, ct);
471 } else if (sub instanceof SNode) {
472 final SNode<K, V> sn = (SNode<K, V>) sub;
473 if (sn.hc == hc && ct.equal(sn.k, k) && (cond == null || cond.equals(sn.v))) {
474 final MainNode<K, V> ncn = cn.removedAt(pos, flag, gen).toContracted(lev);
475 if (GCAS(cn, ncn, ct)) {
476 res = Optional.of(sn.v);
481 res = Optional.empty();
485 if (res == null || !res.isPresent()) {
489 if (parent != null) {
490 // never tomb at root
491 final MainNode<K, V> n = GCAS_READ(ct);
492 if (n instanceof TNode) {
493 cleanParent(n, parent, ct, hc, lev, startgen);
498 } else if (m instanceof TNode) {
499 clean(parent, ct, lev - 5);
501 } else if (m instanceof LNode) {
502 final LNode<K, V> ln = (LNode<K, V>) m;
503 final LNodeEntry<K, V> entry = ln.get(ct.equiv(), k);
505 // Key was not found, hence no modification is needed
506 return Optional.empty();
509 final V value = entry.getValue();
510 if (cond != null && !cond.equals(value)) {
511 // Value does not match
512 return Optional.empty();
515 return GCAS(ln, ln.removeChild(entry, hc), ct) ? Optional.of(value) : null;
517 throw new IllegalStateException("Unhandled node " + m);
521 private void cleanParent(final Object nonlive, final INode<K, V> parent, final TrieMap<K, V> ct, final int hc,
522 final int lev, final Gen startgen) {
524 final MainNode<K, V> pm = parent.GCAS_READ(ct);
525 if ((!(pm instanceof CNode))) {
526 // parent is no longer a cnode, we're done
530 final CNode<K, V> cn = (CNode<K, V>) pm;
531 final int idx = (hc >>> (lev - 5)) & 0x1f;
532 final int bmp = cn.bitmap;
533 final int flag = 1 << idx;
534 if ((bmp & flag) == 0) {
535 // somebody already removed this i-node, we're done
539 final int pos = Integer.bitCount(bmp & (flag - 1));
540 final BasicNode sub = cn.array[pos];
542 if (nonlive instanceof TNode) {
543 final TNode<?, ?> tn = (TNode<?, ?>) nonlive;
544 final MainNode<K, V> ncn = cn.updatedAt(pos, tn.copyUntombed(), gen).toContracted(lev - 5);
545 if (!parent.GCAS(cn, ncn, ct)) {
546 if (ct.readRoot().gen == startgen) {
547 // Tail recursion: cleanParent(nonlive, parent, ct, hc, lev, startgen);
557 private void clean(final INode<K, V> nd, final TrieMap<K, V> ct, final int lev) {
558 final MainNode<K, V> m = nd.GCAS_READ(ct);
559 if (m instanceof CNode) {
560 final CNode<K, V> cn = (CNode<K, V>) m;
561 nd.GCAS(cn, cn.toCompressed(ct, lev, gen), ct);
565 int cachedSize(final TrieMap<?, ?> ct) {
566 return GCAS_READ(ct).cachedSize(ct);
569 // /* this is a quiescent method! */
570 // def string(lev: Int) = "%sINode -> %s".format(" " * lev, mainnode
572 // case null => "<null>"
573 // case tn: TNode[_, _] => "TNode(%s, %s, %d, !)".format(tn.k, tn.v,
575 // case cn: CNode[_, _] => cn.string(lev)
576 // case ln: LNode[_, _] => ln.string(lev)
577 // case x => "<elem: %s>".format(x)
581 String string(final int lev) {