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#include <limits>
10
11struct MyData {
12 int id;
13 double value;
14
15 std::vector<uint8_t> to_bytes() const {
16 std::vector<uint8_t> bytes(sizeof(MyData));
17 std::memcpy(bytes.data(), this, sizeof(MyData));
18 return bytes;
19 }
20
21 static MyData from_bytes(const void* data, size_t size) {
22 if (size != sizeof(MyData))
23 throw std::runtime_error("Invalid data size for MyData");
24 MyData out;
25 std::memcpy(&out, data, sizeof(MyData));
26 return out;
27 }
28};
29
30int main() {
31 mdbxc::Config config;
32 config.pathname = "custom_struct_db";
33 config.max_dbs = 1;
34 auto conn = mdbxc::Connection::create(config);
35
36 mdbxc::KeyValueTable<int, MyData> table(conn, "my_data");
37 table.clear();
38 table.insert_or_assign(42, MyData{42, 3.14});
39# if __cplusplus >= 201703L
40 auto result = table.find(42);
41 if (result)
42 std::cout << "id: " << result->id << ", value: " << result->value << std::endl;
43# else
44 auto result = table.find_compat(42);
45 if (result.first)
46 std::cout << "id: " << result.second.id << ", value: " << result.second.value << std::endl;
47# endif
48
49 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
50 std::cin.get();
51}
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.
std::pair< bool, ValueT > find(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