Use GNU style coding conventions.
[gnulib.git] / lib / memmem.c
1 /* Copyright (C) 1991,92,93,94,96,97,98,2000,2004,2007 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 #ifndef _LIBC
19 # include <config.h>
20 #endif
21
22 #include <stddef.h>
23 #include <string.h>
24 #include <stdbool.h>
25
26 #include "malloca.h"
27
28 #ifndef _LIBC
29 # define __builtin_expect(expr, val)   (expr)
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 (const char *haystack, const char *last_haystack,
38                     const char *needle, size_t m,
39                     const char **resultp)
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 != last_haystack)
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 /* Return the first occurrence of NEEDLE in HAYSTACK.  Return HAYSTACK
154    if NEEDLE_LEN is 0, otherwise NULL if NEEDLE is not found in
155    HAYSTACK.  */
156 void *
157 memmem (const void *haystack_start, size_t haystack_len,
158         const void *needle_start, size_t needle_len)
159 {
160   /* Operating with void * is awkward.  */
161   const char *haystack = (const char *) haystack_start;
162   const char *needle = (const char *) needle_start;
163   const char *last_haystack = haystack + haystack_len;
164   const char *last_needle = needle + needle_len;
165
166   if (needle_len == 0)
167     /* The first occurrence of the empty string is deemed to occur at
168        the beginning of the string.  */
169     return (void *) haystack;
170
171   /* Sanity check, otherwise the loop might search through the whole
172      memory.  */
173   if (__builtin_expect (haystack_len < needle_len, 0))
174     return NULL;
175
176   /* Use optimizations in memchr when possible.  */
177   if (__builtin_expect (needle_len == 1, 0))
178     return memchr (haystack, (unsigned char) *needle, haystack_len);
179
180   /* Minimizing the worst-case complexity:
181      Let n = haystack_len, m = needle_len.
182      The naïve algorithm is O(n*m) worst-case.
183      The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
184      memory allocation.
185      To achieve linear complexity and yet amortize the cost of the
186      memory allocation, we activate the Knuth-Morris-Pratt algorithm
187      only once the naïve algorithm has already run for some time; more
188      precisely, when
189        - the outer loop count is >= 10,
190        - the average number of comparisons per outer loop is >= 5,
191        - the total number of comparisons is >= m.
192      But we try it only once.  If the memory allocation attempt failed,
193      we don't retry it.  */
194   {
195     bool try_kmp = true;
196     size_t outer_loop_count = 0;
197     size_t comparison_count = 0;
198
199     /* Speed up the following searches of needle by caching its first
200        byte.  */
201     char b = *needle++;
202
203     for (;; haystack++)
204       {
205         if (haystack == last_haystack)
206           /* No match.  */
207           return NULL;
208
209         /* See whether it's advisable to use an asymptotically faster
210            algorithm.  */
211         if (try_kmp
212             && outer_loop_count >= 10
213             && comparison_count >= 5 * outer_loop_count)
214           {
215             /* See if needle + comparison_count now reaches the end of
216                needle.  */
217             if (comparison_count >= needle_len)
218               {
219                 /* Try the Knuth-Morris-Pratt algorithm.  */
220                 const char *result;
221                 if (knuth_morris_pratt (haystack, last_haystack,
222                                         needle - 1, needle_len, &result))
223                   return (void *) result;
224                 try_kmp = false;
225               }
226           }
227
228         outer_loop_count++;
229         comparison_count++;
230         if (*haystack == b)
231           /* The first byte matches.  */
232           {
233             const char *rhaystack = haystack + 1;
234             const char *rneedle = needle;
235
236             for (;; rhaystack++, rneedle++)
237               {
238                 if (rneedle == last_needle)
239                   /* Found a match.  */
240                   return (void *) haystack;
241                 if (rhaystack == last_haystack)
242                   /* No match.  */
243                   return NULL;
244                 comparison_count++;
245                 if (*rhaystack != *rneedle)
246                   /* Nothing in this round.  */
247                   break;
248               }
249           }
250       }
251   }
252
253   return NULL;
254 }