1 | //===-- Collection of utils for implementing wide char functions --*-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 | #ifndef LLVM_LIBC_SRC___SUPPORT_WCTYPE_UTILS_H |
10 | #define LLVM_LIBC_SRC___SUPPORT_WCTYPE_UTILS_H |
11 | |
12 | #include "src/__support/CPP/optional.h" |
13 | #include "src/__support/macros/attributes.h" // LIBC_INLINE |
14 | |
15 | #define __need_wint_t |
16 | #define __need_wchar_t |
17 | #include <stddef.h> // needed for wint_t and wchar_t |
18 | |
19 | namespace LIBC_NAMESPACE { |
20 | namespace internal { |
21 | |
22 | // ------------------------------------------------------ |
23 | // Rationale: Since these classification functions are |
24 | // called in other functions, we will avoid the overhead |
25 | // of a function call by inlining them. |
26 | // ------------------------------------------------------ |
27 | |
28 | LIBC_INLINE cpp::optional<int> wctob(wint_t c) { |
29 | // This needs to be translated to EOF at the callsite. This is to avoid |
30 | // including stdio.h in this file. |
31 | // The standard states that wint_t may either be an alias of wchar_t or |
32 | // an alias of an integer type, different platforms define this type with |
33 | // different signedness. This is equivalent to `(c > 127) || (c < 0)` but also |
34 | // works without -Wtype-limits warnings when `wint_t` is unsigned. |
35 | if ((c & ~127) != 0) |
36 | return cpp::nullopt; |
37 | return static_cast<int>(c); |
38 | } |
39 | |
40 | LIBC_INLINE cpp::optional<wint_t> btowc(int c) { |
41 | if (c > 127 || c < 0) |
42 | return cpp::nullopt; |
43 | return static_cast<wint_t>(c); |
44 | } |
45 | |
46 | } // namespace internal |
47 | } // namespace LIBC_NAMESPACE |
48 | |
49 | #endif // LLVM_LIBC_SRC___SUPPORT_WCTYPE_UTILS_H |
50 | |