53 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/__support/wchar/mbrtowc.h"10#include "hdr/errno_macros.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 19namespace LIBC_NAMESPACE_DECL {20namespace internal {21 22ErrorOr<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 (!char_conv.isValidState())26 return Error(EINVAL);27 if (s == nullptr)28 return 0;29 size_t i = 0;30 // Reading in bytes until we have a complete wc or error31 for (; i < n && !char_conv.isFull(); ++i) {32 int err = char_conv.push(static_cast<char8_t>(s[i]));33 // Encoding error34 if (err == EILSEQ)35 return Error(err);36 }37 auto wc = char_conv.pop_utf32();38 if (wc.has_value()) {39 if (pwc != nullptr)40 *pwc = wc.value();41 // null terminator -> return 042 if (wc.value() == L'\0')43 return 0;44 return i;45 }46 // Incomplete but potentially valid47 return -2;48}49 50} // namespace internal51 52} // namespace LIBC_NAMESPACE_DECL53