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