From 67376234b192cfe77a67a82eef06e2c17a913e3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C5=91rinc?= Date: Mon, 24 Mar 2025 14:32:30 +0100 Subject: [PATCH] Add `Reserve` method for fixed-size write batches --- db/write_batch.cc | 4 ++++ db/write_batch_test.cc | 10 ++++++++++ include/leveldb/write_batch.h | 3 +++ 3 files changed, 17 insertions(+) diff --git a/db/write_batch.cc b/db/write_batch.cc index b54313c35e..9d89e5ee0e 100644 --- a/db/write_batch.cc +++ b/db/write_batch.cc @@ -37,6 +37,10 @@ void WriteBatch::Clear() { rep_.resize(kHeader); } +void WriteBatch::Reserve(size_t size) { + rep_.reserve(size); +} + size_t WriteBatch::ApproximateSize() const { return rep_.size(); } Status WriteBatch::Iterate(Handler* handler) const { diff --git a/db/write_batch_test.cc b/db/write_batch_test.cc index c32317fb5e..96153fec78 100644 --- a/db/write_batch_test.cc +++ b/db/write_batch_test.cc @@ -119,6 +119,14 @@ TEST(WriteBatchTest, ApproximateSize) { WriteBatch batch; size_t empty_size = batch.ApproximateSize(); + // Reserve space for multiple operations + size_t expected_size = 35; + batch.Reserve(expected_size); + + // The approximate size should still be the same as empty + // since Reserve doesn't affect the content size + ASSERT_EQ(empty_size, batch.ApproximateSize()); + batch.Put(Slice("foo"), Slice("bar")); size_t one_key_size = batch.ApproximateSize(); ASSERT_LT(empty_size, one_key_size); @@ -130,6 +138,8 @@ TEST(WriteBatchTest, ApproximateSize) { batch.Delete(Slice("box")); size_t post_delete_size = batch.ApproximateSize(); ASSERT_LT(two_keys_size, post_delete_size); + + ASSERT_EQ(expected_size, batch.ApproximateSize()); } } // namespace leveldb diff --git a/include/leveldb/write_batch.h b/include/leveldb/write_batch.h index 94d4115fed..b9e7c59ee7 100644 --- a/include/leveldb/write_batch.h +++ b/include/leveldb/write_batch.h @@ -56,6 +56,9 @@ class LEVELDB_EXPORT WriteBatch { // Clear all updates buffered in this batch. void Clear(); + // Preallocate memory for a batch containing a sequence of updates. + void Reserve(size_t size); + // The size of the database changes caused by this batch. // // This number is tied to implementation details, and may change across