68 lines · cpp
1//===-- Implementation of vprintf -------------------------------*- 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/vprintf.h"10#include "src/__support/CPP/limits.h"11#include "src/__support/OSUtil/io.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 25namespace {26 27LIBC_INLINE int stdout_write_hook(cpp::string_view new_str, void *) {28 write_to_stdout(new_str);29 return printf_core::WRITE_OK;30}31 32} // namespace33 34LLVM_LIBC_FUNCTION(int, vprintf,35 (const char *__restrict format, va_list vlist)) {36 internal::ArgList args(vlist); // This holder class allows for easier copying37 // and pointer semantics, as well as handling38 // destruction automatically.39 static constexpr size_t BUFF_SIZE = 1024;40 char buffer[BUFF_SIZE];41 42 printf_core::WriteBuffer<printf_core::WriteMode::FLUSH_TO_STREAM> wb(43 buffer, BUFF_SIZE, &stdout_write_hook, nullptr);44 printf_core::Writer<printf_core::WriteMode::FLUSH_TO_STREAM> writer(wb);45 46 auto retval = printf_core::printf_main(&writer, format, args);47 if (!retval.has_value()) {48 libc_errno = printf_core::internal_error_to_errno(retval.error());49 return -1;50 }51 52 int flushval = wb.overflow_write("");53 if (flushval != printf_core::WRITE_OK) {54 libc_errno = printf_core::internal_error_to_errno(-flushval);55 return -1;56 }57 58 if (retval.value() > static_cast<size_t>(cpp::numeric_limits<int>::max())) {59 libc_errno =60 printf_core::internal_error_to_errno(-printf_core::OVERFLOW_ERROR);61 return -1;62 }63 64 return static_cast<int>(retval.value());65}66 67} // namespace LIBC_NAMESPACE_DECL68