|
| 1 | +//===-- Implementation of scanf ---------------------------------*- 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/scanf.h" |
| 10 | + |
| 11 | +#include "hdr/stdio_macros.h" |
| 12 | +#include "src/__support/OSUtil/io.h" |
| 13 | +#include "src/__support/arg_list.h" |
| 14 | +#include "src/__support/macros/config.h" |
| 15 | +#include "src/stdio/scanf_core/reader.h" |
| 16 | +#include "src/stdio/scanf_core/scanf_main.h" |
| 17 | + |
| 18 | +#include <stdarg.h> |
| 19 | + |
| 20 | +namespace LIBC_NAMESPACE_DECL { |
| 21 | + |
| 22 | +namespace { |
| 23 | + |
| 24 | +struct StreamBuffer : scanf_core::ReadBuffer<StreamBuffer> { |
| 25 | + LIBC_INLINE char getc() { |
| 26 | + char buf[1]; |
| 27 | + read_from_stdin(buf, sizeof(buf)); |
| 28 | + return buf[0]; |
| 29 | + } |
| 30 | + LIBC_INLINE void ungetc(int) {} |
| 31 | +}; |
| 32 | + |
| 33 | +} // namespace |
| 34 | + |
| 35 | +LLVM_LIBC_FUNCTION(int, scanf, (const char *__restrict format, ...)) { |
| 36 | + va_list vlist; |
| 37 | + va_start(vlist, format); |
| 38 | + internal::ArgList args(vlist); // This holder class allows for easier copying |
| 39 | + // and pointer semantics, as well as handling |
| 40 | + // destruction automatically. |
| 41 | + va_end(vlist); |
| 42 | + |
| 43 | + StreamBuffer buffer; |
| 44 | + scanf_core::Reader<StreamBuffer> reader(&buffer); |
| 45 | + |
| 46 | + int retval = scanf_core::scanf_main(&reader, format, args); |
| 47 | + // This is done to avoid including stdio.h in the internals. On most systems |
| 48 | + // EOF is -1, so this will be transformed into just "return retval". |
| 49 | + return (retval == -1) ? EOF : retval; |
| 50 | +} |
| 51 | + |
| 52 | +} // namespace LIBC_NAMESPACE_DECL |
0 commit comments