@@ -55,11 +55,19 @@ class CDBBatch
5555 CDataStream ssKey;
5656 CDataStream ssValue;
5757
58+ size_t size_estimate;
59+
5860public:
5961 /* *
6062 * @param[in] _parent CDBWrapper that this batch is to be submitted to
6163 */
62- CDBBatch (const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION) { };
64+ CDBBatch (const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0 ) { };
65+
66+ void Clear ()
67+ {
68+ batch.Clear ();
69+ size_estimate = 0 ;
70+ }
6371
6472 template <typename K, typename V>
6573 void Write (const K& key, const V& value)
@@ -74,6 +82,14 @@ class CDBBatch
7482 leveldb::Slice slValue (ssValue.data (), ssValue.size ());
7583
7684 batch.Put (slKey, slValue);
85+ // LevelDB serializes writes as:
86+ // - byte: header
87+ // - varint: key length (1 byte up to 127B, 2 bytes up to 16383B, ...)
88+ // - byte[]: key
89+ // - varint: value length
90+ // - byte[]: value
91+ // The formula below assumes the key and value are both less than 16k.
92+ size_estimate += 3 + (slKey.size () > 127 ) + slKey.size () + (slValue.size () > 127 ) + slValue.size ();
7793 ssKey.clear ();
7894 ssValue.clear ();
7995 }
@@ -86,8 +102,16 @@ class CDBBatch
86102 leveldb::Slice slKey (ssKey.data (), ssKey.size ());
87103
88104 batch.Delete (slKey);
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 ();
89111 ssKey.clear ();
90112 }
113+
114+ size_t SizeEstimate () const { return size_estimate; }
91115};
92116
93117class CDBIterator
0 commit comments