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