acb37df8acc5df9afa36d1de91dfc2f98112b563
[yangtools.git] / third-party / triemap / src / main / java / org / opendaylight / yangtools / triemap / INode.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 org.opendaylight.yangtools.triemap.LookupResult.RESTART;
19 import static org.opendaylight.yangtools.triemap.PresencePredicate.ABSENT;
20 import static org.opendaylight.yangtools.triemap.PresencePredicate.PRESENT;
21
22 import java.util.Optional;
23 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
24
25 final class INode<K, V> extends BasicNode {
26     @SuppressWarnings("rawtypes")
27     private static final AtomicReferenceFieldUpdater<INode, MainNode> MAINNODE_UPDATER =
28             AtomicReferenceFieldUpdater.newUpdater(INode.class, MainNode.class, "mainnode");
29
30     private final Gen gen;
31
32     private volatile MainNode<K, V> mainnode;
33
34     INode(final Gen gen, final MainNode<K, V> mainnode) {
35         this.gen = gen;
36         this.mainnode = mainnode;
37     }
38
39     MainNode<K, V> gcasRead(final TrieMap<K, V> ct) {
40         return GCAS_READ(ct);
41     }
42
43     MainNode<K, V> GCAS_READ(final TrieMap<K, V> ct) {
44         MainNode<K, V> m = /* READ */ mainnode;
45         MainNode<K, V> prevval = /* READ */ m.READ_PREV();
46         if (prevval == null) {
47             return m;
48         }
49
50         return GCAS_Complete(m, ct);
51     }
52
53     private MainNode<K, V> GCAS_Complete(MainNode<K, V> m, final TrieMap<K, V> ct) {
54         while (true) {
55             if (m == null) {
56                 return null;
57             }
58
59             // complete the GCAS
60             final MainNode<K, V> prev = /* READ */ m.READ_PREV();
61             final INode<K, V> ctr = ct.readRoot(true);
62             if (prev == null) {
63                 return m;
64             }
65
66             if (prev instanceof FailedNode) {
67                 // try to commit to previous value
68                 FailedNode<K, V> fn = (FailedNode<K, V>) prev;
69                 if (MAINNODE_UPDATER.compareAndSet(this, m, fn.READ_PREV())) {
70                     return fn.READ_PREV();
71                 }
72
73                 // Tail recursion: return GCAS_Complete (/* READ */ mainnode, ct);
74                 m = /* READ */ mainnode;
75                 continue;
76             }
77
78             // Assume that you've read the root from the generation G.
79             // Assume that the snapshot algorithm is correct.
80             // ==> you can only reach nodes in generations <= G.
81             // ==> `gen` is <= G.
82             // We know that `ctr.gen` is >= G.
83             // ==> if `ctr.gen` = `gen` then they are both equal to G.
84             // ==> otherwise, we know that either `ctr.gen` > G, `gen` < G,
85             // or both
86             if (ctr.gen == gen && !ct.isReadOnly()) {
87                 // try to commit
88                 if (m.CAS_PREV(prev, null)) {
89                     return m;
90                 }
91
92                 // Tail recursion: return GCAS_Complete (m, ct);
93                 continue;
94             }
95
96             // try to abort
97             m.CAS_PREV(prev, new FailedNode<>(prev));
98
99             // Tail recursion: return GCAS_Complete(/* READ */ mainnode, ct);
100             m = /* READ */ mainnode;
101         }
102     }
103
104     private boolean GCAS(final MainNode<K, V> old, final MainNode<K, V> n, final TrieMap<K, V> ct) {
105         n.WRITE_PREV(old);
106         if (MAINNODE_UPDATER.compareAndSet(this, old, n)) {
107             GCAS_Complete(n, ct);
108             return /* READ */ n.READ_PREV() == null;
109         }
110
111         return false;
112     }
113
114     private INode<K, V> inode(final MainNode<K, V> cn) {
115         return new INode<>(gen, cn);
116     }
117
118     INode<K, V> copyToGen(final Gen ngen, final TrieMap<K, V> ct) {
119         return new INode<>(ngen, GCAS_READ(ct));
120     }
121
122     /**
123      * Inserts a key value pair, overwriting the old pair if the keys match.
124      *
125      * @return true if successful, false otherwise
126      */
127     boolean rec_insert(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
128             final TrieMap<K, V> ct) {
129         return rec_insert(k, v, hc, lev, parent, gen, ct);
130     }
131
132     private boolean rec_insert(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
133             final Gen startgen, final TrieMap<K, V> ct) {
134         while (true) {
135             final MainNode<K, V> m = GCAS_READ (ct); // use -Yinline!
136
137             if (m instanceof CNode) {
138                 // 1) a multiway node
139                 final CNode<K, V> cn = (CNode<K, V>) m;
140                 final int idx = (hc >>> lev) & 0x1f;
141                 final int flag = 1 << idx;
142                 final int bmp = cn.bitmap;
143                 final int mask = flag - 1;
144                 final int pos = Integer.bitCount(bmp & mask);
145                 if ((bmp & flag) != 0) {
146                     // 1a) insert below
147                     final BasicNode cnAtPos = cn.array[pos];
148                     if (cnAtPos instanceof INode) {
149                         final INode<K, V> in = (INode<K, V>) cnAtPos;
150                         if (startgen == in.gen) {
151                             return in.rec_insert(k, v, hc, lev + 5, this, startgen, ct);
152                         }
153                         if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
154                             // Tail recursion: return rec_insert (k, v, hc, lev, parent, startgen, ct);
155                             continue;
156                         }
157
158                         return false;
159                     } else if (cnAtPos instanceof SNode) {
160                         final SNode<K, V> sn = (SNode<K, V>) cnAtPos;
161                         if (sn.hc == hc && ct.equal(sn.k, k)) {
162                             return GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct);
163                         }
164
165                         final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
166                         final MainNode<K, V> nn = rn.updatedAt(pos, inode(CNode.dual(sn, sn.hc, new SNode<>(k, v, hc),
167                                 hc, lev + 5, gen)), gen);
168                         return GCAS (cn, nn, ct);
169                     }
170                 } else {
171                     CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
172                     MainNode<K, V> ncnode = rn.insertedAt(pos, flag, new SNode<> (k, v, hc), gen);
173                     return GCAS (cn, ncnode, ct);
174                 }
175             } else if (m instanceof TNode) {
176                 clean(parent, ct, lev - 5);
177                 return false;
178             } else if (m instanceof LNode) {
179                 return insertln((LNode<K, V>) m, k, v, ct);
180             } else {
181                 throw new IllegalStateException("Unhandled node " + m);
182             }
183
184             throw new RuntimeException ("Should not happen");
185         }
186     }
187
188     /**
189      * Inserts a new key value pair, given that a specific condition is met.
190      *
191      * @param cond
192      *            null - don't care if the key was there
193      *            KEY_ABSENT - key wasn't there
194      *            KEY_PRESENT - key was there
195      *            other value `v` - key must be bound to `v`
196      * @return null if unsuccessful, Option[V] otherwise (indicating
197      *         previous value bound to the key)
198      */
199     Optional<V> rec_insertif(final K k, final V v, final int hc, final Object cond, final int lev,
200             final INode<K, V> parent, final TrieMap<K, V> ct) {
201         return rec_insertif(k, v, hc, cond, lev, parent, gen, ct);
202     }
203
204     private Optional<V> rec_insertif(final K k, final V v, final int hc, final Object cond, final int lev,
205             final INode<K, V> parent, final Gen startgen, final TrieMap<K, V> ct) {
206         while (true) {
207             final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
208
209             if (m instanceof CNode) {
210                 // 1) a multiway node
211                 final CNode<K, V> cn = (CNode<K, V>) m;
212                 final int idx = (hc >>> lev) & 0x1f;
213                 final int flag = 1 << idx;
214                 final int bmp = cn.bitmap;
215                 final int mask = flag - 1;
216                 final int pos = Integer.bitCount(bmp & mask);
217
218                 if ((bmp & flag) != 0) {
219                     // 1a) insert below
220                     final BasicNode cnAtPos = cn.array[pos];
221                     if (cnAtPos instanceof INode) {
222                         final INode<K, V> in = (INode<K, V>) cnAtPos;
223                         if (startgen == in.gen) {
224                             return in.rec_insertif(k, v, hc, cond, lev + 5, this, startgen, ct);
225                         }
226
227                         if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
228                             // Tail recursion: return rec_insertif (k, v, hc, cond, lev, parent, startgen, ct);
229                             continue;
230                         }
231
232                         return null;
233                     } else if (cnAtPos instanceof SNode) {
234                         final SNode<K, V> sn = (SNode<K, V>) cnAtPos;
235                         if (cond == null) {
236                             if (sn.hc == hc && ct.equal(sn.k, k)) {
237                                 if (GCAS(cn, cn.updatedAt(pos, new SNode<>(k, v, hc), gen), ct)) {
238                                     return Optional.of(sn.v);
239                                 }
240
241                                 return null;
242                             }
243
244                             final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
245                             final MainNode<K, V> nn = rn.updatedAt(pos, inode (CNode.dual(sn, sn.hc,
246                                     new SNode<>(k, v, hc), hc, lev + 5, gen)), gen);
247                             if (GCAS(cn, nn, ct)) {
248                                 return Optional.empty();
249                             }
250
251                             return null;
252                         } else if (cond == ABSENT) {
253                             if (sn.hc == hc && ct.equal(sn.k, k)) {
254                                 return Optional.of(sn.v);
255                             }
256
257                             final CNode<K, V> rn = (cn.gen == gen) ? cn : cn.renewed(gen, ct);
258                             final MainNode<K, V> nn = rn.updatedAt(pos, inode (CNode.dual(sn, sn.hc,
259                                 new SNode<>(k, v, hc), hc, lev + 5, gen)), gen);
260                             if (GCAS(cn, nn, ct)) {
261                                 return Optional.empty();
262                             }
263
264                             return null;
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);
269                                 }
270                                 return null;
271                             }
272
273                             return Optional.empty();
274                         } else {
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);
278                                 }
279
280                                 return null;
281                             }
282
283                             return Optional.empty();
284                         }
285                     }
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();
291                     }
292
293                     return null;
294                 } else {
295                     return Optional.empty();
296                 }
297             } else if (m instanceof TNode) {
298                 clean(parent, ct, lev - 5);
299                 return null;
300             } else if (m instanceof LNode) {
301                 // 3) an l-node
302                 final LNode<K, V> ln = (LNode<K, V>) m;
303                 if (cond == null) {
304                     final Optional<V> optv = ln.get(k);
305                     if (insertln(ln, k, v, ct)) {
306                         return optv;
307                     }
308                     return null;
309                 } else if (cond == ABSENT) {
310                     final Optional<V> t = ln.get(k);
311                     if (t.isPresent()) {
312                         return t;
313                     }
314                     if (insertln(ln, k, v, ct)) {
315                         return Optional.empty();
316                     }
317                     return null;
318                 } else if (cond == PRESENT) {
319                     final Optional<V> t = ln.get(k);
320                     if (!t.isPresent()) {
321                         return t;
322                     }
323                     if (insertln(ln, k, v, ct)) {
324                         return t;
325                     }
326                     return null;
327                 } else {
328                     final Optional<V> t = ln.get(k);
329                     if (t.isPresent()) {
330                         if (cond.equals(t.get())) {
331                             if (insertln(ln, k, v, ct)) {
332                                 // Difference from Scala: we choose to reuse the object returned from LNode,
333                                 // as the identity of the value does not matter in this call graph.
334                                 return t;
335                             }
336
337                             return null;
338                         }
339                     }
340
341                     return Optional.empty();
342                 }
343             } else {
344                 throw new IllegalStateException("Unhandled node " + m);
345             }
346
347             throw new RuntimeException("Should never happen");
348         }
349     }
350
351     private boolean insertln(final LNode<K, V> ln, final K k, final V v, final TrieMap<K, V> ct) {
352         return GCAS(ln, ln.addChild(k, v), ct);
353     }
354
355     /**
356      * Looks up the value associated with the key.
357      *
358      * @return null if no value has been found, RESTART if the operation
359      *         wasn't successful, or any other value otherwise
360      */
361     Object rec_lookup(final K k, final int hc, final int lev, final INode<K, V> parent, final TrieMap<K, V> ct) {
362         return rec_lookup(k, hc, lev, parent, gen, ct);
363     }
364
365     private Object rec_lookup(final K k, final int hc, final int lev, final INode<K, V> parent, final Gen startgen,
366             final TrieMap<K, V> ct) {
367         while (true) {
368             final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
369
370             if (m instanceof CNode) {
371                 // 1) a multinode
372                 final CNode<K, V> cn = (CNode<K, V>) m;
373                 final int idx = (hc >>> lev) & 0x1f;
374                 final int flag = 1 << idx;
375                 final int bmp = cn.bitmap;
376                 if ((bmp & flag) == 0) {
377                     // 1a) bitmap shows no binding
378                     return null;
379                 }
380
381                 // 1b) bitmap contains a value - descend
382                 final int pos = (bmp == 0xffffffff) ? idx : Integer.bitCount(bmp & (flag - 1));
383                 final BasicNode sub = cn.array[pos];
384                 if (sub instanceof INode) {
385                     final INode<K, V> in = (INode<K, V>) sub;
386                     if (ct.isReadOnly() || (startgen == in.gen)) {
387                         return in.rec_lookup(k, hc, lev + 5, this, startgen, ct);
388                     }
389
390                     if (GCAS(cn, cn.renewed(startgen, ct), ct)) {
391                         // Tail recursion: return rec_lookup(k, hc, lev, parent, startgen, ct);
392                         continue;
393                     }
394
395                     return RESTART;
396                 } else if (sub instanceof SNode) {
397                     // 2) singleton node
398                     final SNode<K, V> sn = (SNode<K, V>) sub;
399                     if (sn.hc == hc && ct.equal(sn.k, k)) {
400                         return sn.v;
401                     }
402
403                     return null;
404                 }
405             } else if (m instanceof TNode) {
406                 // 3) non-live node
407                 return cleanReadOnly((TNode<K, V>) m, lev, parent, ct, k, hc);
408             } else if (m instanceof LNode) {
409                 // 5) an l-node
410                 return ((LNode<K, V>) m).get(k).orElse(null);
411             } else {
412                 throw new IllegalStateException("Unhandled node " + m);
413             }
414
415             throw new RuntimeException ("Should not happen");
416         }
417     }
418
419     private Object cleanReadOnly(final TNode<K, V> tn, final int lev, final INode<K, V> parent,
420             final TrieMap<K, V> ct, final K k, final int hc) {
421         if (ct.isReadOnly()) {
422             if (tn.hc == hc && ct.equal(tn.k, k)) {
423                 return tn.v;
424             }
425
426             return null;
427         }
428
429         clean(parent, ct, lev - 5);
430         return RESTART;
431     }
432
433     /**
434      * Removes the key associated with the given value.
435      *
436      * @param v
437      *            if null, will remove the key regardless of the value;
438      *            otherwise removes only if binding contains that exact key
439      *            and value
440      * @return null if not successful, an Option[V] indicating the previous
441      *         value otherwise
442      */
443     Optional<V> rec_remove(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
444             final TrieMap<K, V> ct) {
445         return rec_remove(k, v, hc, lev, parent, gen, ct);
446     }
447
448     private Optional<V> rec_remove(final K k, final V v, final int hc, final int lev, final INode<K, V> parent,
449             final Gen startgen, final TrieMap<K, V> ct) {
450         final MainNode<K, V> m = GCAS_READ(ct); // use -Yinline!
451
452         if (m instanceof CNode) {
453             final CNode<K, V> cn = (CNode<K, V>) m;
454             final int idx = (hc >>> lev) & 0x1f;
455             final int bmp = cn.bitmap;
456             final int flag = 1 << idx;
457             if ((bmp & flag) == 0) {
458                 return Optional.empty();
459             }
460
461             final int pos = Integer.bitCount(bmp & (flag - 1));
462             final BasicNode sub = cn.array[pos];
463             Optional<V> res = null;
464             if (sub instanceof INode) {
465                 final INode<K, V> in = (INode<K, V>) sub;
466                 if (startgen == in.gen) {
467                     res = in.rec_remove(k, v, hc, lev + 5, this, startgen, ct);
468                 } else {
469                     if (GCAS(cn, cn.renewed (startgen, ct), ct)) {
470                         res = rec_remove(k, v, hc, lev, parent, startgen, ct);
471                     } else {
472                         res = null;
473                     }
474                 }
475
476             } else if (sub instanceof SNode) {
477                 final SNode<K, V> sn = (SNode<K, V>) sub;
478                 if (sn.hc == hc && ct.equal(sn.k, k) && (v == null || v.equals(sn.v))) {
479                     final MainNode<K, V> ncn = cn.removedAt(pos, flag, gen).toContracted(lev);
480                     if (GCAS(cn, ncn, ct)) {
481                         res = Optional.of(sn.v);
482                     } else {
483                         res = null;
484                     }
485                 } else {
486                     res = Optional.empty();
487                 }
488             }
489
490             if (res == null || !res.isPresent()) {
491                 return res;
492             }
493
494             if (parent != null) {
495                 // never tomb at root
496                 final MainNode<K, V> n = GCAS_READ(ct);
497                 if (n instanceof TNode) {
498                     cleanParent(n, parent, ct, hc, lev, startgen);
499                 }
500             }
501
502             return res;
503         } else if (m instanceof TNode) {
504             clean(parent, ct, lev - 5);
505             return null;
506         } else if (m instanceof LNode) {
507             final LNode<K, V> ln = (LNode<K, V>) m;
508             final Optional<V> optv = ln.get(k);
509
510             if (!optv.isPresent()) {
511                 // Key was not found, hence no modification is needed
512                 return Optional.empty();
513             }
514
515             if (v != null && !v.equals(optv.get())) {
516                 // Value does not match
517                 return Optional.empty();
518             }
519
520             return GCAS(ln, ln.removeChild(k, hc, ct), ct) ? optv : null;
521         } else {
522             throw new IllegalStateException("Unhandled node " + m);
523         }
524     }
525
526     private void cleanParent(final Object nonlive, final INode<K, V> parent, final TrieMap<K, V> ct, final int hc,
527             final int lev, final Gen startgen) {
528         while (true) {
529             final MainNode<K, V> pm = parent.GCAS_READ(ct);
530             if ((!(pm instanceof CNode))) {
531                 // parent is no longer a cnode, we're done
532                 return;
533             }
534
535             final CNode<K, V> cn = (CNode<K, V>) pm;
536             final int idx = (hc >>> (lev - 5)) & 0x1f;
537             final int bmp = cn.bitmap;
538             final int flag = 1 << idx;
539             if ((bmp & flag) == 0) {
540                 // somebody already removed this i-node, we're done
541                 return;
542             }
543
544             final int pos = Integer.bitCount(bmp & (flag - 1));
545             final BasicNode sub = cn.array[pos];
546             if (sub == this) {
547                 if (nonlive instanceof TNode) {
548                     final TNode<K, V> tn = (TNode<K, V>) nonlive;
549                     MainNode<K, V> ncn = cn.updatedAt(pos, tn.copyUntombed(), gen).toContracted(lev - 5);
550                     if (!parent.GCAS(cn, ncn, ct)) {
551                         if (ct.readRoot().gen == startgen) {
552                             // Tail recursion: cleanParent(nonlive, parent, ct, hc, lev, startgen);
553                             continue;
554                         }
555                     }
556                 }
557             }
558             break;
559         }
560     }
561
562     private void clean(final INode<K, V> nd, final TrieMap<K, V> ct, final int lev) {
563         final MainNode<K, V> m = nd.GCAS_READ(ct);
564         if (m instanceof CNode) {
565             final CNode<K, V> cn = (CNode<K, V>) m;
566             nd.GCAS(cn, cn.toCompressed(ct, lev, gen), ct);
567         }
568     }
569
570     int cachedSize(final TrieMap<K, V> ct) {
571         MainNode<K, V> m = GCAS_READ(ct);
572         return m.cachedSize(ct);
573     }
574
575     // /* this is a quiescent method! */
576     // def string(lev: Int) = "%sINode -> %s".format("  " * lev, mainnode
577     // match {
578     // case null => "<null>"
579     // case tn: TNode[_, _] => "TNode(%s, %s, %d, !)".format(tn.k, tn.v,
580     // tn.hc)
581     // case cn: CNode[_, _] => cn.string(lev)
582     // case ln: LNode[_, _] => ln.string(lev)
583     // case x => "<elem: %s>".format(x)
584     // })
585
586     @Override
587     String string(final int lev) {
588         return "INode";
589     }
590 }