This repository has been archived by the owner on Sep 4, 2020. It is now read-only.
/
KeyIteratorImpl.java
102 lines (85 loc) · 2.46 KB
/
KeyIteratorImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.snappydb.internal;
import android.util.Log;
import com.snappydb.KeyIterator;
import com.snappydb.SnappydbException;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
class KeyIteratorImpl implements KeyIterator {
private final DBImpl db;
private final String endPrefix;
private final boolean reverse;
private long ptr;
private String nextKey;
protected KeyIteratorImpl(DBImpl db, long ptr, String endPrefix, boolean reverse) {
this.db = db;
this.ptr = ptr;
this.endPrefix = endPrefix;
this.reverse = reverse;
nextKey = db.__iteratorKey(ptr, endPrefix, reverse);
}
@Override
public void close() throws IOException {
if (ptr != 0)
db.__iteratorClose(ptr);
ptr = 0;
}
@Override
protected void finalize() throws Throwable {
if (ptr != 0) {
Log.w("KeyIterator", "SnappyDB iterators must be closed");
close();
}
super.finalize();
}
@Override
public boolean hasNext() {
if (nextKey == null) {
if (ptr != 0) {
try {//auto close the Iterator (if the user is traversing the keys with a for-each loop)
close();
ptr = 0;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
} else {
return true;
}
}
@Override
public String next() {
if (nextKey == null) {
throw new NoSuchElementException();
}
try {
String key = nextKey;
nextKey = db.__iteratorNextKey(ptr, endPrefix, reverse);
return key;
} catch (SnappydbException e) {
throw new RuntimeException(e);
}
}
@Override
public String[] next(int max) {
if (nextKey == null) {
throw new NoSuchElementException();
}
try {
String[] keys = db.__iteratorNextArray(ptr, endPrefix, reverse, max);
nextKey = db.__iteratorKey(ptr, endPrefix, reverse);
return keys;
} catch (SnappydbException e) {
throw new RuntimeException(e);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator() {
return this;
}
}