[PATCH] D91693: [Support] Add reserve() method to the raw_ostream.

Alexey Lapshin via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Feb 22 10:34:46 PST 2021


avl updated this revision to Diff 325488.
avl edited the summary of this revision.
avl added a comment.

change reserve() to reserveExtraSpace(). That allows pre-allocating 
the internal stream buffers without knowing its current size.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D91693/new/

https://reviews.llvm.org/D91693

Files:
  llvm/include/llvm/Support/raw_ostream.h
  llvm/unittests/Support/raw_ostream_test.cpp


Index: llvm/unittests/Support/raw_ostream_test.cpp
===================================================================
--- llvm/unittests/Support/raw_ostream_test.cpp
+++ llvm/unittests/Support/raw_ostream_test.cpp
@@ -455,4 +455,17 @@
   TiedStream << "0";
   EXPECT_EQ("acegostuv", TiedToBuffer);
 }
+
+TEST(raw_ostreamTest, reserve_stream) {
+  std::string Str;
+  raw_string_ostream OS(Str);
+  uint64_t CurrentPos = OS.tell();
+  OS.reserveExtraSpace(1000);
+  EXPECT_TRUE(Str.capacity() >= CurrentPos + 1000);
+  OS << "hello";
+  OS << 1;
+  OS << 'w' << 'o' << 'r' << 'l' << 'd';
+  OS.flush();
+  EXPECT_EQ("hello1world", Str);
+}
 }
Index: llvm/include/llvm/Support/raw_ostream.h
===================================================================
--- llvm/include/llvm/Support/raw_ostream.h
+++ llvm/include/llvm/Support/raw_ostream.h
@@ -137,6 +137,13 @@
   // Configuration Interface
   //===--------------------------------------------------------------------===//
 
+  /// If possible, pre-allocate \p ExtraSize bytes for stream data.
+  /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
+  /// So that the stream could keep at least tell() + ExtraSize bytes
+  /// without re-allocations. reserveExtraSpace() does not change
+  /// the size/data of the stream.
+  virtual void reserveExtraSpace(uint64_t ExtraSize) {}
+
   /// Set the stream to be buffered, with an automatically determined buffer
   /// size.
   void SetBuffered();
@@ -626,6 +633,10 @@
     flush();
     return OS;
   }
+
+  void reserveExtraSpace(uint64_t ExtraSize) override {
+    OS.reserve(tell() + ExtraSize);
+  }
 };
 
 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
@@ -659,6 +670,10 @@
 
   /// Return a StringRef for the vector contents.
   StringRef str() const { return StringRef(OS.data(), OS.size()); }
+
+  void reserveExtraSpace(uint64_t ExtraSize) override {
+    OS.reserve(tell() + ExtraSize);
+  }
 };
 
 /// A raw_ostream that discards all output.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D91693.325488.patch
Type: text/x-patch
Size: 2007 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210222/94d32021/attachment.bin>


More information about the llvm-commits mailing list