aboutsummaryrefslogtreecommitdiff
path: root/vendor/librune/lib/utf8/u8rchr.c
diff options
context:
space:
mode:
authorThomas Voss <mail@thomasvoss.com> 2024-01-21 03:03:58 +0100
committerThomas Voss <mail@thomasvoss.com> 2024-01-21 03:03:58 +0100
commit4f93f935dc7a981ca073a322425c3f5929ffb644 (patch)
tree4460586408ec7fdfcecf3ba4584f0435067125a6 /vendor/librune/lib/utf8/u8rchr.c
parent72ea25a4d73e3e026366d4165f5bc4ec9e7418cb (diff)
Support line- & column-based match locations
Diffstat (limited to 'vendor/librune/lib/utf8/u8rchr.c')
-rw-r--r--vendor/librune/lib/utf8/u8rchr.c87
1 files changed, 87 insertions, 0 deletions
diff --git a/vendor/librune/lib/utf8/u8rchr.c b/vendor/librune/lib/utf8/u8rchr.c
new file mode 100644
index 0000000..15fff51
--- /dev/null
+++ b/vendor/librune/lib/utf8/u8rchr.c
@@ -0,0 +1,87 @@
+#include <stdint.h>
+
+#include "utf8.h"
+
+#include "internal/common.h"
+
+static const char8_t *
+memrchr1(const char8_t *s, size_t k, const char8_t *n)
+{
+ for (const char8_t *p = s + k - 1; k-- > 0; p--) {
+ if (*p == *n)
+ return p;
+ }
+ return nullptr;
+}
+
+static const char8_t *
+memrchr2(const char8_t *h, size_t k, const char8_t *n)
+{
+ uint16_t hw, nw;
+ const char8_t *H = h + k - 1;
+ hw = H[-1] << 8 | H[-0];
+ nw = n[+0] << 8 | n[+1];
+
+ for (H -= 2, k -= 2; k; k--, hw = hw >> 8 | (*H-- << 8)) {
+ if (hw == nw)
+ return H + 1;
+ }
+
+ return hw == nw ? H + 1 : nullptr;
+}
+
+static const char8_t *
+memrchr3(const char8_t *h, size_t k, const char8_t *n)
+{
+ uint32_t hw, nw;
+ const char8_t *H = h + k - 1;
+ hw = H[-2] << 24 | H[-1] << 16 | H[-0] << 8;
+ nw = n[+0] << 24 | n[+1] << 16 | n[+2] << 8;
+
+ for (H -= 3, k -= 3; k;
+ k--, hw = (hw >> 8 | (*H-- << 24)) & UINT32_C(0xFFFFFF00))
+ {
+ if (hw == nw)
+ return H + 1;
+ }
+
+ return hw == nw ? H + 1 : nullptr;
+}
+
+static const char8_t *
+memrchr4(const char8_t *h, size_t k, const char8_t *n)
+{
+ uint32_t hw, nw;
+ const char8_t *H = h + k - 1;
+ hw = H[-3] << 24 | H[-2] << 16 | H[-1] << 8 | H[-0];
+ nw = n[+0] << 24 | n[+1] << 16 | n[+2] << 8 | n[+3];
+
+ for (H -= 4, k -= 4; k; k--, hw = hw >> 8 | (*H-- << 24)) {
+ if (hw == nw)
+ return H + 1;
+ }
+
+ return hw == nw ? H + 1 : nullptr;
+}
+
+const char8_t *
+u8rchr(const char8_t *s, rune ch, size_t n)
+{
+ char8_t buf[U8_LEN_MAX];
+ int m = rtou8(buf, ch, sizeof(buf));
+
+ if (n < (size_t)m)
+ return nullptr;
+ switch (m) {
+ case 1:
+ return memrchr1(s, n, buf);
+ case 2:
+ return memrchr2(s, n, buf);
+ case 3:
+ return memrchr3(s, n, buf);
+ case 4:
+ return memrchr4(s, n, buf);
+ }
+
+ unreachable();
+}