1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.datastructures.persistent;
14 public abstract class ImmutableStack<T> {
16 private ImmutableStack() {
19 private static class SingleStackNode<T> extends ImmutableStack<T> {
20 ImmutableStack<T> parent;
23 public SingleStackNode(ImmutableStack<T> parent, T value) {
30 return i==0 ? value : parent.get(i-1);
34 private static class MultiStackNode<T> extends ImmutableStack<T> {
35 ImmutableStack<T> parent;
38 public MultiStackNode(ImmutableStack<T> parent, T[] values) {
45 return i<values.length ? values[i] : parent.get(i-values.length);
49 private static class EmptyStack<T> extends ImmutableStack<T> {
53 throw new IllegalArgumentException("No such element in stack.");
58 @SuppressWarnings({ "rawtypes" })
59 static final EmptyStack EMPTY = new EmptyStack();
61 public ImmutableStack<T> push(T value) {
62 return new SingleStackNode<T>(this, value);
65 public ImmutableStack<T> push(T[] values) {
67 return new MultiStackNode<T>(this, values);
68 else if(values.length == 1)
69 return new SingleStackNode<T>(this, values[0]);
74 public abstract T get(int i);
76 @SuppressWarnings("unchecked")
77 public static <T> ImmutableStack<T> empty() {
78 return (ImmutableStack<T>)EMPTY;
81 public static <T> ImmutableStack<T> of(T value) {
82 return new SingleStackNode<T>(null, value);
85 @SuppressWarnings("unchecked")
86 public static <T> ImmutableStack<T> of(T[] values) {
88 return new MultiStackNode<T>((ImmutableStack<T>)empty(), values);
89 else if(values.length == 1)
90 return new SingleStackNode<T>((ImmutableStack<T>)empty(), values[0]);