Skip to content

Commit 802f8c8

Browse files
siparandom-zebra
authored andcommitted
Add SizeEstimate to CDBBatch
This allows estimating the in-memory size of a LevelDB batch.
1 parent af793b7 commit 802f8c8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/dbwrapper.h

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,22 @@ class CDBBatch
4848
private:
4949
leveldb::WriteBatch batch;
5050

51+
CDataStream ssKey;
52+
CDataStream ssValue;
53+
54+
size_t size_estimate;
55+
5156
public:
57+
/**
58+
* @param[in] _parent CDBWrapper that this batch is to be submitted to
59+
*/
60+
CDBBatch() : ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
61+
62+
void Clear()
63+
{
64+
batch.Clear();
65+
size_estimate = 0;
66+
}
5267

5368
template <typename K, typename V>
5469
void Write(const K& key, const V& value)
@@ -64,6 +79,17 @@ class CDBBatch
6479
leveldb::Slice slValue(&ssValue[0], ssValue.size());
6580

6681
batch.Put(slKey, slValue);
82+
83+
// LevelDB serializes writes as:
84+
// - byte: header
85+
// - varint: key length (1 byte up to 127B, 2 bytes up to 16383B, ...)
86+
// - byte[]: key
87+
// - varint: value length
88+
// - byte[]: value
89+
// The formula below assumes the key and value are both less than 16k.
90+
size_estimate += 3 + (slKey.size() > 127) + slKey.size() + (slValue.size() > 127) + slValue.size();
91+
ssKey.clear();
92+
ssValue.clear();
6793
}
6894

6995
template <typename K>
@@ -75,7 +101,17 @@ class CDBBatch
75101
leveldb::Slice slKey(&ssKey[0], ssKey.size());
76102

77103
batch.Delete(slKey);
104+
105+
// LevelDB serializes erases as:
106+
// - byte: header
107+
// - varint: key length
108+
// - byte[]: key
109+
// The formula below assumes the key is less than 16kB.
110+
size_estimate += 2 + (slKey.size() > 127) + slKey.size();
111+
ssKey.clear();
78112
}
113+
114+
size_t SizeEstimate() const { return size_estimate; }
79115
};
80116

81117
class CDBIterator

0 commit comments

Comments
 (0)