Unify 5 copies of the KMP code.
[gnulib.git] / lib / str-kmp.h
1 /* Substring search in a NUL terminated string of 'char' elements,
2    using the Knuth-Morris-Pratt algorithm.
3    Copyright (C) 2005-2007 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      CANON_ELEMENT(c)        A macro that canonicalizes an element right after
22                              it has been fetched from one of the two strings.
23                              The argument is an 'unsigned char'; the result
24                              must be an 'unsigned char' as well.  */
25
26 /* Knuth-Morris-Pratt algorithm.
27    See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
28    Return a boolean indicating success.  */
29 static bool
30 knuth_morris_pratt_unibyte (const char *haystack, const char *needle,
31                             const char **resultp)
32 {
33   size_t m = strlen (needle);
34
35   /* Allocate the table.  */
36   size_t *table = (size_t *) nmalloca (m, sizeof (size_t));
37   if (table == NULL)
38     return false;
39   /* Fill the table.
40      For 0 < i < m:
41        0 < table[i] <= i is defined such that
42        forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
43        and table[i] is as large as possible with this property.
44      This implies:
45      1) For 0 < i < m:
46           If table[i] < i,
47           needle[table[i]..i-1] = needle[0..i-1-table[i]].
48      2) For 0 < i < m:
49           rhaystack[0..i-1] == needle[0..i-1]
50           and exists h, i <= h < m: rhaystack[h] != needle[h]
51           implies
52           forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
53      table[0] remains uninitialized.  */
54   {
55     size_t i, j;
56
57     /* i = 1: Nothing to verify for x = 0.  */
58     table[1] = 1;
59     j = 0;
60
61     for (i = 2; i < m; i++)
62       {
63         /* Here: j = i-1 - table[i-1].
64            The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
65            for x < table[i-1], by induction.
66            Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
67         unsigned char b = CANON_ELEMENT ((unsigned char) needle[i - 1]);
68
69         for (;;)
70           {
71             /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
72                is known to hold for x < i-1-j.
73                Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1].  */
74             if (b == CANON_ELEMENT ((unsigned char) needle[j]))
75               {
76                 /* Set table[i] := i-1-j.  */
77                 table[i] = i - ++j;
78                 break;
79               }
80             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
81                for x = i-1-j, because
82                  needle[i-1] != needle[j] = needle[i-1-x].  */
83             if (j == 0)
84               {
85                 /* The inequality holds for all possible x.  */
86                 table[i] = i;
87                 break;
88               }
89             /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
90                for i-1-j < x < i-1-j+table[j], because for these x:
91                  needle[x..i-2]
92                  = needle[x-(i-1-j)..j-1]
93                  != needle[0..j-1-(x-(i-1-j))]  (by definition of table[j])
94                     = needle[0..i-2-x],
95                hence needle[x..i-1] != needle[0..i-1-x].
96                Furthermore
97                  needle[i-1-j+table[j]..i-2]
98                  = needle[table[j]..j-1]
99                  = needle[0..j-1-table[j]]  (by definition of table[j]).  */
100             j = j - table[j];
101           }
102         /* Here: j = i - table[i].  */
103       }
104   }
105
106   /* Search, using the table to accelerate the processing.  */
107   {
108     size_t j;
109     const char *rhaystack;
110     const char *phaystack;
111
112     *resultp = NULL;
113     j = 0;
114     rhaystack = haystack;
115     phaystack = haystack;
116     /* Invariant: phaystack = rhaystack + j.  */
117     while (*phaystack != '\0')
118       if (CANON_ELEMENT ((unsigned char) needle[j])
119           == CANON_ELEMENT ((unsigned char) *phaystack))
120         {
121           j++;
122           phaystack++;
123           if (j == m)
124             {
125               /* The entire needle has been found.  */
126               *resultp = rhaystack;
127               break;
128             }
129         }
130       else if (j > 0)
131         {
132           /* Found a match of needle[0..j-1], mismatch at needle[j].  */
133           rhaystack += table[j];
134           j -= table[j];
135         }
136       else
137         {
138           /* Found a mismatch at needle[0] already.  */
139           rhaystack++;
140           phaystack++;
141         }
142   }
143
144   freea (table);
145   return true;
146 }
147
148 #undef CANON_ELEMENT