Fcitx
charutils.h
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2015-2015 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #ifndef _FCITX_UTILS_CHARUTILS_H_
8 #define _FCITX_UTILS_CHARUTILS_H_
9 
10 #include <limits>
11 
12 /// \addtogroup FcitxUtils
13 /// \{
14 /// \file
15 /// \brief Local independent API to detect character type.
16 
17 namespace fcitx::charutils {
18 /// \brief ascii only is lower
19 static constexpr inline bool islower(char c) { return c >= 'a' && c <= 'z'; }
20 
21 /// \brief ascii only is upper
22 static constexpr inline bool isupper(char c) { return c >= 'A' && c <= 'Z'; }
23 
24 /// \brief ascii only to lower
25 static constexpr inline char tolower(char c) {
26  return isupper(c) ? static_cast<char>(c - 'A' + 'a') : c;
27 }
28 
29 /// \brief ascii only to upper
30 static constexpr inline char toupper(char c) {
31  return islower(c) ? static_cast<char>(c - 'a' + 'A') : c;
32 }
33 
34 /// \brief ascii only is space
35 static constexpr inline bool isspace(char c) {
36  return c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v' ||
37  c == ' ';
38 }
39 
40 /// \brief ascii only is digit
41 static constexpr inline bool isdigit(char c) { return c >= '0' && c <= '9'; }
42 
43 static constexpr inline bool isprint(char c) {
44  constexpr char minPrint = 0x1f;
45  return c >= minPrint && c < std::numeric_limits<signed char>::max();
46 }
47 
48 static constexpr inline char toHex(int c) {
49  constexpr char hex[] = "0123456789abcdef";
50  return hex[c & 0xf];
51 }
52 
53 /**
54  * Return integer value for hex char
55  *
56  * @param c input char
57  * @return return integer for hex, if not hex, return -1
58  * @since 5.0.5
59  */
60 static constexpr inline int fromHex(char c) {
61  if (isdigit(c)) {
62  return c - '0';
63  }
64 
65  c = tolower(c);
66  if ((c >= 'a') && (c <= 'f')) {
67  return c - 'a' + 10;
68  }
69  return -1;
70 }
71 
72 static constexpr inline bool isxdigit(char c) {
73  return isdigit(c) || ((c >= 'a') && (c <= 'f')) ||
74  ((c >= 'A') && (c <= 'F'));
75 }
76 
77 } // namespace fcitx::charutils
78 
79 #endif // _FCITX_UTILS_CHARUTILS_H_