Skip to content

Commit 22008de

Browse files
committed
Convenience methods for cursor navigation
1 parent b40d34d commit 22008de

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/main/java/org/lmdbjava/Cursor.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,34 @@ public boolean seek(final SeekOp op) {
230230
return true;
231231
}
232232

233+
/**
234+
* Position at first key/data item
235+
*/
236+
public boolean first() {
237+
return seek(SeekOp.MDB_FIRST);
238+
}
239+
240+
/**
241+
* Position at last key/data item
242+
*/
243+
public boolean last() {
244+
return seek(SeekOp.MDB_LAST);
245+
}
246+
247+
/**
248+
* Position at next data item
249+
*/
250+
public boolean next() {
251+
return seek(SeekOp.MDB_NEXT);
252+
}
253+
254+
/**
255+
* Position at previous data item
256+
*/
257+
public boolean prev() {
258+
return seek(SeekOp.MDB_PREV);
259+
}
260+
233261
private void checkNotClosed() throws ClosedException {
234262
if (closed) {
235263
throw new ClosedException();

src/main/java/org/lmdbjava/SeekOp.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ public enum SeekOp {
7777
* Position at first data item of next key
7878
*/
7979
MDB_NEXT_NODUP(11),
80+
8081
/**
8182
* Position at previous data item
8283
*/

src/test/java/org/lmdbjava/CursorTest.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,4 +350,35 @@ private <T> Env<T> makeEnv(final BufferProxy<T> proxy) {
350350
throw new RuntimeException(e);
351351
}
352352
}
353+
354+
@Test
355+
public void cursorFirstLastNextPrev() {
356+
final Env<ByteBuffer> env = makeEnv(PROXY_OPTIMAL);
357+
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
358+
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
359+
// populate data
360+
final Cursor<ByteBuffer> c = db.openCursor(txn);
361+
c.put(createBb(1), createBb(2), MDB_NOOVERWRITE);
362+
c.put(createBb(3), createBb(4));
363+
c.put(createBb(5), createBb(6));
364+
c.put(createBb(7), createBb(8));
365+
366+
assertThat(c.first(), is(true));
367+
assertThat(txn.key().getInt(0), is(1));
368+
assertThat(txn.val().getInt(0), is(2));
369+
370+
assertThat(c.last(), is(true));
371+
assertThat(txn.key().getInt(0), is(7));
372+
assertThat(txn.val().getInt(0), is(8));
373+
374+
assertThat(c.prev(), is(true));
375+
assertThat(txn.key().getInt(0), is(5));
376+
assertThat(txn.val().getInt(0), is(6));
377+
378+
assertThat(c.first(), is(true));
379+
assertThat(c.next(), is(true));
380+
assertThat(txn.key().getInt(0), is(3));
381+
assertThat(txn.val().getInt(0), is(4));
382+
}
383+
}
353384
}

0 commit comments

Comments
 (0)