From a8d95fd51ab53f287ba107b1bdb792ab7edf05b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20Michaj=C5=82ow?= Date: Tue, 4 Jun 2024 20:55:33 +0200 Subject: [PATCH] bstr: use memchr and memrchr for bstrchr and bstrrchr May be faster to use optimized variants instead of simple loop. --- meson.build | 2 ++ misc/bstr.c | 15 +++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/meson.build b/meson.build index 0f692a8e87..d1eee06be4 100644 --- a/meson.build +++ b/meson.build @@ -428,6 +428,8 @@ endif features += {'ppoll': cc.has_function('ppoll', args: '-D_GNU_SOURCE', prefix: '#include ')} +features += {'memrchr': cc.has_function('memrchr', args: '-D_GNU_SOURCE', + prefix: '#include ')} cd_devices = { 'windows': 'D:', diff --git a/misc/bstr.c b/misc/bstr.c index 379b2ed22d..b9a260f8e1 100644 --- a/misc/bstr.c +++ b/misc/bstr.c @@ -63,18 +63,25 @@ int bstrcasecmp(struct bstr str1, struct bstr str2) int bstrchr(struct bstr str, int c) { - for (int i = 0; i < str.len; i++) - if (str.start[i] == c) - return i; - return -1; + if (!str.len) + return -1; + unsigned char *pos = memchr(str.start, c, str.len); + return pos ? pos - str.start : -1; } int bstrrchr(struct bstr str, int c) { + if (!str.len) + return -1; +#if HAVE_MEMRCHR + unsigned char *pos = memrchr(str.start, c, str.len); + return pos ? pos - str.start : -1; +#else for (int i = str.len - 1; i >= 0; i--) if (str.start[i] == c) return i; return -1; +#endif } int bstrcspn(struct bstr str, const char *reject)