Revert "[demangler] Simplify OutputBuffer initialization"

Reverting due to a bot failure:
https://lab.llvm.org/buildbot/#/builders/5/builds/22738

This reverts commit 5b3ca24a35e91bf9c19af856e7f92c69b17f989e.

GitOrigin-RevId: aabeb5eb7f0aaa2c80147d904959c882cdeba1e5
diff --git a/src/cxa_demangle.cpp b/src/cxa_demangle.cpp
index 7baac68..ddab6d3 100644
--- a/src/cxa_demangle.cpp
+++ b/src/cxa_demangle.cpp
@@ -386,12 +386,15 @@
 
   int InternalStatus = demangle_success;
   Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
+  OutputBuffer O;
+
   Node *AST = Parser.parse();
 
   if (AST == nullptr)
     InternalStatus = demangle_invalid_mangled_name;
+  else if (!initializeOutputBuffer(Buf, N, O, 1024))
+    InternalStatus = demangle_memory_alloc_failure;
   else {
-    OutputBuffer O(Buf, N);
     assert(Parser.ForwardTemplateRefs.empty());
     AST->print(O);
     O += '\0';
diff --git a/src/demangle/Utility.h b/src/demangle/Utility.h
index 0057288..6e0fa38 100644
--- a/src/demangle/Utility.h
+++ b/src/demangle/Utility.h
@@ -69,9 +69,7 @@
 
 public:
   OutputBuffer(char *StartBuf, size_t Size)
-      : Buffer(StartBuf), BufferCapacity(Size) {}
-  OutputBuffer(char *StartBuf, size_t *SizePtr)
-      : OutputBuffer(StartBuf, StartBuf ? *SizePtr : 0) {}
+      : Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {}
   OutputBuffer() = default;
   // Non-copyable
   OutputBuffer(const OutputBuffer &) = delete;
@@ -79,6 +77,12 @@
 
   operator StringView() const { return StringView(Buffer, CurrentPosition); }
 
+  void reset(char *Buffer_, size_t BufferCapacity_) {
+    CurrentPosition = 0;
+    Buffer = Buffer_;
+    BufferCapacity = BufferCapacity_;
+  }
+
   /// If a ParameterPackExpansion (or similar type) is encountered, the offset
   /// into the pack that we're currently printing.
   unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max();
@@ -193,6 +197,21 @@
   ScopedOverride &operator=(const ScopedOverride &) = delete;
 };
 
+inline bool initializeOutputBuffer(char *Buf, size_t *N, OutputBuffer &OB,
+                                   size_t InitSize) {
+  size_t BufferSize;
+  if (Buf == nullptr) {
+    Buf = static_cast<char *>(std::malloc(InitSize));
+    if (Buf == nullptr)
+      return false;
+    BufferSize = InitSize;
+  } else
+    BufferSize = *N;
+
+  OB.reset(Buf, BufferSize);
+  return true;
+}
+
 DEMANGLE_NAMESPACE_END
 
 #endif