8 int ksprintf(kstring_t *s, const char *fmt, ...)
13 l = vsnprintf(s->s + s->l, s->m - s->l, fmt, ap); // This line does not work with glibc 2.0. See `man snprintf'.
15 if (l + 1 > s->m - s->l) {
18 s->s = (char*)realloc(s->s, s->m);
20 l = vsnprintf(s->s + s->l, s->m - s->l, fmt, ap);
27 // s MUST BE a null terminated string; l = strlen(s)
28 int ksplit_core(char *s, int delimiter, int *_max, int **_offsets)
30 int i, n, max, last_char, last_start, *offsets, l;
31 n = 0; max = *_max; offsets = *_offsets;
34 #define __ksplit_aux do { \
38 max = max? max<<1 : 2; \
39 offsets = (int*)realloc(offsets, sizeof(int) * max); \
41 offsets[n++] = last_start; \
45 for (i = 0, last_char = last_start = 0; i <= l; ++i) {
47 if (isspace(s[i]) || s[i] == 0) {
48 if (isgraph(last_char)) __ksplit_aux; // the end of a field
50 if (isspace(last_char) || last_char == 0) last_start = i;
53 if (s[i] == delimiter || s[i] == 0) {
54 if (last_char != 0 && last_char != delimiter) __ksplit_aux; // the end of a field
56 if (last_char == delimiter || last_char == 0) last_start = i;
61 *_max = max; *_offsets = offsets;
65 /**********************
66 * Boyer-Moore search *
67 **********************/
69 // reference: http://www-igm.univ-mlv.fr/~lecroq/string/node14.html
70 int *ksBM_prep(const uint8_t *pat, int m)
72 int i, *suff, *prep, *bmGs, *bmBc;
73 prep = calloc(m + 256, 1);
74 bmGs = prep; bmBc = prep + m;
76 for (i = 0; i < 256; ++i) bmBc[i] = m;
77 for (i = 0; i < m - 1; ++i) bmBc[pat[i]] = m - i - 1;
79 suff = calloc(m, sizeof(int));
84 for (i = m - 2; i >= 0; --i) {
85 if (i > g && suff[i + m - 1 - f] < i - g)
86 suff[i] = suff[i + m - 1 - f];
90 while (g >= 0 && pat[g] == pat[g + m - 1 - f]) --g;
97 for (i = 0; i < m; ++i) bmGs[i] = m;
98 for (i = m - 1; i >= 0; --i)
100 for (; j < m - 1 - i; ++j)
103 for (i = 0; i <= m - 2; ++i)
104 bmGs[m - 1 - suff[i]] = m - 1 - i;
110 int *ksBM_search(const uint8_t *str, int n, const uint8_t *pat, int m, int *_prep, int *n_matches)
112 int i, j, *prep, *bmGs, *bmBc;
113 int *matches = 0, mm = 0, nm = 0;
114 prep = _prep? _prep : ksBM_prep(pat, m);
115 bmGs = prep; bmBc = prep + m;
118 for (i = m - 1; i >= 0 && pat[i] == str[i+j]; --i);
122 matches = realloc(matches, mm * sizeof(int));
127 int max = bmBc[str[i+j]] - m + 1 + i;
128 if (max < bmGs[i]) max = bmGs[i];
133 if (_prep == 0) free(prep);
143 s = (kstring_t*)calloc(1, sizeof(kstring_t));
145 ksprintf(s, " abcdefg: %d ", 100);
146 printf("'%s'\n", s->s);
148 fields = ksplit(s, 0, &n);
149 for (i = 0; i < n; ++i)
150 printf("field[%d] = '%s'\n", i, s->s + fields[i]);
154 static char *str = "abcdefgcdg";
155 static char *pat = "cd";
157 matches = ksBM_search(str, strlen(str), pat, strlen(pat), 0, &n);
159 for (i = 0; i < n; ++i)
160 printf("- %d\n", matches[i]);