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