diff options
| author | Vinayak Dev <104419489+vinayakdsci@users.noreply.github.com> | 2024-03-20 23:17:35 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-03-20 10:47:35 -0700 |
| commit | 5ea152033ee99ac7ccde791009c372a0983b4eaf (patch) | |
| tree | 30d6f766d5112bbded63ff6bf2c9284f7d356e0a /libc/src/stdlib/strfromf.cpp | |
| parent | 10b0e355372fab1f4d585555536525545eef8523 (diff) | |
[libc]: Implement strfromf() and shared utilities (#85438)
Fixes #84244.
Implements the function `strfromf()` introduced in C23, and adds shared
utilities for implementation of other `strfrom*()` functions, including
`strfromd()` and `strfroml()`.
Diffstat (limited to 'libc/src/stdlib/strfromf.cpp')
| -rw-r--r-- | libc/src/stdlib/strfromf.cpp | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/libc/src/stdlib/strfromf.cpp b/libc/src/stdlib/strfromf.cpp new file mode 100644 index 000000000000..40eff87eb454 --- /dev/null +++ b/libc/src/stdlib/strfromf.cpp @@ -0,0 +1,42 @@ +//===-- Implementation of strfromf ------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "src/stdlib/strfromf.h" +#include "src/stdlib/str_from_util.h" + +#include <stdarg.h> +#include <stddef.h> + +namespace LIBC_NAMESPACE { + +LLVM_LIBC_FUNCTION(int, strfromf, + (char *__restrict s, size_t n, const char *__restrict format, + float fp)) { + LIBC_ASSERT(s != nullptr); + + printf_core::FormatSection section = + internal::parse_format_string(format, fp); + printf_core::WriteBuffer wb(s, (n > 0 ? n - 1 : 0)); + printf_core::Writer writer(&wb); + + int result = 0; + if (section.has_conv) + result = internal::strfromfloat_convert<float>(&writer, section); + else + result = writer.write(section.raw_string); + + if (result < 0) + return result; + + if (n > 0) + wb.buff[wb.buff_cur] = '\0'; + + return writer.get_chars_written(); +} + +} // namespace LIBC_NAMESPACE |
