在 RocksDB 中存储任意字节

jim*_*pez 4 rocksdb

RocksDB 表示它可以存储任意数据,但 API 仅支持std::string类型。我想存储std::vector<T>值,如果我想这样做,那么我必须将它转换为std::string.

有没有一种不那么脆弱的方式来存储任意类型?

Ben*_*enj 5

我倾向于使用以下使用模板将结构/类打包/解包到 std::string 以自动调整到它们的大小。

template <typename T>
std::string Pack(const T* data)
{
    std::string d(sizeof(T), L'\0');
    memcpy(&d[0], data, d.size());
    return d;
}

template <typename T>
std::unique_ptr<T> Unpack(const std::string& data)
{
    if (data.size() != sizeof(T))
        return nullptr;

    auto d = std::make_unique<T>();
    memcpy(d.get(), data.data(), data.size());
    return d;
}
Run Code Online (Sandbox Code Playgroud)

所以下面的客户端代码可以将一个结构打包和解包到数据库中:

    // Test structure
    BOB b = {};
    b.a = 12;
    b.b = 144;
    b.c[0] = 's';
    b.c[1] = '\0';

    // Write to the db
    status = pDb->Put(rocksdb::WriteOptions(), key, Pack(&b));

    // Read from db with same key
    std::string result;
    status = pDb->Get(rocksdb::ReadOptions(), key, &result);
    std::unique_ptr<BOB> pBob = Unpack<BOB>(result);

    if (b.a == pBob->a && b.b == pBob->b && b.c[0] == pBob->c[0])
    {
        printf("Structure matches!\n");
    }
    else
    {
        printf("Structure doesn't match!\n");
    }
Run Code Online (Sandbox Code Playgroud)