Make strcasestr() faster

This commit is contained in:
Justine Tunney 2024-12-12 22:50:20 -08:00
parent 22094ae9ca
commit c22b413ac4
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
2 changed files with 133 additions and 0 deletions

View file

@ -17,12 +17,20 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/str/str.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/intrin/safemacros.h"
#include "libc/mem/alg.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/sysconf.h"
#include "libc/stdio/rand.h"
#include "libc/str/tab.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/prot.h"
#include "libc/testlib/ezbench.h"
#include "libc/testlib/hyperion.h"
#include "libc/testlib/testlib.h"
@ -54,6 +62,25 @@ TEST(strcasestr, tester) {
ASSERT_STREQ(haystack, strcasestr(haystack, "win"));
}
TEST(strcasestr, safety) {
int pagesz = sysconf(_SC_PAGESIZE);
char *map = (char *)mmap(0, pagesz * 2, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
npassert(map != MAP_FAILED);
npassert(!mprotect(map + pagesz, pagesz, PROT_NONE));
for (int haylen = 1; haylen < 128; ++haylen) {
char *hay = map + pagesz - (haylen + 1);
for (int i = 0; i < haylen; ++i)
hay[i] = max(rand() & 255, 1);
hay[haylen] = 0;
for (int neelen = 1; neelen < haylen; ++neelen) {
char *nee = hay + (haylen + 1) - (neelen + 1);
ASSERT_EQ(strcasestr_naive(hay, nee), strcasestr(hay, nee));
}
}
munmap(map, pagesz * 2);
}
TEST(strcasestr, test_emptyString_isFoundAtBeginning) {
MAKESTRING(haystack, "abc123def");
ASSERT_STREQ(&haystack[0], strcasestr(haystack, gc(strdup(""))));