浏览代码

LibC: Implement asprintf() and vasprintf()

These simply use StringBuilder::appendvf() internally which is not
optimal in terms of heap allocations, but simple enough and I don't
think they are performance sensitive functions anyway.
Andreas Kling 4 年之前
父节点
当前提交
fdd01a0a07
共有 2 个文件被更改,包括 27 次插入1 次删除
  1. 24 0
      Userland/Libraries/LibC/stdio.cpp
  2. 3 1
      Userland/Libraries/LibC/stdio.h

+ 24 - 0
Userland/Libraries/LibC/stdio.cpp

@@ -29,6 +29,7 @@
 #include <AK/PrintfImplementation.h>
 #include <AK/ScopedValueRollback.h>
 #include <AK/StdLibExtras.h>
+#include <AK/String.h>
 #include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -880,6 +881,29 @@ int printf(const char* fmt, ...)
     return ret;
 }
 
+int vasprintf(char** strp, const char* fmt, va_list ap)
+{
+    StringBuilder builder;
+    builder.appendvf(fmt, ap);
+    VERIFY(builder.length() <= NumericLimits<int>::max());
+    int length = builder.length();
+    *strp = strdup(builder.to_string().characters());
+    return length;
+}
+
+int asprintf(char** strp, const char* fmt, ...)
+{
+    StringBuilder builder;
+    va_list ap;
+    va_start(ap, fmt);
+    builder.appendvf(fmt, ap);
+    va_end(ap);
+    VERIFY(builder.length() <= NumericLimits<int>::max());
+    int length = builder.length();
+    *strp = strdup(builder.to_string().characters());
+    return length;
+}
+
 static void buffer_putch(char*& bufptr, char ch)
 {
     *bufptr++ = ch;

+ 3 - 1
Userland/Libraries/LibC/stdio.h

@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
+ * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -89,6 +89,7 @@ size_t fread(void* ptr, size_t size, size_t nmemb, FILE*);
 size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE*);
 int vprintf(const char* fmt, va_list) __attribute__((format(printf, 1, 0)));
 int vfprintf(FILE*, const char* fmt, va_list) __attribute__((format(printf, 2, 0)));
+int vasprintf(char** strp, const char* fmt, va_list) __attribute__((format(printf, 2, 0)));
 int vsprintf(char* buffer, const char* fmt, va_list) __attribute__((format(printf, 2, 0)));
 int vsnprintf(char* buffer, size_t, const char* fmt, va_list) __attribute__((format(printf, 3, 0)));
 int fprintf(FILE*, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
@@ -96,6 +97,7 @@ int printf(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
 void dbgputch(char);
 void dbgputstr(const char*, size_t);
 int sprintf(char* buffer, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
+int asprintf(char** strp, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
 int snprintf(char* buffer, size_t, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
 int putchar(int ch);
 int putc(int ch, FILE*);