Unify 5 copies of the KMP code.
[pspp] / lib / mbscasestr.c
1 /* Case-insensitive searching in a string.
2    Copyright (C) 2005-2007 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2005.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #include <config.h>
19
20 /* Specification.  */
21 #include <string.h>
22
23 #include <ctype.h>
24 #include <stdbool.h>
25 #include <stddef.h>  /* for NULL, in case a nonstandard string.h lacks it */
26
27 #include "malloca.h"
28 #if HAVE_MBRTOWC
29 # include "mbuiter.h"
30 #endif
31
32 #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
33
34 /* Knuth-Morris-Pratt algorithm.  */
35 #define CANON_ELEMENT(c) TOLOWER (c)
36 #include "str-kmp.h"
37
38 #if HAVE_MBRTOWC
39 /* Knuth-Morris-Pratt algorithm.
40    See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
41    Return a boolean indicating success.  */
42 static bool
43 knuth_morris_pratt_multibyte (const char *haystack, const char *needle,
44                               const char **resultp)
45 {
46   size_t m = mbslen (needle);
47   mbchar_t *needle_mbchars;
48   size_t *table;
49
50   /* Allocate room for needle_mbchars and the table.  */
51   char *memory = (char *) nmalloca (m, sizeof (mbchar_t) + sizeof (size_t));
52   if (memory == NULL)
53     return false;
54   needle_mbchars = (mbchar_t *) memory;
55   table = (size_t *) (memory + m * sizeof (mbchar_t));
56
57   /* Fill needle_mbchars.  */
58   {
59     mbui_iterator_t iter;
60     size_t j;
61
62     j = 0;
63     for (mbui_init (iter, needle); mbui_avail (iter); mbui_advance (iter), j++)
64       {
65         mb_copy (&needle_mbchars[j], &mbui_cur (iter));
66         if (needle_mbchars[j].wc_valid)
67           needle_mbchars[j].wc = towlower (needle_mbchars[j].wc);
68       }
69   }
70
71   /* Fill the table.
72      For 0 < i < m:
73        0 < table[i] <= i is defined such that
74        forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
75        and table[i] is as large as possible with this property.
76      This implies:
77      1) For 0 < i < m:
78           If table[i] < i,
79           needle[table[i]..i-1] = needle[0..i-1-table[i]].
80      2) For 0 < i < m:
81           rhaystack[0..i-1] == needle[0..i-1]
82           and exists h, i <= h < m: rhaystack[h] != needle[h]
83           implies
84           forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
85      table[0] remains uninitialized.  */
86   {
87     size_t i, j;
88
89     /* i = 1: Nothing to verify for x = 0.  */
90     table[1] = 1;
91     j = 0;
92
93     for (i = 2; i < m; i++)
94       {
95         /* Here: j = i-1 - table[i-1].
96            The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
97            for x < table[i-1], by induction.
98            Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
99         mbchar_t *b = &needle_mbchars[i - 1];
100
101         for (;;)
102           {
103             /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
104                is known to hold for x < i-1-j.
105                Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
106             if (mb_equal (*b, needle_mbchars[j]))
107               {
108                 /* Set table[i] := i-1-j.  */
109                 table[i] = i - ++j;
110                 break;
111               }
112             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
113                for x = i-1-j, because
114                  needle[i-1] != needle[j] = needle[i-1-x].  */
115             if (j == 0)
116               {
117                 /* The inequality holds for all possible x.  */
118                 table[i] = i;
119                 break;
120               }
121             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
122                for i-1-j < x < i-1-j+table[j], because for these x:
123                  needle[x..i-2]
124                  = needle[x-(i-1-j)..j-1]
125                  != needle[0..j-1-(x-(i-1-j))]  (by definition of table[j])
126                     = needle[0..i-2-x],
127                hence needle[x..i-1] != needle[0..i-1-x].
128                Furthermore
129                  needle[i-1-j+table[j]..i-2]
130                  = needle[table[j]..j-1]
131                  = needle[0..j-1-table[j]]  (by definition of table[j]).  */
132             j = j - table[j];
133           }
134         /* Here: j = i - table[i].  */
135       }
136   }
137
138   /* Search, using the table to accelerate the processing.  */
139   {
140     size_t j;
141     mbui_iterator_t rhaystack;
142     mbui_iterator_t phaystack;
143
144     *resultp = NULL;
145     j = 0;
146     mbui_init (rhaystack, haystack);
147     mbui_init (phaystack, haystack);
148     /* Invariant: phaystack = rhaystack + j.  */
149     while (mbui_avail (phaystack))
150       {
151         mbchar_t c;
152
153         mb_copy (&c, &mbui_cur (phaystack));
154         if (c.wc_valid)
155           c.wc = towlower (c.wc);
156         if (mb_equal (needle_mbchars[j], c))
157           {
158             j++;
159             mbui_advance (phaystack);
160             if (j == m)
161               {
162                 /* The entire needle has been found.  */
163                 *resultp = mbui_cur_ptr (rhaystack);
164                 break;
165               }
166           }
167         else if (j > 0)
168           {
169             /* Found a match of needle[0..j-1], mismatch at needle[j].  */
170             size_t count = table[j];
171             j -= count;
172             for (; count > 0; count--)
173               {
174                 if (!mbui_avail (rhaystack))
175                   abort ();
176                 mbui_advance (rhaystack);
177               }
178           }
179         else
180           {
181             /* Found a mismatch at needle[0] already.  */
182             if (!mbui_avail (rhaystack))
183               abort ();
184             mbui_advance (rhaystack);
185             mbui_advance (phaystack);
186           }
187       }
188   }
189
190   freea (memory);
191   return true;
192 }
193 #endif
194
195 /* Find the first occurrence of the character string NEEDLE in the character
196    string HAYSTACK, using case-insensitive comparison.
197    Note: This function may, in multibyte locales, return success even if
198    strlen (haystack) < strlen (needle) !  */
199 char *
200 mbscasestr (const char *haystack, const char *needle)
201 {
202   /* Be careful not to look at the entire extent of haystack or needle
203      until needed.  This is useful because of these two cases:
204        - haystack may be very long, and a match of needle found early,
205        - needle may be very long, and not even a short initial segment of
206          needle may be found in haystack.  */
207 #if HAVE_MBRTOWC
208   if (MB_CUR_MAX > 1)
209     {
210       mbui_iterator_t iter_needle;
211
212       mbui_init (iter_needle, needle);
213       if (mbui_avail (iter_needle))
214         {
215           /* Minimizing the worst-case complexity:
216              Let n = mbslen(haystack), m = mbslen(needle).
217              The naïve algorithm is O(n*m) worst-case.
218              The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
219              memory allocation.
220              To achieve linear complexity and yet amortize the cost of the
221              memory allocation, we activate the Knuth-Morris-Pratt algorithm
222              only once the naïve algorithm has already run for some time; more
223              precisely, when
224                - the outer loop count is >= 10,
225                - the average number of comparisons per outer loop is >= 5,
226                - the total number of comparisons is >= m.
227              But we try it only once.  If the memory allocation attempt failed,
228              we don't retry it.  */
229           bool try_kmp = true;
230           size_t outer_loop_count = 0;
231           size_t comparison_count = 0;
232           size_t last_ccount = 0;                  /* last comparison count */
233           mbui_iterator_t iter_needle_last_ccount; /* = needle + last_ccount */
234
235           mbchar_t b;
236           mbui_iterator_t iter_haystack;
237
238           mbui_init (iter_needle_last_ccount, needle);
239
240           mb_copy (&b, &mbui_cur (iter_needle));
241           if (b.wc_valid)
242             b.wc = towlower (b.wc);
243
244           mbui_init (iter_haystack, haystack);
245           for (;; mbui_advance (iter_haystack))
246             {
247               mbchar_t c;
248
249               if (!mbui_avail (iter_haystack))
250                 /* No match.  */
251                 return NULL;
252
253               /* See whether it's advisable to use an asymptotically faster
254                  algorithm.  */
255               if (try_kmp
256                   && outer_loop_count >= 10
257                   && comparison_count >= 5 * outer_loop_count)
258                 {
259                   /* See if needle + comparison_count now reaches the end of
260                      needle.  */
261                   size_t count = comparison_count - last_ccount;
262                   for (;
263                        count > 0 && mbui_avail (iter_needle_last_ccount);
264                        count--)
265                     mbui_advance (iter_needle_last_ccount);
266                   last_ccount = comparison_count;
267                   if (!mbui_avail (iter_needle_last_ccount))
268                     {
269                       /* Try the Knuth-Morris-Pratt algorithm.  */
270                       const char *result;
271                       bool success =
272                         knuth_morris_pratt_multibyte (haystack, needle,
273                                                       &result);
274                       if (success)
275                         return (char *) result;
276                       try_kmp = false;
277                     }
278                 }
279
280               outer_loop_count++;
281               comparison_count++;
282               mb_copy (&c, &mbui_cur (iter_haystack));
283               if (c.wc_valid)
284                 c.wc = towlower (c.wc);
285               if (mb_equal (c, b))
286                 /* The first character matches.  */
287                 {
288                   mbui_iterator_t rhaystack;
289                   mbui_iterator_t rneedle;
290
291                   memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
292                   mbui_advance (rhaystack);
293
294                   mbui_init (rneedle, needle);
295                   if (!mbui_avail (rneedle))
296                     abort ();
297                   mbui_advance (rneedle);
298
299                   for (;; mbui_advance (rhaystack), mbui_advance (rneedle))
300                     {
301                       if (!mbui_avail (rneedle))
302                         /* Found a match.  */
303                         return (char *) mbui_cur_ptr (iter_haystack);
304                       if (!mbui_avail (rhaystack))
305                         /* No match.  */
306                         return NULL;
307                       comparison_count++;
308                       if (!mb_caseequal (mbui_cur (rhaystack),
309                                          mbui_cur (rneedle)))
310                         /* Nothing in this round.  */
311                         break;
312                     }
313                 }
314             }
315         }
316       else
317         return (char *) haystack;
318     }
319   else
320 #endif
321     {
322       if (*needle != '\0')
323         {
324           /* Minimizing the worst-case complexity:
325              Let n = strlen(haystack), m = strlen(needle).
326              The naïve algorithm is O(n*m) worst-case.
327              The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
328              memory allocation.
329              To achieve linear complexity and yet amortize the cost of the
330              memory allocation, we activate the Knuth-Morris-Pratt algorithm
331              only once the naïve algorithm has already run for some time; more
332              precisely, when
333                - the outer loop count is >= 10,
334                - the average number of comparisons per outer loop is >= 5,
335                - the total number of comparisons is >= m.
336              But we try it only once.  If the memory allocation attempt failed,
337              we don't retry it.  */
338           bool try_kmp = true;
339           size_t outer_loop_count = 0;
340           size_t comparison_count = 0;
341           size_t last_ccount = 0;                  /* last comparison count */
342           const char *needle_last_ccount = needle; /* = needle + last_ccount */
343
344           /* Speed up the following searches of needle by caching its first
345              character.  */
346           unsigned char b = TOLOWER ((unsigned char) *needle);
347
348           needle++;
349           for (;; haystack++)
350             {
351               if (*haystack == '\0')
352                 /* No match.  */
353                 return NULL;
354
355               /* See whether it's advisable to use an asymptotically faster
356                  algorithm.  */
357               if (try_kmp
358                   && outer_loop_count >= 10
359                   && comparison_count >= 5 * outer_loop_count)
360                 {
361                   /* See if needle + comparison_count now reaches the end of
362                      needle.  */
363                   if (needle_last_ccount != NULL)
364                     {
365                       needle_last_ccount +=
366                         strnlen (needle_last_ccount,
367                                  comparison_count - last_ccount);
368                       if (*needle_last_ccount == '\0')
369                         needle_last_ccount = NULL;
370                       last_ccount = comparison_count;
371                     }
372                   if (needle_last_ccount == NULL)
373                     {
374                       /* Try the Knuth-Morris-Pratt algorithm.  */
375                       const char *result;
376                       bool success =
377                         knuth_morris_pratt_unibyte (haystack, needle - 1,
378                                                     &result);
379                       if (success)
380                         return (char *) result;
381                       try_kmp = false;
382                     }
383                 }
384
385               outer_loop_count++;
386               comparison_count++;
387               if (TOLOWER ((unsigned char) *haystack) == b)
388                 /* The first character matches.  */
389                 {
390                   const char *rhaystack = haystack + 1;
391                   const char *rneedle = needle;
392
393                   for (;; rhaystack++, rneedle++)
394                     {
395                       if (*rneedle == '\0')
396                         /* Found a match.  */
397                         return (char *) haystack;
398                       if (*rhaystack == '\0')
399                         /* No match.  */
400                         return NULL;
401                       comparison_count++;
402                       if (TOLOWER ((unsigned char) *rhaystack)
403                           != TOLOWER ((unsigned char) *rneedle))
404                         /* Nothing in this round.  */
405                         break;
406                     }
407                 }
408             }
409         }
410       else
411         return (char *) haystack;
412     }
413 }