Skip to content

Commit

Permalink
Implement RedbKey and RedbValue for bool
Browse files Browse the repository at this point in the history
  • Loading branch information
cberner committed Nov 5, 2023
1 parent 4ba570a commit fc150a2
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,53 @@ impl RedbKey for () {
}
}

impl RedbValue for bool {
type SelfType<'a> = bool
where
Self: 'a;
type AsBytes<'a> = &'a [u8]
where
Self: 'a;

fn fixed_width() -> Option<usize> {
Some(1)
}

fn from_bytes<'a>(data: &'a [u8]) -> bool
where
Self: 'a,
{
match data[0] {
0 => false,
1 => true,
_ => unreachable!(),
}
}

fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> &'a [u8]
where
Self: 'a,
Self: 'b,
{
match value {
true => &[1],
false => &[0],
}
}

fn type_name() -> TypeName {
TypeName::internal("bool")
}
}

impl RedbKey for bool {
fn compare(data1: &[u8], data2: &[u8]) -> Ordering {
let value1 = Self::from_bytes(data1);
let value2 = Self::from_bytes(data2);
value1.cmp(&value2)
}
}

impl<T: RedbValue> RedbValue for Option<T> {
type SelfType<'a> = Option<T::SelfType<'a>>
where
Expand Down
27 changes: 27 additions & 0 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,33 @@ fn empty_type() {
assert!(!table.is_empty().unwrap());
}

#[test]
#[allow(clippy::bool_assert_comparison)]
fn bool_type() {
let tmpfile = create_tempfile();
let db = Database::create(tmpfile.path()).unwrap();

let definition: TableDefinition<bool, bool> = TableDefinition::new("x");

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_table(definition).unwrap();
table.insert(true, &false).unwrap();
table.insert(&false, false).unwrap();
}
write_txn.commit().unwrap();

let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(definition).unwrap();
assert_eq!(false, table.get(&true).unwrap().unwrap().value());
assert_eq!(false, table.get(&false).unwrap().unwrap().value());

let mut iter = table.iter().unwrap();
assert_eq!(iter.next().unwrap().unwrap().0.value(), false);
assert_eq!(iter.next().unwrap().unwrap().0.value(), true);
assert!(iter.next().is_none());
}

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

0 comments on commit fc150a2

Please sign in to comment.