001/*
002 *  This file is part of the Jikes RVM project (http://jikesrvm.org).
003 *
004 *  This file is licensed to You under the Eclipse Public License (EPL);
005 *  You may not use this file except in compliance with the License. You
006 *  may obtain a copy of the License at
007 *
008 *      http://www.opensource.org/licenses/eclipse-1.0.php
009 *
010 *  See the COPYRIGHT.txt file distributed with this work for information
011 *  regarding copyright ownership.
012 */
013package org.jikesrvm.compilers.opt.util;
014
015import java.util.ArrayList;
016import java.util.Iterator;
017
018/**
019 * Stack is a smaller implementation of java.util.Stack, that uses a linked
020 * list rather than a vector.
021 */
022public class Stack<T> implements Iterable<T> {
023  private final ArrayList<T> stack = new ArrayList<T>();
024
025  public Stack() {
026  }
027
028  public Stack(T e) {
029    push(e);
030  }
031
032  public final T push(T e) {
033    stack.add(e);
034    return e;
035  }
036
037  public final T pop() {
038    return stack.remove(stack.size() - 1);
039  }
040
041  public final T getTOS() {
042    return stack.get(stack.size() - 1);
043  }
044
045  public final T peek() {
046    return getTOS();
047  }
048
049  public final boolean isEmpty() {
050    return stack.isEmpty();
051  }
052
053  public final boolean empty() {
054    return isEmpty();
055  }
056
057  public final boolean compare(Stack<T> s2) {
058    Iterator<T> i1 = iterator();
059    Iterator<T> i2 = s2.iterator();
060    if (isEmpty() && s2.isEmpty()) {
061      return true;
062    } else if (isEmpty() || s2.isEmpty()) {
063      return false;
064    }
065    for (T t1 = i1.next(), t2 = i2.next(); i1.hasNext() && i2.hasNext();) {
066      if (t1 != t2) {
067        return false;
068      }
069      t1 = i1.next();
070      t2 = i2.next();
071    }
072    return !i1.hasNext() && !i2.hasNext();
073  }
074
075  public final Stack<T> copy() {
076    Stack<T> s = new Stack<T>();
077    s.stack.addAll(stack);
078    return s;
079  }
080
081  public final Stack<T> shallowCopy() {
082    Stack<T> s = new Stack<T>();
083    s.stack.addAll(stack);
084    return s;
085  }
086
087  @Override
088  public final Iterator<T> iterator() {
089    return stack.iterator();
090  }
091
092  @Override
093  public String toString() {
094    StringBuilder sb = new StringBuilder(" --> ");
095    for (T t : stack) {
096      sb.append(t.toString());
097      sb.append(' ');
098    }
099    return sb.toString();
100  }
101}