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