xref: /aosp_15_r20/external/llvm-libc/src/stdio/printf_core/string_converter.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- String Converter 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_CONVERTER_H
10 #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_CONVERTER_H
11 
12 #include "src/__support/CPP/string_view.h"
13 #include "src/__support/macros/config.h"
14 #include "src/stdio/printf_core/converter_utils.h"
15 #include "src/stdio/printf_core/core_structs.h"
16 #include "src/stdio/printf_core/writer.h"
17 
18 #include <stddef.h>
19 
20 namespace LIBC_NAMESPACE_DECL {
21 namespace printf_core {
22 
convert_string(Writer * writer,const FormatSection & to_conv)23 LIBC_INLINE int convert_string(Writer *writer, const FormatSection &to_conv) {
24   size_t string_len = 0;
25   const char *str_ptr = reinterpret_cast<const char *>(to_conv.conv_val_ptr);
26 
27 #ifndef LIBC_COPT_PRINTF_NO_NULLPTR_CHECKS
28   if (str_ptr == nullptr) {
29     str_ptr = "(null)";
30   }
31 #endif // LIBC_COPT_PRINTF_NO_NULLPTR_CHECKS
32 
33   for (const char *cur_str = (str_ptr); cur_str[string_len]; ++string_len) {
34     ;
35   }
36 
37   if (to_conv.precision >= 0 &&
38       static_cast<size_t>(to_conv.precision) < string_len)
39     string_len = to_conv.precision;
40 
41   size_t padding_spaces = to_conv.min_width > static_cast<int>(string_len)
42                               ? to_conv.min_width - string_len
43                               : 0;
44 
45   // If the padding is on the left side, write the spaces first.
46   if (padding_spaces > 0 &&
47       (to_conv.flags & FormatFlags::LEFT_JUSTIFIED) == 0) {
48     RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_spaces));
49   }
50 
51   RET_IF_RESULT_NEGATIVE(writer->write({(str_ptr), string_len}));
52 
53   // If the padding is on the right side, write the spaces last.
54   if (padding_spaces > 0 &&
55       (to_conv.flags & FormatFlags::LEFT_JUSTIFIED) != 0) {
56     RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_spaces));
57   }
58   return WRITE_OK;
59 }
60 
61 } // namespace printf_core
62 } // namespace LIBC_NAMESPACE_DECL
63 
64 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_CONVERTER_H
65