1 //===-- Writer definition for printf ----------------------------*- 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_PRINTF_CORE_WRITER_H
10 #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_WRITER_H
11 
12 #include <stddef.h>
13 
14 namespace __llvm_libc {
15 namespace printf_core {
16 
17 using WriteFunc = int (*)(void *, const char *__restrict, size_t);
18 
19 class Writer final {
20   // output is a pointer to the string or file that the writer is meant to write
21   // to.
22   void *output;
23 
24   // raw_write is a function that, when called on output with a char* and
25   // length, will copy the number of bytes equal to the length from the char*
26   // onto the end of output. It should return a positive number or zero on
27   // success, or a negative number on failure.
28   WriteFunc raw_write;
29 
30   int chars_written = 0;
31 
32 public:
Writer(void * init_output,WriteFunc init_raw_write)33   Writer(void *init_output, WriteFunc init_raw_write)
34       : output(init_output), raw_write(init_raw_write) {}
35 
36   // write will copy length bytes from new_string into output using
37   // raw_write. It increments chars_written by length always. It returns the
38   // result of raw_write.
39   int write(const char *new_string, size_t length);
40 
41   // write_chars will copy length copies of new_char into output using the write
42   // function and a statically sized buffer. This is primarily used for padding.
43   // If write returns a negative value, this will return early with that value.
44   int write_chars(char new_char, size_t length);
45 
get_chars_written()46   int get_chars_written() { return chars_written; }
47 };
48 
49 } // namespace printf_core
50 } // namespace __llvm_libc
51 
52 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_WRITER_H
53