57 lines · cpp
1//===-- Implementation of snprintf ------------------------------*- 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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/stdio/snprintf.h"10 11#include "src/__support/CPP/limits.h"12#include "src/__support/arg_list.h"13#include "src/__support/libc_errno.h"14#include "src/__support/macros/config.h"15#include "src/stdio/printf_core/core_structs.h"16#include "src/stdio/printf_core/error_mapper.h"17#include "src/stdio/printf_core/printf_main.h"18#include "src/stdio/printf_core/writer.h"19 20#include <stdarg.h>21#include <stddef.h>22 23namespace LIBC_NAMESPACE_DECL {24 25LLVM_LIBC_FUNCTION(int, snprintf,26 (char *__restrict buffer, size_t buffsz,27 const char *__restrict format, ...)) {28 va_list vlist;29 va_start(vlist, format);30 internal::ArgList args(vlist); // This holder class allows for easier copying31 // and pointer semantics, as well as handling32 // destruction automatically.33 va_end(vlist);34 printf_core::WriteBuffer<printf_core::Mode<35 printf_core::WriteMode::FILL_BUFF_AND_DROP_OVERFLOW>::value>36 wb(buffer, (buffsz > 0 ? buffsz - 1 : 0));37 printf_core::Writer writer(wb);38 39 auto ret_val = printf_core::printf_main(&writer, format, args);40 if (!ret_val.has_value()) {41 libc_errno = printf_core::internal_error_to_errno(ret_val.error());42 return -1;43 }44 if (buffsz > 0) // if the buffsz is 0 the buffer may be a null pointer.45 wb.buff[wb.buff_cur] = '\0';46 47 if (ret_val.value() > static_cast<size_t>(cpp::numeric_limits<int>::max())) {48 libc_errno =49 printf_core::internal_error_to_errno(-printf_core::OVERFLOW_ERROR);50 return -1;51 }52 53 return static_cast<int>(ret_val.value());54}55 56} // namespace LIBC_NAMESPACE_DECL57