1 //===-- Implementation of wcrtomb -----------------------------------------===// 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 #include "src/__support/wchar/wcrtomb.h" 10 #include "src/__support/error_or.h" 11 #include "src/__support/wchar/character_converter.h" 12 #include "src/__support/wchar/mbstate.h" 13 14 #include "hdr/errno_macros.h" 15 #include "hdr/types/char32_t.h" 16 #include "hdr/types/size_t.h" 17 #include "hdr/types/wchar_t.h" 18 #include "src/__support/common.h" 19 #include "src/__support/libc_assert.h" 20 21 namespace LIBC_NAMESPACE_DECL { 22 namespace internal { 23 wcrtomb(char * __restrict s,wchar_t wc,mbstate * __restrict ps)24ErrorOr<size_t> wcrtomb(char *__restrict s, wchar_t wc, 25 mbstate *__restrict ps) { 26 static_assert(sizeof(wchar_t) == 4); 27 28 CharacterConverter cr(ps); 29 30 if (!cr.isValidState()) 31 return Error(EINVAL); 32 33 int status = cr.push(static_cast<char32_t>(wc)); 34 if (status != 0) 35 return Error(status); 36 37 size_t count = 0; 38 while (!cr.isEmpty()) { 39 auto utf8 = cr.pop_utf8(); // can never fail as long as the push succeeded 40 LIBC_ASSERT(utf8.has_value()); 41 42 *s = utf8.value(); 43 s++; 44 count++; 45 } 46 return count; 47 } 48 49 } // namespace internal 50 } // namespace LIBC_NAMESPACE_DECL 51