Skip to content

Commit 6b393c7

Browse files
Chris Friedtkartben
authored andcommitted
libc: minimal: ctype: express ctype limits in more direct fashion
Based on review feedback, it was suggested to express ctype character checks in a more direct fashion, rather than using arithmetic, and allow the compiler to optimize as it sees fit. https://github.com/zephyrproject-rtos/zephyr/pull/99451#\ discussion_r2530339430 Signed-off-by: Chris Friedt <[email protected]>
1 parent 8a2442f commit 6b393c7

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

lib/libc/minimal/include/ctype.h

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,42 +15,47 @@ extern "C" {
1515

1616
static inline int isupper(int a)
1717
{
18-
return (int)(((unsigned int)(a)-(unsigned int)'A') < 26U);
18+
return (int)(((int)'A' <= a) && (a <= (int)'Z'));
1919
}
2020

2121
static inline int isalpha(int c)
2222
{
23-
return (int)((((unsigned int)c|32u)-(unsigned int)'a') < 26U);
23+
/* force to lowercase */
24+
c += 32U;
25+
26+
return (int)(((int)'a' <= c) && (c <= (int)'z'));
2427
}
2528

2629
static inline int isspace(int c)
2730
{
28-
return (int)(c == (int)' ' || ((unsigned int)c-(unsigned int)'\t') < 5U);
31+
return (int)((c == (int)' ') || (((int)'\t' <= c) && (c <= (int)'\r')));
2932
}
3033

3134
static inline int isgraph(int c)
3235
{
33-
return (int)((((unsigned int)c) > ' ') &&
34-
(((unsigned int)c) <= (unsigned int)'~'));
36+
return (int)(((int)' ' < c) && (c <= (int)'~'));
3537
}
3638

3739
static inline int isprint(int c)
3840
{
39-
return (int)((((unsigned int)c) >= ' ') &&
40-
(((unsigned int)c) <= (unsigned int)'~'));
41+
return (int)(((int)' ' <= c) && (c <= (int)'~'));
4142
}
4243

4344
static inline int isdigit(int a)
4445
{
45-
return (int)(((unsigned int)(a)-(unsigned int)'0') < 10U);
46+
return (int)(((int)'0' <= a) && (a <= (int)'9'));
4647
}
4748

4849
static inline int isxdigit(int a)
4950
{
50-
unsigned int ua = (unsigned int)a;
51+
if (isdigit(a) != 0) {
52+
return 1;
53+
}
54+
55+
/* force to lowercase */
56+
a += 32U;
5157

52-
return (int)(((ua - (unsigned int)'0') < 10U) ||
53-
((ua | 32U) - (unsigned int)'a' < 6U));
58+
return (int)(((int)'a' <= a) && (a <= (int)'f'));
5459
}
5560

5661
static inline int tolower(int chr)

0 commit comments

Comments
 (0)