001: /* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com
002:
003: This file is part of the db4o open source object database.
004:
005: db4o is free software; you can redistribute it and/or modify it under
006: the terms of version 2 of the GNU General Public License as published
007: by the Free Software Foundation and as clarified by db4objects' GPL
008: interpretation policy, available at
009: http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
010: Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
011: Suite 350, San Mateo, CA 94403, USA.
012:
013: db4o is distributed in the hope that it will be useful, but WITHOUT ANY
014: WARRANTY; without even the implied warranty of MERCHANTABILITY or
015: FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
016: for more details.
017:
018: You should have received a copy of the GNU General Public License along
019: with this program; if not, write to the Free Software Foundation, Inc.,
020: 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
021: package com.db4o.foundation;
022:
023: /**
024: * @exclude
025: */
026: public abstract class AbstractTreeIterator implements Iterator4 {
027:
028: private final Tree _tree;
029:
030: private Stack4 _stack;
031:
032: public AbstractTreeIterator(Tree tree) {
033: _tree = tree;
034: }
035:
036: public Object current() {
037: if (_stack == null) {
038: throw new IllegalStateException();
039: }
040: Tree tree = peek();
041: if (tree == null) {
042: return null;
043: }
044: return currentValue(tree);
045: }
046:
047: private Tree peek() {
048: return (Tree) _stack.peek();
049: }
050:
051: public void reset() {
052: _stack = null;
053: }
054:
055: public boolean moveNext() {
056: if (_stack == null) {
057: initStack();
058: return _stack != null;
059: }
060:
061: Tree current = peek();
062: if (current == null) {
063: return false;
064: }
065:
066: if (pushPreceding(current._subsequent)) {
067: return true;
068: }
069:
070: while (true) {
071: _stack.pop();
072: Tree parent = peek();
073: if (parent == null) {
074: return false;
075: }
076: if (current == parent._preceding) {
077: return true;
078: }
079: current = parent;
080: }
081: }
082:
083: private void initStack() {
084: if (_tree == null) {
085: return;
086: }
087: _stack = new Stack4();
088: pushPreceding(_tree);
089: }
090:
091: private boolean pushPreceding(Tree node) {
092: if (node == null) {
093: return false;
094: }
095: while (node != null) {
096: _stack.push(node);
097: node = node._preceding;
098: }
099: return true;
100: }
101:
102: protected abstract Object currentValue(Tree tree);
103: }
|