Skip to content

Commit fac27b8

Browse files
committed
libc.
1 parent 9f626b2 commit fac27b8

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

sqlite3/strings.c

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#include <limits.h>
2+
#include <stddef.h>
3+
#include <stdint.h>
4+
5+
#if defined(__wasm_bulk_memory__)
6+
#define memset __builtin_memset
7+
#define memcpy __builtin_memcpy
8+
#define memmove __builtin_memmove
9+
#endif
10+
11+
#define ONES (~(uintmax_t)(0) / UCHAR_MAX)
12+
#define HIGHS (ONES * (UCHAR_MAX / 2 + 1))
13+
#define HASZERO(x) ((x) - (typeof(x))(ONES) & ~(x) & (typeof(x))(HIGHS))
14+
#define UNALIGNED(x) ((uintptr_t)(x) & (sizeof(*x) - 1))
15+
16+
int memcmp(const void *v1, const void *v2, size_t n) {
17+
typedef uint64_t __attribute__((__may_alias__)) word;
18+
19+
const word *w1 = v1;
20+
const word *w2 = v2;
21+
if (!(UNALIGNED(w1) | UNALIGNED(w2))) {
22+
while (n >= sizeof(word) && *w1 == *w2) {
23+
n -= sizeof(word);
24+
w1++;
25+
w2++;
26+
}
27+
}
28+
29+
const unsigned char *u1 = (const void *)w1;
30+
const unsigned char *u2 = (const void *)w2;
31+
while (n--) {
32+
if (*u1 != *u2) return *u1 - *u2;
33+
u1++;
34+
u2++;
35+
}
36+
return 0;
37+
}
38+
39+
int strcmp(const char *c1, const char *c2) {
40+
typedef uintptr_t __attribute__((__may_alias__)) word;
41+
42+
const word *w1 = (const void *)c1;
43+
const word *w2 = (const void *)c2;
44+
if (!(UNALIGNED(w1) | UNALIGNED(w2))) {
45+
while (*w1 == *w2) {
46+
if (HASZERO(*w1)) return 0;
47+
w1++;
48+
w2++;
49+
}
50+
c1 = (const void *)w1;
51+
c2 = (const void *)w2;
52+
}
53+
54+
while (*c1 == *c2 && *c1) {
55+
c1++;
56+
c2++;
57+
}
58+
return *(unsigned char *)c1 - *(unsigned char *)c2;
59+
}
60+
61+
int strncmp(const char *c1, const char *c2, size_t n) {
62+
typedef uintptr_t __attribute__((__may_alias__)) word;
63+
64+
const word *w1 = (const void *)c1;
65+
const word *w2 = (const void *)c2;
66+
if (!(UNALIGNED(w1) | UNALIGNED(w2))) {
67+
while (n >= sizeof(word) && *w1 == *w2) {
68+
if ((n -= sizeof(word)) == 0 || HASZERO(*w1)) return 0;
69+
w1++;
70+
w2++;
71+
}
72+
c1 = (const void *)w1;
73+
c2 = (const void *)w2;
74+
}
75+
76+
while (n-- && *c1 == *c2) {
77+
if (n == 0 || *c1 == 0) return 0;
78+
c1++;
79+
c2++;
80+
}
81+
return *(unsigned char *)c1 - *(unsigned char *)c2;
82+
}
83+
84+
#undef UNALIGNED
85+
#undef HASZERO
86+
#undef HIGHS
87+
#undef ONES

0 commit comments

Comments
 (0)