|
| 1 | +//===-- Implementation for mbrtowc function ---------------------*- C++ -*-===// |
| 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/mbrtowc.h" |
| 10 | +#include "hdr/types/mbstate_t.h" |
| 11 | +#include "hdr/types/size_t.h" |
| 12 | +#include "hdr/types/wchar_t.h" |
| 13 | +#include "src/__support/common.h" |
| 14 | +#include "src/__support/error_or.h" |
| 15 | +#include "src/__support/macros/config.h" |
| 16 | +#include "src/__support/wchar/character_converter.h" |
| 17 | +#include "src/__support/wchar/mbstate.h" |
| 18 | + |
| 19 | +namespace LIBC_NAMESPACE_DECL { |
| 20 | +namespace internal { |
| 21 | + |
| 22 | +ErrorOr<size_t> mbrtowc(wchar_t *__restrict pwc, const char *__restrict s, |
| 23 | + size_t n, mbstate *__restrict ps) { |
| 24 | + CharacterConverter char_conv(ps); |
| 25 | + if (s == nullptr) |
| 26 | + return 0; |
| 27 | + size_t i = 0; |
| 28 | + // Reading in bytes until we have a complete wc or error |
| 29 | + for (; i < n && !char_conv.isFull(); ++i) { |
| 30 | + int err = char_conv.push(static_cast<char8_t>(s[i])); |
| 31 | + // Encoding error |
| 32 | + if (err == -1) |
| 33 | + return Error(-1); |
| 34 | + } |
| 35 | + auto wc = char_conv.pop_utf32(); |
| 36 | + if (wc.has_value()) { |
| 37 | + *pwc = wc.value(); |
| 38 | + // null terminator -> return 0 |
| 39 | + if (wc.value() == L'\0') |
| 40 | + return 0; |
| 41 | + return i; |
| 42 | + } |
| 43 | + // Incomplete but potentially valid |
| 44 | + return -2; |
| 45 | +} |
| 46 | + |
| 47 | +} // namespace internal |
| 48 | + |
| 49 | +} // namespace LIBC_NAMESPACE_DECL |
0 commit comments