File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\mvstore\Cursor.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.mvstore;
8
9 import java.util.Iterator;
10
11 /**
12 * A cursor to iterate over elements in ascending order.
13 *
14 * @param <K> the key type
15 */
16 public class Cursor<K> implements Iterator<K> {
17
18 protected final MVMap<K, ?> map;
19 protected final K from;
20 protected CursorPos pos;
21 protected K current;
22 private final Page root;
23 private boolean initialized;
24
25 protected Cursor(MVMap<K, ?> map, Page root, K from) {
26 this.map = map;
27 this.root = root;
28 this.from = from;
29 }
30
31 public K next() {
32 hasNext();
33 K c = current;
34 fetchNext();
35 return c;
36 }
37
38 public boolean hasNext() {
39 if (!initialized) {
40 min(root, from);
41 initialized = true;
42 fetchNext();
43 }
44 return current != null;
45 }
46
47 /**
48 * Skip over that many entries. This method is relatively fast (for this map
49 * implementation) even if many entries need to be skipped.
50 *
51 * @param n the number of entries to skip
52 */
53 public void skip(long n) {
54 if (!hasNext()) {
55 return;
56 }
57 if (n < 10) {
58 while (n-- > 0) {
59 fetchNext();
60 }
61 return;
62 }
63 long index = map.getKeyIndex(current);
64 K k = map.getKey(index + n);
65 min(root, k);
66 fetchNext();
67 }
68
69 public void remove() {
70 throw new UnsupportedOperationException();
71 }
72
73 /**
74 * Fetch the next entry that is equal or larger than the given key, starting
75 * from the given page.
76 *
77 * @param p the page to start
78 * @param from the key to search
79 */
80 protected void min(Page p, K from) {
81 while (true) {
82 if (p.isLeaf()) {
83 int x = from == null ? 0 : p.binarySearch(from);
84 if (x < 0) {
85 x = -x - 1;
86 }
87 pos = new CursorPos(p, x, pos);
88 break;
89 }
90 int x = from == null ? -1 : p.binarySearch(from);
91 if (x < 0) {
92 x = -x - 1;
93 } else {
94 x++;
95 }
96 pos = new CursorPos(p, x + 1, pos);
97 p = p.getChildPage(x);
98 }
99 }
100
101 /**
102 * Fetch the next entry if there is one.
103 */
104 @SuppressWarnings("unchecked")
105 protected void fetchNext() {
106 while (pos != null) {
107 if (pos.index < pos.page.getKeyCount()) {
108 current = (K) pos.page.getKey(pos.index++);
109 return;
110 }
111 pos = pos.parent;
112 if (pos == null) {
113 break;
114 }
115 if (pos.index < map.getChildPageCount(pos.page)) {
116 min(pos.page.getChildPage(pos.index++), null);
117 }
118 }
119 current = null;
120 }
121
122 }
123