1 28 29 package com.caucho.xpath.pattern; 30 31 import com.caucho.xpath.ExprEnvironment; 32 import com.caucho.xpath.XPathException; 33 34 import org.w3c.dom.Node ; 35 36 import java.util.logging.Level ; 37 38 41 public class MergeIterator extends NodeIterator { 42 private NodeIterator _baseIterator; 43 44 private SelectedNode []_nodes = new SelectedNode[32]; 45 private int _head; 46 private int _tail; 47 48 51 public MergeIterator(ExprEnvironment env, NodeIterator baseIterator) 52 throws XPathException 53 { 54 super(env); 55 56 _baseIterator = baseIterator; 57 58 SelectedNode node; 59 loop: 60 while ((node = baseIterator.nextSelectedNode()) != null) { 61 if (_tail == _nodes.length) { 62 SelectedNode []newNodes = new SelectedNode[2 * _nodes.length]; 63 System.arraycopy(_nodes, 0, newNodes, 0, _nodes.length); 64 _nodes = newNodes; 65 } 66 67 int index = _tail; 68 for (; index > 0; index--) { 69 SelectedNode oldNode = _nodes[index - 1]; 70 71 int cmp = node.compareTo(oldNode); 72 73 if (cmp > 0) 74 break; 75 else if (cmp == 0) 76 continue loop; 77 } 78 79 for (int ptr = _tail++; index < ptr; ptr--) 80 _nodes[ptr] = _nodes[ptr - 1]; 81 82 _nodes[index] = node; 83 } 84 } 85 86 89 public boolean hasNext() 90 { 91 return _head < _tail; 92 } 93 94 97 public Node nextNode() 98 { 99 if (_head < _tail) { 100 _position = _head + 1; 101 return _nodes[_head++].getNode(); 102 } 103 else 104 return null; 105 } 106 107 110 public SelectedNode nextSelectedNode() 111 { 112 if (_head < _tail) { 113 _position = _head + 1; 114 return _nodes[_head++]; 115 } 116 else 117 return null; 118 } 119 120 123 public Object clone() 124 { 125 try { 126 MergeIterator clone = new MergeIterator(_env, _baseIterator); 127 clone._head = _head; 128 clone._tail = _tail; 129 130 if (_nodes.length != clone._nodes.length) 131 clone._nodes = new SelectedNode[_nodes.length]; 132 133 System.arraycopy(_nodes, 0, clone._nodes, 0, _tail); 134 135 return clone; 136 } catch (Exception e) { 137 log.log(Level.FINE, e.toString(), e); 138 139 return null; 140 } 141 } 142 } 143 144 | Popular Tags |