Skip to content

Commit 020e699

Browse files
authored
Merge pull request #33 from nicolasnoble/improve-stringh
Improving inlined string.h a bit.
2 parents 756cb37 + c22548c commit 020e699

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

libc/include/string.h

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,13 @@ static __inline__ const void * memchr(const void * _s, int c, size_t n) {
7272

7373
static __inline__ char * strcat(char * s1, const char * s2) {
7474
char * r = s1;
75+
char c;
7576

7677
while (*s1)
7778
s1++;
7879

79-
while (*s2)
80-
*s1++ = *s2++;
80+
while ((c = *s2++))
81+
*s1++ = c;
8182

8283
*s1 = 0;
8384

@@ -94,11 +95,12 @@ static __inline__ char * strcpy(char * s1, const char * s2) {
9495

9596
static __inline__ char * strncpy(char * s1, const char * s2, size_t n) {
9697
char * r = s1;
98+
char c;
9799
size_t i;
98100

99101
for (i = 0; i < n; i++) {
100-
if (*s2) {
101-
*s1++ = *s2++;
102+
if ((c = *s2++)) {
103+
*s1++ = c;
102104
} else {
103105
*s1++ = 0;
104106
}
@@ -108,8 +110,9 @@ static __inline__ char * strncpy(char * s1, const char * s2, size_t n) {
108110
}
109111

110112
static __inline__ char * strchr(const char * s, int c) {
111-
while (*s) {
112-
if (*s == c)
113+
char b;
114+
while ((b = *s)) {
115+
if (b == c)
113116
return (char *) s;
114117
s++;
115118
}
@@ -119,9 +122,10 @@ static __inline__ char * strchr(const char * s, int c) {
119122

120123
static __inline__ char * strrchr(const char * s, int c) {
121124
const char * r = NULL;
125+
char b;
122126

123-
while (*s) {
124-
if (*s == c)
127+
while ((b = *s)) {
128+
if (b == c)
125129
r = s;
126130
s++;
127131
}
@@ -149,37 +153,34 @@ static __inline__ char * strncat(char * s1, const char * s2, size_t n) {
149153
}
150154

151155
static __inline__ int strcmp(const char * s1, const char * s2) {
152-
while (*s1 && *s2) {
153-
if (!*s1) {
156+
char c1, c2;
157+
while ((c1 = *s1++) && (c2 = *s2++)) {
158+
if (!c1) {
154159
return -1;
155-
} else if (!*s2) {
160+
} else if (!c2) {
156161
return 1;
157-
} else if (*s1 < *s2) {
162+
} else if (c1 < c2) {
158163
return -1;
159-
} else if (*s1 > *s2) {
164+
} else if (c1 > c2) {
160165
return 1;
161166
}
162-
s1++;
163-
s2++;
164167
}
165168

166169
return 0;
167170
}
168171

169172
static __inline__ int strncmp(const char * s1, const char * s2, size_t n) {
170-
while (*s1 && *s2 && n) {
171-
if (!*s1) {
173+
char c1, c2;
174+
while ((c1 = *s1++) && (c2 = *s2++) && n--) {
175+
if (!c1) {
172176
return -1;
173-
} else if (!*s2) {
177+
} else if (!c2) {
174178
return 1;
175-
} else if (*s1 < *s2) {
179+
} else if (c1 < c2) {
176180
return -1;
177-
} else if (*s1 > *s2) {
181+
} else if (c1 > c2) {
178182
return 1;
179183
}
180-
s1++;
181-
s2++;
182-
n--;
183184
}
184185

185186
return 0;

0 commit comments

Comments
 (0)