1 //===-- String Writer class 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))
27       : cur_buffer(buffer), available_capacity(max_len) {}
28 
29   void write(const char *__restrict to_write, size_t len) {
30     if (len > available_capacity)
31       len = available_capacity;
32 
33     if (len > 0) {
34       inline_memcpy(cur_buffer, to_write, len);
35       cur_buffer += len;
36       available_capacity -= len;
37     }
38   }
39   // Terminate should only be called if the original max length passed to
40   // snprintf was greater than 0. It writes a null byte to the end of the
41   // cur_buffer, regardless of available_capacity.
42   void terminate() { *cur_buffer = '\0'; }
43 };
44 
45 // write_to_string treats raw_pointer as a StringWriter and calls its write
46 // function.
47 void write_to_string(void *raw_pointer, const char *__restrict to_write,
48                      size_t len) {
49   StringWriter *string_writer = reinterpret_cast<StringWriter *>(raw_pointer);
50   string_writer->write(to_write, len);
51 }
52 
53 } // namespace printf_core
54 } // namespace __llvm_libc
55 
56 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_WRITER_H
57