|
| 1 | +//===-- Reader definition for 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 | +#ifndef LLVM_LIBC_SRC_STDIO_SCANF_CORE_STRING_READER_H |
| 10 | +#define LLVM_LIBC_SRC_STDIO_SCANF_CORE_STRING_READER_H |
| 11 | + |
| 12 | +#include "src/__support/macros/attributes.h" // For LIBC_INLINE |
| 13 | +#include "src/__support/macros/config.h" |
| 14 | +#include "src/stdio/scanf_core/reader.h" |
| 15 | + |
| 16 | +#include <stddef.h> |
| 17 | + |
| 18 | +namespace LIBC_NAMESPACE_DECL { |
| 19 | +namespace scanf_core { |
| 20 | + |
| 21 | +class StringReader : public Reader<StringReader> { |
| 22 | + const char *buffer; |
| 23 | + [[maybe_unused]] size_t buff_len; |
| 24 | + size_t buff_cur = 0; |
| 25 | + |
| 26 | +public: |
| 27 | + LIBC_INLINE StringReader(const char *buffer, size_t buff_len) |
| 28 | + : buffer(buffer), buff_len(buff_len) {} |
| 29 | + |
| 30 | + LIBC_INLINE char getc() { |
| 31 | + char output = buffer[buff_cur]; |
| 32 | + ++buff_cur; |
| 33 | + return output; |
| 34 | + } |
| 35 | + LIBC_INLINE void ungetc(int) { |
| 36 | + if (buff_cur > 0) { |
| 37 | + // While technically c should be written back to the buffer, in scanf we |
| 38 | + // always write the character that was already there. Additionally, the |
| 39 | + // buffer is most likely to contain a string that isn't part of a file, |
| 40 | + // which may not be writable. |
| 41 | + --buff_cur; |
| 42 | + } |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | +} // namespace scanf_core |
| 47 | +} // namespace LIBC_NAMESPACE_DECL |
| 48 | + |
| 49 | +#endif // LLVM_LIBC_SRC_STDIO_SCANF_CORE_STRING_READER_H |
0 commit comments