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
+9 -5
View File
@@ -1,4 +1,5 @@
/*
* Copyright 2025, Haiku, Inc. All rights reserved.
* Copyright 2008, Axel Dörfler, [email protected].
* 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;
}
while (count-- > 0) {
int cmp = *a++ - *b++;
if (cmp != 0)
return cmp;
while (count > 0 && *a == *b) {
a++;
b++;
count--;
}
return 0;
if (count == 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].
* Distributed under the terms of the MIT license.
*/
@@ -26,9 +27,10 @@ strcmp(char const *a, char const *b)
b = (const char *)b32;
}
while (1) {
int cmp = (unsigned char)*a - (unsigned char)*b++;
if (cmp != 0 || *a++ == '\0')
return cmp;
while (*a == *b && *a != 0) {
a++;
b++;
}
return (unsigned char)*a - (unsigned char)*b;
}
+9 -5
View File
@@ -1,4 +1,5 @@
/*
* Copyright 2025, Haiku, Inc. All rights reserved.
* Copyright 2008, Axel Dörfler, [email protected].
* 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;
}
while (count-- > 0) {
int cmp = (unsigned char)*a - (unsigned char)*b++;
if (cmp != 0 || *a++ == '\0')
return cmp;
while (count > 0 && *a == *b && *a != 0) {
a++;
b++;
count--;
}
return 0;
if (count == 0)
return 0;
return (unsigned char)*a - (unsigned char)*b;
}