Skip to content

Commit

Permalink
Implement RedbKey for Option<T: RedbKey>
Browse files Browse the repository at this point in the history
  • Loading branch information
cberner committed Sep 30, 2023
1 parent 2a39fe3 commit 13604b5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
19 changes: 19 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,25 @@ impl<T: RedbValue> RedbValue for Option<T> {
}
}

impl<T: RedbKey> RedbKey for Option<T> {
#[allow(clippy::collapsible_else_if)]
fn compare(data1: &[u8], data2: &[u8]) -> Ordering {
if data1[0] == 0 {
if data2[0] == 0 {
Ordering::Equal
} else {
Ordering::Less
}
} else {
if data2[0] == 0 {
Ordering::Greater
} else {
T::compare(&data1[1..], &data2[1..])
}
}
}
}

impl RedbValue for &[u8] {
type SelfType<'a> = &'a [u8]
where
Expand Down
14 changes: 9 additions & 5 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -999,20 +999,24 @@ fn option_type() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();

let definition: TableDefinition<u8, Option<u32>> = TableDefinition::new("x");
let definition: TableDefinition<Option<u8>, Option<u32>> = TableDefinition::new("x");

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_table(definition).unwrap();
table.insert(0, None).unwrap();
table.insert(1, Some(1)).unwrap();
table.insert(None, None).unwrap();
table.insert(None, Some(0)).unwrap();
table.insert(Some(1), Some(1)).unwrap();
}
write_txn.commit().unwrap();

let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(definition).unwrap();
assert_eq!(table.get(0).unwrap().unwrap().value(), None);
assert_eq!(table.get(1).unwrap().unwrap().value(), Some(1));
assert_eq!(table.get(None).unwrap().unwrap().value(), Some(0));
assert_eq!(table.get(Some(1)).unwrap().unwrap().value(), Some(1));
let mut iter = table.iter().unwrap();
assert_eq!(iter.next().unwrap().unwrap().0.value(), None);
assert_eq!(iter.next().unwrap().unwrap().0.value(), Some(1));
}

#[test]
Expand Down

0 comments on commit 13604b5

Please sign in to comment.