[libc-commits] [libc] [libc] Implemented wcrtomb internal function and public libc function (PR #144596)
Uzair Nawaz via libc-commits
libc-commits at lists.llvm.org
Fri Jun 20 10:37:00 PDT 2025
================
@@ -0,0 +1,50 @@
+//===-- Implementation of wcrtomb -----------------------------------------===//
+//
+// 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/__support/wchar/wcrtomb.h"
+#include "src/__support/error_or.h"
+#include "src/__support/wchar/character_converter.h"
+#include "src/__support/wchar/mbstate.h"
+
+#include "hdr/types/char32_t.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/wchar_t.h"
+#include "src/__support/common.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace internal {
+
+ErrorOr<size_t> wcrtomb(char *__restrict s, wchar_t wc,
+ mbstate *__restrict ps) {
+ static_assert(sizeof(wchar_t) == 4);
+
+ CharacterConverter cr(ps);
+
+ // when s is nullptr, this is equivalent to wcrtomb(buf, L'\0', ps)
+ char buf[sizeof(wchar_t) / sizeof(char)];
+ if (s == nullptr) {
+ s = buf;
+ wc = L'\0';
+ }
----------------
uzairnawaz wrote:
Well, the buffer isn't actually static here and isn't technically necessary. The function is just expected to return the length of the null character when converted to multibyte form.
An alternative implementation would remove the buffer completely and do something along the lines of:
```
while (!cr.isComplete()) {
auto utf8 = cr.pop_utf8(); // can never fail as long as the push succeeded
LIBC_ASSERT(utf8.has_value());
if (s != nullptr) {
*s = utf8.value();
s++;
}
count++;
}
```
The internal buffer just avoids checking that condition in a loop.
But, I thought about it some more and this seems like a quirk of the public function anyway, so I think it's fair to move it.
https://github.com/llvm/llvm-project/pull/144596
More information about the libc-commits
mailing list