BUG-7464: Optimize LNode.removed()
[yangtools.git] / third-party / triemap / src / main / java / org / opendaylight / yangtools / triemap / LNode.java
index 3aad0d70c2e24224369302dcea2dc666024f8ea1..7d55a7442cc109a3c10bb1401f18a8f73b62fcf0 100644 (file)
  */
 package org.opendaylight.yangtools.triemap;
 
+import java.util.Iterator;
 import java.util.Map.Entry;
+import java.util.Optional;
 
 final class LNode<K, V> extends MainNode<K, V> {
-    final ListMap<K, V> listmap;
+    private final ListMap<K, V> listmap;
 
-    LNode(final ListMap<K, V> listmap) {
+    private LNode(final ListMap<K, V> listmap) {
         this.listmap = listmap;
     }
 
-    LNode(final K k, final V v) {
-        this(ListMap.map(k, v));
-    }
-
     LNode(final K k1, final V v1, final K k2, final V v2) {
         this(ListMap.map(k1, v1, k2, v2));
     }
 
     LNode<K, V> inserted(final K k, final V v) {
-        return new LNode<> (listmap.add (k, v));
+        return new LNode<>(listmap.add(k, v));
     }
 
-    MainNode<K, V> removed (final K k, final TrieMap<K, V> ct) {
-        ListMap<K, V> updmap = listmap.remove(k);
-        if (updmap.size () > 1) {
-            return new LNode<> (updmap);
+    // FIXME: can we also get the hashcode ?
+    MainNode<K, V> removed(final K k, final TrieMap<K, V> ct) {
+        // We only ever create ListMaps with two or more entries,  and remove them as soon as they reach one element
+        // (below), so we cannot observe a null return here.
+        final ListMap<K, V> map = listmap.remove(k);
+        final Optional<Entry<K, V>> maybeKv = map.maybeSingleton();
+        if (maybeKv.isPresent()) {
+            final Entry<K, V> kv = maybeKv.get();
+            // create it tombed so that it gets compressed on subsequent accesses
+            return new TNode<>(kv.getKey(), kv.getValue(), ct.computeHash(kv.getKey()));
         }
 
-        final Entry<K, V> kv = updmap.iterator().next();
-        // create it tombed so that it gets compressed on subsequent accesses
-        return new TNode<>(kv.getKey(), kv.getValue(), ct.computeHash(kv.getKey()));
+        return new LNode<>(map);
     }
 
-    Option<V> get(final K k) {
+    Optional<V> get(final K k) {
         return listmap.get(k);
     }
 
     @Override
-    public int cachedSize(final Object ct) {
+    int cachedSize(final TrieMap<K, V> ct) {
         return listmap.size();
     }
 
@@ -61,4 +63,8 @@ final class LNode<K, V> extends MainNode<K, V> {
         // (" " * lev) + "LNode(%s)".format(listmap.mkString(", "))
         return "LNode";
     }
+
+    Iterator<Entry<K, V>> iterator() {
+        return listmap.iterator();
+    }
 }
\ No newline at end of file