1 /* Test of searching in a string.
2 Copyright (C) 2007-2008 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2007. */
27 #define ASSERT(expr) \
32 fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \
43 const char input[] = "foo";
44 const char *result = c_strstr (input, "");
45 ASSERT (result == input);
49 const char input[] = "foo";
50 const char *result = c_strstr (input, "o");
51 ASSERT (result == input + 1);
55 const char input[] = "ABC ABCDAB ABCDABCDABDE";
56 const char *result = c_strstr (input, "ABCDABD");
57 ASSERT (result == input + 15);
61 const char input[] = "ABC ABCDAB ABCDABCDABDE";
62 const char *result = c_strstr (input, "ABCDABE");
63 ASSERT (result == NULL);
66 /* Check that a very long haystack is handled quickly if the needle is
67 short and occurs near the beginning. */
69 size_t repeat = 10000;
72 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
73 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
74 char *haystack = (char *) malloc (m + 1);
77 memset (haystack, 'A', m);
81 for (; repeat > 0; repeat--)
83 ASSERT (c_strstr (haystack, needle) == haystack + 1);
90 /* Check that a very long needle is discarded quickly if the haystack is
93 size_t repeat = 10000;
96 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
97 "ABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABAB";
98 char *needle = (char *) malloc (m + 1);
101 memset (needle, 'A', m);
104 for (; repeat > 0; repeat--)
106 ASSERT (c_strstr (haystack, needle) == NULL);
113 /* Check that the asymptotic worst-case complexity is not quadratic. */
116 char *haystack = (char *) malloc (2 * m + 2);
117 char *needle = (char *) malloc (m + 2);
118 if (haystack != NULL && needle != NULL)
122 memset (haystack, 'A', 2 * m);
123 haystack[2 * m] = 'B';
124 haystack[2 * m + 1] = '\0';
126 memset (needle, 'A', m);
128 needle[m + 1] = '\0';
130 result = c_strstr (haystack, needle);
131 ASSERT (result == haystack + m);