001    /*
002     * Copyright 2010-2013 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.jet.descriptors.serialization;
018    
019    import gnu.trove.TObjectHashingStrategy;
020    import gnu.trove.TObjectIntHashMap;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.annotations.Nullable;
023    
024    import java.util.ArrayList;
025    import java.util.List;
026    
027    public final class Interner<T> {
028        private final Interner<T> parent;
029        private final int firstIndex;
030        private final TObjectIntHashMap<T> interned;
031        private final List<T> all = new ArrayList<T>();
032    
033        public Interner(Interner<T> parent, @NotNull TObjectHashingStrategy<T> hashing) {
034            this.parent = parent;
035            this.firstIndex = parent == null ? 0 : parent.all.size();
036            this.interned = new TObjectIntHashMap<T>(hashing);
037        }
038    
039        public Interner(@NotNull TObjectHashingStrategy<T> hashing) {
040            this(null, hashing);
041        }
042    
043        public Interner(@Nullable Interner<T> parent) {
044            //noinspection unchecked
045            this(parent, TObjectHashingStrategy.CANONICAL);
046        }
047    
048        public Interner() {
049            //noinspection unchecked
050            this((Interner) null);
051        }
052    
053        public int intern(@NotNull T obj) {
054            assert parent == null || parent.all.size() == firstIndex : "Parent changed in parallel with child: indexes will be wrong";
055            if (parent != null && parent.interned.contains(obj)) {
056                return parent.intern(obj);
057            }
058            if (interned.contains(obj)) {
059                return interned.get(obj);
060            }
061            int index = firstIndex + interned.size();
062            interned.put(obj, index);
063            all.add(obj);
064            return index;
065        }
066    
067        public List<T> getAllInternedObjects() {
068            return all;
069        }
070    }