1 //===-- String 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_STRING_WRITER_H
10 #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_WRITER_H
11 
12 #include "src/string/memory_utils/memcpy_implementations.h"
13 #include <stddef.h>
14 
15 namespace __llvm_libc {
16 namespace printf_core {
17 
18 class StringWriter {
19   char *__restrict cur_buffer;
20   size_t available_capacity;
21 
22 public:
23   // StringWriter is intended to take a copy of the cur_buffer pointer, as well
24   // as the maximum length of the string. This maximum length should not include
25   // the null terminator, since that's written separately.
26   StringWriter(char *__restrict buffer, size_t max_len = ~size_t(0))
cur_buffer(buffer)27       : cur_buffer(buffer), available_capacity(max_len) {}
28 
29   void write(const char *__restrict to_write, size_t len);
30 
31   // Terminate should only be called if the original max length passed to
32   // snprintf was greater than 0. It writes a null byte to the end of the
33   // cur_buffer, regardless of available_capacity.
terminate()34   void terminate() { *cur_buffer = '\0'; }
35 };
36 
37 // write_to_string treats raw_pointer as a StringWriter and calls its write
38 // function.
39 int write_to_string(void *raw_pointer, const char *__restrict to_write,
40                     size_t len);
41 
42 } // namespace printf_core
43 } // namespace __llvm_libc
44 
45 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_WRITER_H
46