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