MDBX Containers
Loading...
Searching...
No Matches
custom_struct_example.cpp
Go to the documentation of this file.
1
5
7#include <iostream>
8#include <vector>
9
10struct MyData {
11 int id;
12 double value;
13
14 std::vector<uint8_t> to_bytes() const {
15 std::vector<uint8_t> bytes(sizeof(MyData));
16 std::memcpy(bytes.data(), this, sizeof(MyData));
17 return bytes;
18 }
19
20 static MyData from_bytes(const void* data, size_t size) {
21 if (size != sizeof(MyData))
22 throw std::runtime_error("Invalid data size for MyData");
23 MyData out;
24 std::memcpy(&out, data, sizeof(MyData));
25 return out;
26 }
27};
28
29int main() {
30 mdbxc::Config config;
31 config.pathname = "custom_struct_db";
32 config.max_dbs = 1;
33 auto conn = mdbxc::Connection::create(config);
34
35 mdbxc::KeyValueTable<int, MyData> table(conn, "my_data");
36 table.clear();
37 table.insert_or_assign(42, MyData{42, 3.14});
38# if __cplusplus >= 201703L
39 auto result = table.find(42);
40 if (result)
41 std::cout << "id: " << result->id << ", value: " << result->value << std::endl;
42# else
43 auto result = table.find_compat(42);
44 if (result.first)
45 std::cout << "id: " << result.second.id << ", value: " << result.second.value << std::endl;
46# endif
47}
Declaration of the KeyValueTable class for managing key-value pairs in an MDBX database.
Parameters used by Connection to create the MDBX environment.
Definition Config.hpp:17
std::string pathname
Path to the database file or directory containing the database.
Definition Config.hpp:19
int64_t max_dbs
Maximum number of named databases (DBI) in the environment.
Definition Config.hpp:27
static std::shared_ptr< Connection > create(const Config &config)
Creates and connects a new shared Connection instance.
Template class for managing key-value pairs in an MDBX database.
void insert_or_assign(const KeyT &key, const ValueT &value, MDBX_txn *txn=nullptr)
Inserts or replaces key-value pair.
std::pair< bool, ValueT > find_compat(const KeyT &key, MDBX_txn *txn=nullptr) const
Finds value by key.
void clear(MDBX_txn *txn=nullptr)
Clears all key-value pairs from the database.
Storing a custom struct with to_bytes/from_bytes.
static MyData from_bytes(const void *data, size_t size)
std::vector< uint8_t > to_bytes() const