xref: /aosp_15_r20/external/llvm-libc/src/stdio/sprintf.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Implementation of sprintf -------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/stdio/sprintf.h"
10 
11 #include "src/__support/CPP/limits.h"
12 #include "src/__support/arg_list.h"
13 #include "src/__support/macros/config.h"
14 #include "src/stdio/printf_core/printf_main.h"
15 #include "src/stdio/printf_core/writer.h"
16 
17 #include <stdarg.h>
18 
19 namespace LIBC_NAMESPACE_DECL {
20 
21 LLVM_LIBC_FUNCTION(int, sprintf,
22                    (char *__restrict buffer, const char *__restrict format,
23                     ...)) {
24   va_list vlist;
25   va_start(vlist, format);
26   internal::ArgList args(vlist); // This holder class allows for easier copying
27                                  // and pointer semantics, as well as handling
28                                  // destruction automatically.
29   va_end(vlist);
30 
31   printf_core::WriteBuffer wb(buffer, cpp::numeric_limits<size_t>::max());
32   printf_core::Writer writer(&wb);
33 
34   int ret_val = printf_core::printf_main(&writer, format, args);
35   wb.buff[wb.buff_cur] = '\0';
36   return ret_val;
37 }
38 
39 } // namespace LIBC_NAMESPACE_DECL
40