1 /*
   2  * Copyright (c) 2015, 2017, 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.graph;
  24 
  25 public final class NodeStack {
  26 
  27     private static final int INITIAL_SIZE = 8;
  28 
  29     protected Node[] values;
  30     public int tos;
  31 
  32     public NodeStack() {
  33         values = new Node[INITIAL_SIZE];
  34     }
  35 
  36     public int size() {
  37         return tos;
  38     }
  39 
  40     public void push(Node n) {
  41         int newIndex = tos++;
  42         int valuesLength = values.length;
  43         if (newIndex >= valuesLength) {
  44             grow();
  45         }
  46         values[newIndex] = n;
  47     }
  48 
  49     private void grow() {
  50         int valuesLength = values.length;
  51         Node[] newValues = new Node[valuesLength << 1];
  52         System.arraycopy(values, 0, newValues, 0, valuesLength);
  53         values = newValues;
  54     }
  55 
  56     public Node get(int index) {
  57         return values[index];
  58     }
  59 
  60     public Node pop() {
  61         assert tos > 0 : "stack must be non-empty";
  62         return values[--tos];
  63     }
  64 
  65     public Node peek() {
  66         assert tos > 0 : "stack must be non-empty";
  67         return values[tos - 1];
  68     }
  69 
  70     public boolean isEmpty() {
  71         return tos == 0;
  72     }
  73 
  74     @Override
  75     public String toString() {
  76         if (tos == 0) {
  77             return "NodeStack: []";
  78         }
  79         StringBuilder sb = new StringBuilder();
  80         for (int i = 0; i < tos; i++) {
  81             sb.append(", ");
  82             sb.append(values[i]);
  83         }
  84         return "NodeStack: [" + sb.substring(2) + "]";
  85     }
  86 }