Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement RedbValue and RedbKey for char #718

Merged
merged 1 commit into from
Nov 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,41 @@ impl RedbKey for &str {
}
}

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

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

fn from_bytes<'a>(data: &'a [u8]) -> char
where
Self: 'a,
{
char::from_u32(u32::from_le_bytes([data[0], data[1], data[2], 0])).unwrap()
}

fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> [u8; 3]
where
Self: 'a,
Self: 'b,
{
let bytes = u32::from(*value).to_le_bytes();
[bytes[0], bytes[1], bytes[2]]
}

fn type_name() -> TypeName {
TypeName::internal(stringify!(char))
}
}

impl RedbKey for char {
fn compare(data1: &[u8], data2: &[u8]) -> Ordering {
Self::from_bytes(data1).cmp(&Self::from_bytes(data2))
}
}

macro_rules! le_value {
($t:ty) => {
impl RedbValue for $t {
Expand Down
26 changes: 26 additions & 0 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1606,3 +1606,29 @@ fn generic_signature_lifetimes() {
read_key_generic(table, key, db);
}
}

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

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

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

let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(definition).unwrap();
assert_eq!('a', table.get(&'b').unwrap().unwrap().value());
assert_eq!('b', table.get(&'a').unwrap().unwrap().value());

let mut iter = table.iter().unwrap();
assert_eq!(iter.next().unwrap().unwrap().0.value(), 'a');
assert_eq!(iter.next().unwrap().unwrap().0.value(), 'b');
assert!(iter.next().is_none());
}
Loading