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