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 java.util.Iterator;
19 import java.util.Map.Entry;
20 import java.util.NoSuchElementException;
23 * Similar to Scala's ListMap. Stores a linked set of entries, guaranteed to contain unique entry keys.
25 * @author Robert Varga
27 * @param <K> the type of keys
28 * @param <V> the type of values
30 final class LNodeEntries<K, V> extends LNodeEntry<K, V> {
31 // Modified during remove only
32 private LNodeEntries<K, V> next;
34 private LNodeEntries(final K k, final V v) {
38 private LNodeEntries(final K k, final V v, final LNodeEntries<K, V> next) {
43 static <K,V> LNodeEntries<K, V> map(final K k1, final V v1, final K k2, final V v2) {
44 return new LNodeEntries<>(k1, v1, new LNodeEntries<>(k2, v2));
53 for (LNodeEntries<?, ?> wlk = next; wlk != null; wlk = wlk.next) {
59 LNodeEntry<K, V> findEntry(final Equivalence<? super K> equiv, final K key) {
60 // We do not perform recursion on purpose here, so we do not run out of stack if the key hashing fails.
61 LNodeEntries<K, V> entry = this;
63 if (equiv.equivalent(entry.getKey(), key)) {
68 } while (entry != null);
73 LNodeEntries<K,V> insert(final K key, final V value) {
74 return new LNodeEntries<>(key, value, this);
77 LNodeEntries<K, V> replace(final LNodeEntry<K, V> entry, final V v) {
78 return new LNodeEntries<>(entry.getKey(), v, remove(entry));
81 LNodeEntries<K, V> remove(final LNodeEntry<K, V> entry) {
86 final LNodeEntries<K, V> ret = new LNodeEntries<>(getKey(), getValue());
88 LNodeEntries<K, V> last = ret;
89 LNodeEntries<K, V> cur = next;
91 // We cannot use equals() here, as it is wired to key/value equality,
92 // which we really do not want.
98 last.next = new LNodeEntries<>(cur.getKey(), cur.getValue());
103 throw new IllegalStateException(String.format("Entry %s not found", entry));
106 Iterator<Entry<K, V>> iterator() {
107 return new NodeIterator<>(this);
110 static final class NodeIterator<K,V> implements Iterator<Entry<K, V>> {
111 private LNodeEntries<K, V> n;
113 NodeIterator(final LNodeEntries<K, V> n) {
118 public boolean hasNext() {
123 public Entry<K, V> next() {
125 throw new NoSuchElementException();
128 final Entry<K, V> res = n;