Skip to content

Implement Key and Value for String #792

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

Merged
merged 1 commit into from
Apr 8, 2024
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
40 changes: 40 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,46 @@ impl Key for &str {
}
}

impl Value for String {
type SelfType<'a> = String
where
Self: 'a;
type AsBytes<'a> = &'a str
where
Self: 'a;

fn fixed_width() -> Option<usize> {
None
}

fn from_bytes<'a>(data: &'a [u8]) -> String
where
Self: 'a,
{
std::str::from_utf8(data).unwrap().to_string()
}

fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> &'a str
where
Self: 'a,
Self: 'b,
{
value.as_str()
}

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

impl Key for String {
fn compare(data1: &[u8], data2: &[u8]) -> Ordering {
let str1 = std::str::from_utf8(data1).unwrap();
let str2 = std::str::from_utf8(data2).unwrap();
str1.cmp(str2)
}
}

impl Value for char {
type SelfType<'a> = char;
type AsBytes<'a> = [u8; 3] where Self: 'a;
Expand Down
32 changes: 32 additions & 0 deletions tests/basic_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,38 @@ fn str_type() {
assert!(iter.next().is_none());
}

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

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

let write_txn = db.begin_write().unwrap();
{
let mut table = write_txn.open_table(definition).unwrap();
table
.insert("hello".to_string(), "world".to_string())
.unwrap();
}
write_txn.commit().unwrap();

let read_txn = db.begin_read().unwrap();
let table = read_txn.open_table(definition).unwrap();
assert_eq!(
"world",
table.get("hello".to_string()).unwrap().unwrap().value()
);

let mut iter = table.iter().unwrap();
assert_eq!(iter.next().unwrap().unwrap().1.value(), "world");
assert!(iter.next().is_none());

let mut iter: Range<String, String> = table.range("a".to_string().."z".to_string()).unwrap();
assert_eq!(iter.next().unwrap().unwrap().1.value(), "world");
assert!(iter.next().is_none());
}

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