Skip to content

Commit 88841d9

Browse files
committed
Add Reserve method for fixed-size write batches
1 parent ac69108 commit 88841d9

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

db/write_batch.cc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ void WriteBatch::Clear() {
3737
rep_.resize(kHeader);
3838
}
3939

40+
void WriteBatch::Reserve(size_t size) {
41+
rep_.reserve(size);
42+
}
43+
4044
size_t WriteBatch::ApproximateSize() const { return rep_.size(); }
4145

4246
Status WriteBatch::Iterate(Handler* handler) const {

db/write_batch_test.cc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,14 @@ TEST(WriteBatchTest, ApproximateSize) {
116116
WriteBatch batch;
117117
size_t empty_size = batch.ApproximateSize();
118118

119+
// Reserve space for multiple operations
120+
size_t expected_size = 35;
121+
batch.Reserve(expected_size);
122+
123+
// The approximate size should still be the same as empty
124+
// since Reserve doesn't affect the content size
125+
ASSERT_EQ(empty_size, batch.ApproximateSize());
126+
119127
batch.Put(Slice("foo"), Slice("bar"));
120128
size_t one_key_size = batch.ApproximateSize();
121129
ASSERT_LT(empty_size, one_key_size);
@@ -127,6 +135,8 @@ TEST(WriteBatchTest, ApproximateSize) {
127135
batch.Delete(Slice("box"));
128136
size_t post_delete_size = batch.ApproximateSize();
129137
ASSERT_LT(two_keys_size, post_delete_size);
138+
139+
ASSERT_EQ(expected_size, batch.ApproximateSize());
130140
}
131141

132142
} // namespace leveldb

include/leveldb/write_batch.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ class LEVELDB_EXPORT WriteBatch {
5656
// Clear all updates buffered in this batch.
5757
void Clear();
5858

59+
// Preallocate memory for a batch containing a sequence of updates.
60+
void Reserve(size_t size);
61+
5962
// The size of the database changes caused by this batch.
6063
//
6164
// This number is tied to implementation details, and may change across

0 commit comments

Comments
 (0)