xref: /llvm-project/libc/src/stdlib/strfroml.cpp (revision 5ff3ff33ff930e4ec49da7910612d8a41eb068cb)
183e96977SVinayak Dev //===-- Implementation of strfroml ------------------------------*- C++ -*-===//
283e96977SVinayak Dev //
383e96977SVinayak Dev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
483e96977SVinayak Dev // See https://llvm.org/LICENSE.txt for license information.
583e96977SVinayak Dev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
683e96977SVinayak Dev //
783e96977SVinayak Dev //===----------------------------------------------------------------------===//
883e96977SVinayak Dev 
983e96977SVinayak Dev #include "src/stdlib/strfroml.h"
10*5ff3ff33SPetr Hosek #include "src/__support/macros/config.h"
1183e96977SVinayak Dev #include "src/stdlib/str_from_util.h"
1283e96977SVinayak Dev 
13*5ff3ff33SPetr Hosek namespace LIBC_NAMESPACE_DECL {
1483e96977SVinayak Dev 
1583e96977SVinayak Dev LLVM_LIBC_FUNCTION(int, strfroml,
1683e96977SVinayak Dev                    (char *__restrict s, size_t n, const char *__restrict format,
1783e96977SVinayak Dev                     long double fp)) {
1883e96977SVinayak Dev   LIBC_ASSERT(s != nullptr);
1983e96977SVinayak Dev 
2083e96977SVinayak Dev   printf_core::FormatSection section =
2183e96977SVinayak Dev       internal::parse_format_string(format, fp);
2283e96977SVinayak Dev 
2383e96977SVinayak Dev   // To ensure that the conversion function actually uses long double,
2483e96977SVinayak Dev   // the length modifier has to be set to LenghtModifier::L
2583e96977SVinayak Dev   section.length_modifier = printf_core::LengthModifier::L;
2683e96977SVinayak Dev 
2783e96977SVinayak Dev   printf_core::WriteBuffer wb(s, (n > 0 ? n - 1 : 0));
2883e96977SVinayak Dev   printf_core::Writer writer(&wb);
2983e96977SVinayak Dev 
3083e96977SVinayak Dev   int result = 0;
3183e96977SVinayak Dev   if (section.has_conv)
3283e96977SVinayak Dev     result = internal::strfromfloat_convert<long double>(&writer, section);
3383e96977SVinayak Dev   else
3483e96977SVinayak Dev     result = writer.write(section.raw_string);
3583e96977SVinayak Dev 
3683e96977SVinayak Dev   if (result < 0)
3783e96977SVinayak Dev     return result;
3883e96977SVinayak Dev 
3983e96977SVinayak Dev   if (n > 0)
4083e96977SVinayak Dev     wb.buff[wb.buff_cur] = '\0';
4183e96977SVinayak Dev 
4283e96977SVinayak Dev   return writer.get_chars_written();
4383e96977SVinayak Dev }
4483e96977SVinayak Dev 
45*5ff3ff33SPetr Hosek } // namespace LIBC_NAMESPACE_DECL
46