libroot/string: Use '==' and not '-' and '== 0' for all except the last comparison.

Should make the code clearer and save a branch in the loop.
Also add Haiku, Inc. to copyright notice.
This commit is contained in:
Augustin Cavalier
2025-03-05 11:12:41 -05:00
parent 5d46b254d4
commit 2b52ddef79
3 changed files with 24 additions and 14 deletions
+8 -4
View File
@@ -1,4 +1,5 @@
/* /*
* Copyright 2025, Haiku, Inc. All rights reserved.
* Copyright 2008, Axel Dörfler, [email protected]. * Copyright 2008, Axel Dörfler, [email protected].
* Distributed under the terms of the MIT license. * Distributed under the terms of the MIT license.
*/ */
@@ -27,11 +28,14 @@ memcmp(const void *_a, const void *_b, size_t count)
b = (const unsigned char *)bsz; b = (const unsigned char *)bsz;
} }
while (count-- > 0) { while (count > 0 && *a == *b) {
int cmp = *a++ - *b++; a++;
if (cmp != 0) b++;
return cmp; count--;
} }
if (count == 0)
return 0; return 0;
return *a - *b;
} }
+6 -4
View File
@@ -1,4 +1,5 @@
/* /*
* Copyright 2025, Haiku, Inc. All rights reserved.
* Copyright 2008, Axel Dörfler, [email protected]. * Copyright 2008, Axel Dörfler, [email protected].
* Distributed under the terms of the MIT license. * Distributed under the terms of the MIT license.
*/ */
@@ -26,9 +27,10 @@ strcmp(char const *a, char const *b)
b = (const char *)b32; b = (const char *)b32;
} }
while (1) { while (*a == *b && *a != 0) {
int cmp = (unsigned char)*a - (unsigned char)*b++; a++;
if (cmp != 0 || *a++ == '\0') b++;
return cmp;
} }
return (unsigned char)*a - (unsigned char)*b;
} }
+8 -4
View File
@@ -1,4 +1,5 @@
/* /*
* Copyright 2025, Haiku, Inc. All rights reserved.
* Copyright 2008, Axel Dörfler, [email protected]. * Copyright 2008, Axel Dörfler, [email protected].
* Distributed under the terms of the MIT license. * Distributed under the terms of the MIT license.
*/ */
@@ -27,11 +28,14 @@ strncmp(char const *a, char const *b, size_t count)
b = (const char *)b32; b = (const char *)b32;
} }
while (count-- > 0) { while (count > 0 && *a == *b && *a != 0) {
int cmp = (unsigned char)*a - (unsigned char)*b++; a++;
if (cmp != 0 || *a++ == '\0') b++;
return cmp; count--;
} }
if (count == 0)
return 0; return 0;
return (unsigned char)*a - (unsigned char)*b;
} }