001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.utils;
018    
019    import kotlin.collections.CollectionsKt;
020    import kotlin.jvm.functions.Function1;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    
024    import java.util.HashMap;
025    import java.util.List;
026    import java.util.Map;
027    
028    public final class Interner<T> {
029        private final Interner<T> parent;
030        private final int firstIndex;
031        private final Map<T, Integer> interned = new HashMap<T, Integer>();
032    
033        public Interner(Interner<T> parent) {
034            this.parent = parent;
035            this.firstIndex = parent != null ? parent.interned.size() + parent.firstIndex : 0;
036        }
037    
038        public Interner() {
039            this(null);
040        }
041    
042        @Nullable
043        private Integer find(@NotNull T obj) {
044            assert parent == null || parent.interned.size() + parent.firstIndex == firstIndex :
045                    "Parent changed in parallel with child: indexes will be wrong";
046            if (parent != null) {
047                Integer index = parent.find(obj);
048                if (index != null) return index;
049            }
050            return interned.get(obj);
051        }
052    
053        public int intern(@NotNull T obj) {
054            Integer index = find(obj);
055            if (index != null) return index;
056    
057            index = firstIndex + interned.size();
058            interned.put(obj, index);
059            return index;
060        }
061    
062        @NotNull
063        public List<T> getAllInternedObjects() {
064            return CollectionsKt.sortedBy(interned.keySet(), new Function1<T, Integer>() {
065                @Override
066                public Integer invoke(T key) {
067                    return interned.get(key);
068                }
069            });
070        }
071    
072        public boolean isEmpty() {
073            return interned.isEmpty() && (parent == null || parent.isEmpty());
074        }
075    }