[libc-commits] [libc] [libc] Implement vasprintf (PR #98824)

Joseph Huber via libc-commits libc-commits at lists.llvm.org
Sun Jul 14 11:18:05 PDT 2024


================
@@ -0,0 +1,74 @@
+//===-- Implementation of vasprintf -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/stdio/vasprintf.h"
+
+#include "src/__support/OSUtil/io.h"
+#include "src/__support/arg_list.h"
+#include "src/stdio/printf.h"
+#include "src/stdio/printf_core/core_structs.h"
+#include "src/stdio/printf_core/printf_main.h"
+#include "src/stdio/printf_core/writer.h"
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h> // malloc, realloc, free
+
+namespace LIBC_NAMESPACE {
+
+namespace {
+
+LIBC_INLINE int resize_overflow_hook(printf_core::WriteBuffer *wb,
+                                     cpp::string_view new_str) {
+  size_t NewSize = new_str.size() + wb->buff_cur;
+  char *TmpBuf =
+      static_cast<char *>(realloc(wb->buff, NewSize + 1)); // +1 for null
+  if (TmpBuf == nullptr) {
+    return printf_core::FILE_WRITE_ERROR;
+  }
+  wb->buff = TmpBuf;
+  inline_memcpy(wb->buff + wb->buff_cur, new_str.data(), new_str.size());
+  wb->buff_cur = NewSize;
+  wb->buff_len = NewSize;
+  return printf_core::WRITE_OK;
+}
+
+} // namespace
+
+LLVM_LIBC_FUNCTION(int, vasprintf,
+                   (char **__restrict ret, const char *format, va_list vlist)) {
+  internal::ArgList args(vlist); // This holder class allows for easier copying
+                                 // and pointer semantics, as well as handling
+                                 // destruction automatically.
+  const uint16_t defaultSize = 200;
----------------
jhuber6 wrote:

This should probably be a constexpr global, doubt we need to dedicate a config macro for it. Also I don't think there's a need for `uint16_t`.

https://github.com/llvm/llvm-project/pull/98824


More information about the libc-commits mailing list