BUG-7464: make LNodeEntry implement Map.Entry
[yangtools.git] / third-party / triemap / src / main / java / org / opendaylight / yangtools / triemap / LNode.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 java.util.Iterator;
19 import java.util.Map.Entry;
20
21 final class LNode<K, V> extends MainNode<K, V> {
22     private final LNodeEntries<K, V> listmap;
23
24     private LNode(final LNodeEntries<K, V> listmap) {
25         this.listmap = listmap;
26     }
27
28     LNode(final K k1, final V v1, final K k2, final V v2) {
29         this(LNodeEntries.map(k1, v1, k2, v2));
30     }
31
32     LNode<K, V> insertChild( final K k, final V v) {
33         return new LNode<>(listmap.insert(k, v));
34     }
35
36     MainNode<K, V> removeChild(final LNodeEntry<K, V> entry, final int hc) {
37         // We only ever create ListMaps with two or more entries,  and remove them as soon as they reach one element
38         // (below), so we cannot observe a null return here.
39         final LNodeEntries<K, V> map = listmap.remove(entry);
40         if (map.isSingle()) {
41             // create it tombed so that it gets compressed on subsequent accesses
42             return new TNode<>(map.getKey(), map.getValue(), hc);
43         }
44
45         return new LNode<>(map);
46     }
47
48     MainNode<K, V> replaceChild(final LNodeEntry<K, V> entry, final V v) {
49         return new LNode<>(listmap.replace(entry, v));
50     }
51
52     LNodeEntry<K, V> get(final Equivalence<? super K> equiv, final K k) {
53         return listmap.findEntry(equiv, k);
54     }
55
56     @Override
57     int cachedSize(final TrieMap<?, ?> ct) {
58         return listmap.size();
59     }
60
61     @Override
62     String string(final int lev) {
63         // (" " * lev) + "LNode(%s)".format(listmap.mkString(", "))
64         return "LNode";
65     }
66
67     Iterator<Entry<K, V>> iterator() {
68         return listmap.iterator();
69     }
70 }