[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:19:43 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:

Is there a reason you feel like this should be moved to the public function? My idea was to have the behavior of the internal function match the public one wherever possible. 

I handled the nullptr case for the `mbstate_t` argument in the public function only because each public function is supposed to have its own internal state. Ex: the public `wcrtomb` should have a separate internal mbstate than the public `wcsrtombs`.

It feels like this change creates redundant cases if both the public function and the internal function perform a null check, but the internal function is guaranteed to never get called with a null string.

https://github.com/llvm/llvm-project/pull/144596


More information about the libc-commits mailing list