1 /*
   2  * Copyright (c) 2015, 2015, 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 void push(Node n) {
  37         int newIndex = tos++;
  38         int valuesLength = values.length;
  39         if (newIndex >= valuesLength) {
  40             grow();
  41         }
  42         values[newIndex] = n;
  43     }
  44 
  45     private void grow() {
  46         int valuesLength = values.length;
  47         Node[] newValues = new Node[valuesLength << 1];
  48         System.arraycopy(values, 0, newValues, 0, valuesLength);
  49         values = newValues;
  50     }
  51 
  52     public Node pop() {
  53         assert tos > 0 : "stack must be non-empty";
  54         return values[--tos];
  55     }
  56 
  57     public Node peek() {
  58         assert tos > 0 : "stack must be non-empty";
  59         return values[tos - 1];
  60     }
  61 
  62     public boolean isEmpty() {
  63         return tos == 0;
  64     }
  65 
  66     @Override
  67     public String toString() {
  68         if (tos == 0) {
  69             return "NodeStack: []";
  70         }
  71         StringBuilder sb = new StringBuilder();
  72         for (int i = 0; i < tos; i++) {
  73             sb.append(", ");
  74             sb.append(values[i]);
  75         }
  76         return "NodeStack: [" + sb.substring(2) + "]";
  77     }
  78 }