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.codegen.optimization.boxing;
018    
019    import org.jetbrains.annotations.NotNull;
020    
021    import java.util.HashSet;
022    import java.util.Iterator;
023    import java.util.Set;
024    
025    public class RedundantBoxedValuesCollection implements Iterable<BoxedBasicValue> {
026        private final Set<BoxedBasicValue> safeToDeleteValues = new HashSet<BoxedBasicValue>();
027    
028        public void add(@NotNull BoxedBasicValue value) {
029            safeToDeleteValues.add(value);
030        }
031    
032        public void remove(@NotNull BoxedBasicValue value) {
033            if (safeToDeleteValues.contains(value)) {
034                safeToDeleteValues.remove(value);
035                value.markAsUnsafeToRemove();
036    
037                for (BoxedBasicValue mergedValue : value.getMergedWith()) {
038                    remove(mergedValue);
039                }
040            }
041        }
042    
043        public void merge(@NotNull BoxedBasicValue v, @NotNull BoxedBasicValue w) {
044            v.addMergedWith(w);
045            w.addMergedWith(v);
046    
047            if (v.isSafeToRemove() && !w.isSafeToRemove()) {
048                remove(v);
049            }
050    
051            if (!v.isSafeToRemove() && w.isSafeToRemove()) {
052                remove(w);
053            }
054        }
055    
056        public boolean isEmpty() {
057            return safeToDeleteValues.isEmpty();
058        }
059    
060        @NotNull
061        @Override
062        public Iterator<BoxedBasicValue> iterator() {
063            return safeToDeleteValues.iterator();
064        }
065    }