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