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/stdio/printf_core/core_structs.h"
13 #include "src/stdio/printf_core/writer.h"
14 
15 #include <stddef.h>
16 
17 namespace __llvm_libc {
18 namespace printf_core {
19 
20 int inline convert_string(Writer *writer, const FormatSection &to_conv) {
21   int string_len = 0;
22 
23   for (char *cur_str = reinterpret_cast<char *>(to_conv.conv_val_ptr);
24        cur_str[string_len]; ++string_len) {
25     ;
26   }
27 
28   if (to_conv.precision >= 0 && to_conv.precision < string_len)
29     string_len = to_conv.precision;
30 
31   if (to_conv.min_width > string_len) {
32     if ((to_conv.flags & FormatFlags::LEFT_JUSTIFIED) ==
33         FormatFlags::LEFT_JUSTIFIED) {
34       RET_IF_RESULT_NEGATIVE(writer->write(
35           reinterpret_cast<const char *>(to_conv.conv_val_ptr), string_len));
36       RET_IF_RESULT_NEGATIVE(
37           writer->write_chars(' ', to_conv.min_width - string_len));
38 
39     } else {
40       RET_IF_RESULT_NEGATIVE(
41           writer->write_chars(' ', to_conv.min_width - string_len));
42       RET_IF_RESULT_NEGATIVE(writer->write(
43           reinterpret_cast<const char *>(to_conv.conv_val_ptr), string_len));
44     }
45   } else {
46     RET_IF_RESULT_NEGATIVE(writer->write(
47         reinterpret_cast<const char *>(to_conv.conv_val_ptr), string_len));
48   }
49   return 0;
50 }
51 
52 } // namespace printf_core
53 } // namespace __llvm_libc
54 
55 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_STRING_CONVERTER_H
56