1*9f1d905fSMichael Jones //===-- Implementation of snprintf ------------------------------*- C++ -*-===// 2*9f1d905fSMichael Jones // 3*9f1d905fSMichael Jones // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*9f1d905fSMichael Jones // See https://llvm.org/LICENSE.txt for license information. 5*9f1d905fSMichael Jones // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*9f1d905fSMichael Jones // 7*9f1d905fSMichael Jones //===----------------------------------------------------------------------===// 8*9f1d905fSMichael Jones 9*9f1d905fSMichael Jones #include "src/stdio/snprintf.h" 10*9f1d905fSMichael Jones 11*9f1d905fSMichael Jones #include "src/__support/arg_list.h" 12*9f1d905fSMichael Jones #include "src/stdio/printf_core/printf_main.h" 13*9f1d905fSMichael Jones #include "src/stdio/printf_core/string_writer.h" 14*9f1d905fSMichael Jones #include "src/stdio/printf_core/writer.h" 15*9f1d905fSMichael Jones 16*9f1d905fSMichael Jones #include <stdarg.h> 17*9f1d905fSMichael Jones #include <stddef.h> 18*9f1d905fSMichael Jones 19*9f1d905fSMichael Jones namespace __llvm_libc { 20*9f1d905fSMichael Jones 21*9f1d905fSMichael Jones LLVM_LIBC_FUNCTION(int, snprintf, 22*9f1d905fSMichael Jones (char *__restrict buffer, size_t buffsz, 23*9f1d905fSMichael Jones const char *__restrict format, ...)) { 24*9f1d905fSMichael Jones va_list vlist; 25*9f1d905fSMichael Jones va_start(vlist, format); 26*9f1d905fSMichael Jones internal::ArgList args(vlist); // This holder class allows for easier copying 27*9f1d905fSMichael Jones // and pointer semantics, as well as handling 28*9f1d905fSMichael Jones // destruction automatically. 29*9f1d905fSMichael Jones va_end(vlist); 30*9f1d905fSMichael Jones printf_core::StringWriter str_writer(buffer, (buffsz > 0 ? buffsz - 1 : 0)); 31*9f1d905fSMichael Jones printf_core::Writer writer(reinterpret_cast<void *>(&str_writer), 32*9f1d905fSMichael Jones printf_core::write_to_string); 33*9f1d905fSMichael Jones 34*9f1d905fSMichael Jones int ret_val = printf_core::printf_main(&writer, format, args); 35*9f1d905fSMichael Jones if (buffsz > 0) // if the buffsz is 0 the buffer may be a null pointer. 36*9f1d905fSMichael Jones str_writer.terminate(); 37*9f1d905fSMichael Jones return ret_val; 38*9f1d905fSMichael Jones } 39*9f1d905fSMichael Jones 40*9f1d905fSMichael Jones } // namespace __llvm_libc 41