Skip to content

Commit

Permalink
Add ReadableTable::first() and last()
Browse files Browse the repository at this point in the history
  • Loading branch information
cberner committed Oct 14, 2023
1 parent e559ed9 commit e435401
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,16 @@ pub trait ReadableTable<K: RedbKey + 'static, V: RedbValue + 'static>: Sealed {
K: 'a,
KR: Borrow<K::SelfType<'a>> + 'a;

/// Returns the first key-value pair in the table, if it exists
fn first(&self) -> Result<Option<(AccessGuard<K>, AccessGuard<V>)>> {
self.iter()?.next().transpose()
}

/// Returns the last key-value pair in the table, if it exists
fn last(&self) -> Result<Option<(AccessGuard<K>, AccessGuard<V>)>> {
self.iter()?.next_back().transpose()
}

/// Retrieves information about storage usage for the table
fn stats(&self) -> Result<TableStats>;

Expand Down
23 changes: 23 additions & 0 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,29 @@ fn len() {
assert_eq!(table.len().unwrap(), 3);
}

#[test]
fn first_last() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();
let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_table(STR_TABLE).unwrap();
assert!(table.first().unwrap().is_none());
assert!(table.last().unwrap().is_none());
table.insert("a", "world1").unwrap();
assert_eq!(table.first().unwrap().unwrap().0.value(), "a");
assert_eq!(table.last().unwrap().unwrap().0.value(), "a");
table.insert("b", "world2").unwrap();
table.insert("c", "world3").unwrap();
}
write_txn.commit().unwrap();

let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(STR_TABLE).unwrap();
assert_eq!(table.first().unwrap().unwrap().0.value(), "a");
assert_eq!(table.last().unwrap().unwrap().0.value(), "c");
}

#[test]
fn pop() {
let tmpfile = create_tempfile();
Expand Down

0 comments on commit e435401

Please sign in to comment.