【问题标题】:Storing arbitrary bytes in RocksDB在 RocksDB 中存储任意字节
【发布时间】:2015-07-22 14:10:10
【问题描述】:

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

有没有更简单的方法来存储任意类型?

【问题讨论】:

    标签: rocksdb


    【解决方案1】:

    我倾向于使用以下内容将结构/类打包/解包到 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;
    }
    

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

        // 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");
        }
    

    【讨论】:

      【解决方案2】:

      作为键值存储,RocksDB 可以存储“任意字节数组”。对于您的用例,您需要有某种方法将您的std::vector&lt;T&gt; 序列化为字节数组,以便可以将其放入std::string。请注意,输入 std::string 不需要以零结尾。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多