Location: PHPKode > scripts > ps stack classes > ps-stack-classes/stack.class.php
<?php

/* Basic Stack Class
 * Written by Jon Lawrence (http://www.phpclasses.org/browse/author/150618.html)
 * Modified by Asher Holley (http://www.wolfoxinc.com/opensource/)
 * Released under the GNU General Public License ( http://www.opensource.org/licenses/gpl-license.html )
 * Copyright © 2006 Asher Holley
 *
 * This stack conforms to almost all of the PostScript stack manipulators
 *      except for mark and cleartomark.  It is modified from its
 *      original design to eliminate the superfluous $index variable. */

class Stack {
	var $lifo;

	function Stack( $data = null ) {
		if ( is_array( $data ) ) {
			$this->lifo = $data;
		} else if ( is_a( $data, 'Stack' ) ) {
			$this->lifo = $data->lifo;
		} else if ( $data ) {
			$this->lifo = array();
			$this->lifo[] = $data;
		} else {
			$this->lifo = array();
		}

		return;
	}
	
	function top() {
		if ( !empty( $this->lifo ) ) {
			return array_slice( $this->lifo, -1 );
		} else {
			return null;
		}
	}
	
	function &top_ref() {
		if ( !empty( $this->lifo ) ) {
			return $this->lifo[ $this->count() - 1 ];
		} else {
			return null;
		}
	}

	function push() {
		$args = func_get_args();
		$exec = 'array_push( $this->lifo';
		for ( $a = 0; $a < count( $args ); $a++ ) {
			$exec .= ', $args[' . $a . ']';
		}
		
		$exec .= ' );';
		return eval( $exec );
	}

	function pop() {
		return array_pop( $this->lifo );
	}
	
	function &pop_ref() {
		$e =& $this->top_ref();
		array_pop( $this->lifo );
		return $e;
	}
	
	function index( $i ) {
		if ( $i > ( $l = count( $this->lifo ) - 1 ) || $i < 0 ) {
			return null;
		} else {
			return $this->lifo[ $l - $i ];
		}
	}
	
	function &index_ref( $i ) {
		if ( $i > ( $l = count( $this->lifo ) - 1 ) || $i < 0 ) {
			return null;
		} else {
			return $this->lifo[ $l - $i ];
		}
	}
	
	function count() {
		return count( $this->lifo );
	}
	
	function is_empty() {
		return empty( $this->lifo );
	}

	function clear() {
		$this->lifo = array();
		return;
	}

	function get_stack() {
		return array_reverse( $this->lifo );
	}
	
	function exch() {
		$m1 =& $this->pop_ref();
		$m2 =& $this->pop_ref();
		$this->lifo[] =& $m1;
		$this->lifo[] =& $m2;
		return;
	}
	
	function dup() {
		$this->lifo[] = $this->top();
		return;
	}
	
	function roll( $c ) {
		if ( is_int( $c ) ) {
			if ( abs( $c ) > ( $l = $this->count() ) ) {
				if ( $c < 0 ) {
					$c = ( abs( $c ) % $l ) * -1;
				} else {
					$c %= $l;
				}
			}
			
			if ( $c > 0 ) { // rotate right
				$this->lifo = array_merge( array_slice( $this->lifo, $l - $c ),
										array_slice( $this->lifo, 0, $l - $c ) );
			} else if ( $c < 0 ) { // rotate left
				$c = abs( $c );
				$this->lifo = array_merge( array_slice( $this->lifo, $c ),
										array_slice( $this->lifo, 0, $c ) );
			}
		}

		return;
	}
}

?>
Return current item: ps stack classes