Prepare for faster uN_strstr functions.
[gnulib.git] / lib / str-kmp.h
1 /* Substring search in a NUL terminated string of UNIT elements,
2    using the Knuth-Morris-Pratt algorithm.
3    Copyright (C) 2005-2011 Free Software Foundation, Inc.
4    Written by Bruno Haible <bruno@clisp.org>, 2005.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 /* Before including this file, you need to define:
21      UNIT                    The element type of the needle and haystack.
22      CANON_ELEMENT(c)        A macro that canonicalizes an element right after
23                              it has been fetched from needle or haystack.
24                              The argument is of type UNIT; the result must be
25                              of type UNIT as well.  */
26
27 /* Knuth-Morris-Pratt algorithm.
28    See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
29    HAYSTACK is the NUL terminated string in which to search for.
30    NEEDLE is the string to search for in HAYSTACK, consisting of NEEDLE_LEN
31    units.
32    Return a boolean indicating success:
33    Return true and set *RESULTP if the search was completed.
34    Return false if it was aborted because not enough memory was available.  */
35 static bool
36 knuth_morris_pratt (const UNIT *haystack,
37                     const UNIT *needle, size_t needle_len,
38                     const UNIT **resultp)
39 {
40   size_t m = needle_len;
41
42   /* Allocate the table.  */
43   size_t *table = (size_t *) nmalloca (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        forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
50        and table[i] is as large as possible with this property.
51      This implies:
52      1) For 0 < i < m:
53           If table[i] < i,
54           needle[table[i]..i-1] = needle[0..i-1-table[i]].
55      2) For 0 < i < m:
56           rhaystack[0..i-1] == needle[0..i-1]
57           and exists h, i <= h < m: rhaystack[h] != needle[h]
58           implies
59           forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
60      table[0] remains uninitialized.  */
61   {
62     size_t i, j;
63
64     /* i = 1: Nothing to verify for x = 0.  */
65     table[1] = 1;
66     j = 0;
67
68     for (i = 2; i < m; i++)
69       {
70         /* Here: j = i-1 - table[i-1].
71            The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
72            for x < table[i-1], by induction.
73            Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
74         UNIT b = CANON_ELEMENT (needle[i - 1]);
75
76         for (;;)
77           {
78             /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
79                is known to hold for x < i-1-j.
80                Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
81             if (b == CANON_ELEMENT (needle[j]))
82               {
83                 /* Set table[i] := i-1-j.  */
84                 table[i] = i - ++j;
85                 break;
86               }
87             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
88                for x = i-1-j, because
89                  needle[i-1] != needle[j] = needle[i-1-x].  */
90             if (j == 0)
91               {
92                 /* The inequality holds for all possible x.  */
93                 table[i] = i;
94                 break;
95               }
96             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
97                for i-1-j < x < i-1-j+table[j], because for these x:
98                  needle[x..i-2]
99                  = needle[x-(i-1-j)..j-1]
100                  != needle[0..j-1-(x-(i-1-j))]  (by definition of table[j])
101                     = needle[0..i-2-x],
102                hence needle[x..i-1] != needle[0..i-1-x].
103                Furthermore
104                  needle[i-1-j+table[j]..i-2]
105                  = needle[table[j]..j-1]
106                  = needle[0..j-1-table[j]]  (by definition of table[j]).  */
107             j = j - table[j];
108           }
109         /* Here: j = i - table[i].  */
110       }
111   }
112
113   /* Search, using the table to accelerate the processing.  */
114   {
115     size_t j;
116     const UNIT *rhaystack;
117     const UNIT *phaystack;
118
119     *resultp = NULL;
120     j = 0;
121     rhaystack = haystack;
122     phaystack = haystack;
123     /* Invariant: phaystack = rhaystack + j.  */
124     while (*phaystack != 0)
125       if (CANON_ELEMENT (needle[j]) == CANON_ELEMENT (*phaystack))
126         {
127           j++;
128           phaystack++;
129           if (j == m)
130             {
131               /* The entire needle has been found.  */
132               *resultp = rhaystack;
133               break;
134             }
135         }
136       else if (j > 0)
137         {
138           /* Found a match of needle[0..j-1], mismatch at needle[j].  */
139           rhaystack += table[j];
140           j -= table[j];
141         }
142       else
143         {
144           /* Found a mismatch at needle[0] already.  */
145           rhaystack++;
146           phaystack++;
147         }
148   }
149
150   freea (table);
151   return true;
152 }
153
154 #undef CANON_ELEMENT