diff --git a/src/table.rs b/src/table.rs index 5e8d5b9a..60505ce9 100644 --- a/src/table.rs +++ b/src/table.rs @@ -292,6 +292,16 @@ pub trait ReadableTable: Sealed { K: 'a, KR: Borrow> + 'a; + /// Returns the first key-value pair in the table, if it exists + fn first(&self) -> Result, AccessGuard)>> { + self.iter()?.next().transpose() + } + + /// Returns the last key-value pair in the table, if it exists + fn last(&self) -> Result, AccessGuard)>> { + self.iter()?.next_back().transpose() + } + /// Retrieves information about storage usage for the table fn stats(&self) -> Result; diff --git a/tests/basic_tests.rs b/tests/basic_tests.rs index 1f92bece..9192b7a4 100644 --- a/tests/basic_tests.rs +++ b/tests/basic_tests.rs @@ -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();