google / leveldb

LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.
BSD 3-Clause "New" or "Revised" License
36.51k stars 7.81k forks source link

Question: how to cast to int #1203

Open fadhil-riyanto opened 2 months ago

fadhil-riyanto commented 2 months ago

Hi, I have following map

std::map<std::string, int> db;

which in future, I want load data from leveldb to the memory by looping all of keys and insert to the std::map, I was do this

leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());

for (it->SeekToFirst(); it->Valid(); it->Next()) {
        db.insert(
                {
                        it->key().ToString(),
                        it->value()
                }
        );
}
assert(it->status().ok());

which get the key as string, then get the value. my question how do I can cast back the "value" to int?

paweenwich commented 1 month ago

For me, depend on how to you put data in LevelDB if you put it as string (Ex. "1234" for 1234) then just convert parse it bact it int if you put it as int32_t's binary (Ex 00 00 00 0F for 15) then just cast to back from string.data() to int32_t* and then copy to any where you like.

fadhil-riyanto commented 1 month ago

I think converting the data back to int is little bit slow. But thanks for your reply and time!!

Amr-Shams commented 1 month ago

you simply can't do this unless you cast or decod which is not recommended in many cases espically if you are sending this through and responce it is better to be bytes and then casted in the presentation layer