1 /* 2 * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 package org.graalvm.compiler.lir.constopt; 24 25 import java.util.ArrayList; 26 import java.util.function.Consumer; 27 import java.util.function.Predicate; 28 29 import org.graalvm.compiler.lir.Variable; 30 31 /** 32 * Maps variables to a generic type. 33 * 34 * TODO (je) evaluate data structure 35 */ 36 class VariableMap<T> { 37 38 private final ArrayList<T> content; 39 40 VariableMap() { 41 content = new ArrayList<>(); 42 } 43 44 public T get(Variable key) { 45 if (key == null || key.index >= content.size()) { 46 return null; 47 } 48 return content.get(key.index); 49 } 50 51 public T put(Variable key, T value) { 52 assert key != null : "Key cannot be null"; 53 assert value != null : "Value cannot be null"; 54 while (key.index >= content.size()) { 55 content.add(null); 56 } 57 return content.set(key.index, value); 58 } 59 60 public T remove(Variable key) { 61 assert key != null : "Key cannot be null"; 62 if (key.index >= content.size()) { 63 return null; 64 } 65 return content.set(key.index, null); 66 } 67 68 public void forEach(Consumer<T> action) { 69 for (T e : content) { 70 if (e != null) { 71 action.accept(e); 72 } 73 } 74 } 75 76 /** 77 * Keeps only keys which match the given predicate. 78 */ 79 public void filter(Predicate<T> predicate) { 80 for (int i = 0; i < content.size(); i++) { 81 T e = content.get(i); 82 if (e != null && !predicate.test(e)) { 83 content.set(i, null); 84 } 85 } 86 } 87 88 }