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